Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(app): preserve the current local Jarvis runtime and interface
rubenluetke10-beep4c1e930f31d5
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex f741facd1d..c3502bac34 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -791,6 +791,7 @@ jobs:- name: Blocking provider-neutral realtime contractrun: >-python -m pytest+ tests/contract/test_gpt_live.pytests/contract/test_realtime_provider_contract.pytests/contract/test_realtime_reliability_gate.py-q -p no:cacheprovider@@ -827,6 +828,7 @@ jobs:- name: Blocking headless realtime degradation contractrun: >-python -m pytest+ tests/contract/test_gpt_live.pytests/contract/test_realtime_provider_contract.pytests/contract/test_realtime_reliability_gate.py-q -p no:cacheproviderdiff --git a/art/studies/agent-symbol-companions/brief.md b/art/studies/agent-symbol-companions/brief.mdnew file mode 100644index 0000000000..fc5ddc8fc1--- /dev/null+++ b/art/studies/agent-symbol-companions/brief.md@@ -0,0 +1,32 @@+# Agent profile companions++Use the seven existing, accepted flat profile shapes as small companions that+follow the independently configurable agent character. Profile and companion+share shape, colour and eyes. Preserve character recipes, imported bodies and+wardrobe choices. Gigi keeps the existing graphite-and-gold first-party identity.++The bodies retain the SVG silhouettes with a modest rounded extrusion, plain+PBR materials, two eyes and no human facial features. Blender is the editable+mesh source. No image model, external texture, provider request or task/audio+authority is introduced. The runtime target is the current Three.js map.++Runtime size is fixed at 0.50 metres, with a standard 1 metre following distance. Each pet+uses the existing canvas and a cached model; only its materials and transform+belong to the instance. Follow actual route breadcrumbs around corners. Freeze+on stale/hidden presentation and retain existing context recovery. Reduced+motion removes the small walking bob, while deliberate following remains usable.++Rebuild authoring input with `node scripts/art/capture_companion_shapes.mjs`,+then `python scripts/art/sample_companion_outlines.py`. Run+`scripts/art/build_agent_companions.py` inside background Blender. The manifest+exporter can regenerate the GLB from `source/companions.blend`; its named export+collection is `Collection`. The Gigi master uses `GigiExport`.++The seven-symbol GLB targets less than 1 MB, no external dependencies, and at+most five visible meshes per instance. Check normal and close map views, the+editor, small profile sizes, both application themes and path turns. Record+measured evidence rather than asserting performance from file size.++This is one matching companion family. It does not approve redesigns of the+map, characters, buildings or vehicles. Further unrelated art-family rollout+retains the project's reference-review gate.diff --git a/art/studies/agent-symbol-companions/exports/companions.glb b/art/studies/agent-symbol-companions/exports/companions.glbnew file mode 100644index 0000000000..2cbd01136eBinary files /dev/null and b/art/studies/agent-symbol-companions/exports/companions.glb differdiff --git a/art/studies/agent-symbol-companions/exports/gigi.glb b/art/studies/agent-symbol-companions/exports/gigi.glbnew file mode 100644index 0000000000..ae096d4ce1Binary files /dev/null and b/art/studies/agent-symbol-companions/exports/gigi.glb differdiff --git a/art/studies/agent-symbol-companions/review.md b/art/studies/agent-symbol-companions/review.mdnew file mode 100644index 0000000000..cc1779ee05--- /dev/null+++ b/art/studies/agent-symbol-companions/review.md@@ -0,0 +1,8 @@+# Reference review++Decision: pending.++Separate visual judgement from technical results. Record defects and revisions.+After actual user approval, record its date, scope and an English summary here;+keep private conversation content and personal identifiers outside the repository.+A passing check or an agent's own opinion is not user approval.diff --git a/art/studies/agent-symbol-companions/source/outlines.json b/art/studies/agent-symbol-companions/source/outlines.jsonnew file mode 100644index 0000000000..9f43b94315--- /dev/null+++ b/art/studies/agent-symbol-companions/source/outlines.json@@ -0,0 +1 @@+{"circle":[[36.2,20],[36.16875,21.00574],[36.07211,22.03162],[35.9061,23.07181],[35.66742,24.11972],[35.35352,25.16811],[34.97057,26.19049],[34.54214,27.13906],[34.0481,28.06789],[33.48975,28.97032],[32.86929,29.83979],[32.18978,30.67002],[31.45513,31.45513],[30.67002,32.18977],[29.83979,32.86929],[28.97032,33.48975],[28.06789,34.0481],[27.13906,34.54214],[26.19049,34.97057],[25.16811,35.35352],[24.11972,35.66742],[23.07181,35.9061],[22.03162,36.0721],[21.00574,36.16875],[20,36.2],[18.99426,36.16875],[17.96838,36.0721],[16.92819,35.9061],[15.88029,35.66742],[14.83189,35.35352],[13.80951,34.97057],[12.86094,34.54214],[11.93211,34.0481],[11.02969,33.48975],[10.16021,32.86929],[9.32998,32.18978],[8.54487,31.45513],[7.81023,30.67003],[7.13072,29.83979],[6.51025,28.97032],[5.9519,28.06789],[5.45786,27.13906],[5.02944,26.19049],[4.64648,25.16811],[4.33259,24.11972],[4.0939,23.07181],[3.9279,22.03163],[3.83125,21.00575],[3.8,20.00001],[3.83125,18.99426],[3.9279,17.96838],[4.0939,16.9282],[4.33258,15.88029],[4.64648,14.83189],[5.02943,13.80951],[5.45786,12.86094],[5.95189,11.93212],[6.51024,11.02969],[7.13071,10.16021],[7.81022,9.32998],[8.54486,8.54488],[9.32997,7.81023],[10.1602,7.13072],[11.02968,6.51025],[11.93211,5.9519],[12.86094,5.45786],[13.80951,5.02944],[14.83188,4.64648],[15.88028,4.33259],[16.92818,4.0939],[17.96838,3.9279],[18.99426,3.83125],[20,3.8],[21.00574,3.83125],[22.03162,3.9279],[23.0718,4.0939],[24.11972,4.33258],[25.1681,4.64648],[26.19049,5.02943],[27.13905,5.45786],[28.06789,5.9519],[28.97031,6.51024],[29.83978,7.13071],[30.67002,7.81022],[31.45512,8.54486],[32.18977,9.32997],[32.86928,10.1602],[33.48975,11.02968],[34.0481,11.93211],[34.54214,12.86094],[34.97056,13.80951],[35.35352,14.83189],[35.66742,15.88028],[35.9061,16.92819],[36.0721,17.96838],[36.16875,18.99426]],"squircle":[[20,3.8],[21.21198,3.8],[22.42395,3.8],[23.63593,3.8],[24.84782,3.81203],[26.05968,3.82901],[27.27058,3.87938],[28.48108,3.9356],[29.68195,4.09936],[30.88146,4.26834],[32.01112,4.70738],[33.14078,5.14642],[34,6],[34.85358,6.85923],[35.29263,7.98889],[35.73167,9.11855],[35.90065,10.31806],[36.0644,11.51892],[36.12062,12.72943],[36.17098,13.94033],[36.18797,15.15219],[36.2,16.36408],[36.2,17.57606],[36.2,18.78803],[36.2,20.00001],[36.2,21.21199],[36.2,22.42396],[36.2,23.63594],[36.18797,24.84783],[36.17098,26.05969],[36.12062,27.27059],[36.0644,28.4811],[35.90064,29.68196],[35.73166,30.88147],[35.29262,32.01113],[34.85358,33.14079],[33.99999,34.00001],[33.14077,34.85359],[32.0111,35.29263],[30.88144,35.73167],[29.68193,35.90065],[28.48107,36.0644],[27.27057,36.12062],[26.05966,36.17099],[24.84781,36.18797],[23.63592,36.2],[22.42394,36.2],[21.21196,36.2],[19.99999,36.2],[18.78801,36.2],[17.57603,36.2],[16.36405,36.2],[15.15216,36.18797],[13.94031,36.17098],[12.7294,36.12062],[11.5189,36.0644],[10.31804,35.90064],[9.11853,35.73166],[7.98887,35.29262],[6.85921,34.85358],[5.99999,33.99999],[5.14641,33.14077],[4.70737,32.0111],[4.26833,30.88144],[4.09935,29.68193],[3.9356,28.48107],[3.87938,27.27057],[3.82901,26.05967],[3.81203,24.84781],[3.8,23.63592],[3.8,22.42393],[3.8,21.21196],[3.8,19.99999],[3.8,18.78801],[3.8,17.57604],[3.8,16.36406],[3.81203,15.15217],[3.82901,13.94031],[3.87938,12.72941],[3.9356,11.51891],[4.09936,10.31805],[4.26834,9.11854],[4.70738,7.98888],[5.14642,6.85922],[6.00001,5.99999],[6.85923,5.14641],[7.98889,4.70737],[9.11855,4.26834],[10.31806,4.09936],[11.51892,3.9356],[12.72942,3.87938],[13.94033,3.82901],[15.15218,3.81203],[16.36407,3.8],[17.57605,3.8],[18.78802,3.8]],"pill":[[20,8.48],[21.07003,8.48],[22.14006,8.48],[23.21009,8.48],[24.28012,8.48],[25.35014,8.48],[26.42017,8.48195],[27.49018,8.48758],[28.56015,8.49825],[29.63008,8.5127],[30.69827,8.56351],[31.76469,8.65133],[32.8228,8.77314],[33.80947,9.18719],[34.79614,9.60124],[35.32128,10.48592],[35.7545,11.46433],[35.90157,12.51256],[35.96774,13.58055],[35.99335,14.64988],[35.9984,15.71989],[36,16.78992],[36,17.85995],[36,18.92998],[36,20.00001],[36,21.07003],[36,22.14006],[36,23.21009],[35.9984,24.28012],[35.99335,25.35013],[35.96773,26.41947],[35.90157,27.48745],[35.7545,28.53568],[35.32127,29.51409],[34.79613,30.39877],[33.80946,30.81281],[32.82279,31.22687],[31.76467,31.34867],[30.69826,31.4365],[29.63007,31.4873],[28.56014,31.50175],[27.49017,31.51242],[26.42016,31.51805],[25.35013,31.52],[24.2801,31.52],[23.21008,31.52],[22.14005,31.52],[21.07002,31.52],[19.99999,31.52],[18.92996,31.52],[17.85994,31.52],[16.78991,31.52],[15.71988,31.52],[14.64985,31.52],[13.57983,31.51805],[12.50981,31.51242],[11.43985,31.50175],[10.36992,31.4873],[9.30173,31.43649],[8.23531,31.34867],[7.1772,31.22686],[6.19053,30.81281],[5.20385,30.39876],[4.67872,29.51407],[4.24549,28.53567],[4.09843,27.48744],[4.03227,26.41946],[4.00665,25.35013],[4.0016,24.28011],[4,23.21008],[4,22.14006],[4,21.07003],[4,20],[4,18.92997],[4,17.85994],[4,16.78992],[4.0016,15.7199],[4.00665,14.64988],[4.03227,13.58055],[4.09843,12.51256],[4.24549,11.46433],[4.67872,10.48593],[5.20386,9.60124],[6.19053,9.18719],[7.1772,8.77314],[8.23531,8.65133],[9.30173,8.56351],[10.36992,8.5127],[11.43986,8.49825],[12.50982,8.48758],[13.57983,8.48195],[14.64986,8.48],[15.71989,8.48],[16.78992,8.48],[17.85994,8.48],[18.92997,8.48]],"triangle":[[20,5.5],[20.49871,6.37275],[20.99743,7.2455],[21.49614,8.11824],[21.99485,8.99099],[22.49356,9.86374],[22.99228,10.73649],[23.49099,11.60923],[23.9897,12.48198],[24.48841,13.35473],[24.98713,14.22748],[25.48584,15.10023],[25.98455,15.97297],[26.48327,16.84572],[26.98198,17.71847],[27.48069,18.59122],[27.97941,19.46396],[28.47812,20.33671],[28.97683,21.20946],[29.47555,22.08221],[29.97426,22.95496],[30.47297,23.8277],[30.97169,24.70045],[31.4704,25.5732],[31.96911,26.44595],[32.46782,27.31869],[32.96654,28.19144],[33.46525,29.06419],[33.96396,29.93694],[34.46268,30.80968],[34.96139,31.68243],[35.4601,32.55518],[35.95882,33.42793],[35.07782,33.5],[34.07264,33.5],[33.06745,33.5],[32.06226,33.5],[31.05707,33.5],[30.05188,33.5],[29.04669,33.5],[28.0415,33.5],[27.03632,33.5],[26.03113,33.5],[25.02594,33.5],[24.02075,33.5],[23.01556,33.5],[22.01038,33.5],[21.00519,33.5],[20,33.5],[18.99481,33.5],[17.98962,33.5],[16.98444,33.5],[15.97925,33.5],[14.97406,33.5],[13.96887,33.5],[12.96368,33.5],[11.9585,33.5],[10.95331,33.5],[9.94812,33.5],[8.94293,33.5],[7.93774,33.5],[6.93255,33.5],[5.92736,33.5],[4.92218,33.5],[4.04118,33.42793],[4.5399,32.55518],[5.03861,31.68243],[5.53732,30.80968],[6.03603,29.93694],[6.53475,29.06419],[7.03346,28.19144],[7.53217,27.3187],[8.03089,26.44594],[8.5296,25.57319],[9.02831,24.70045],[9.52703,23.8277],[10.02574,22.95495],[10.52445,22.0822],[11.02317,21.20946],[11.52188,20.33671],[12.02059,19.46396],[12.51931,18.59121],[13.01802,17.71847],[13.51673,16.84572],[14.01544,15.97297],[14.51416,15.10022],[15.01287,14.22748],[15.51158,13.35473],[16.0103,12.48198],[16.50901,11.60923],[17.00772,10.73648],[17.50644,9.86374],[18.00515,8.99099],[18.50386,8.11824],[19.00257,7.24549],[19.50129,6.37275]],"hexagon":[[20,3.5],[20.90294,4.01374],[21.80588,4.52749],[22.70882,5.04123],[23.61177,5.55497],[24.51471,6.06871],[25.41765,6.58246],[26.32059,7.0962],[27.22353,7.60994],[28.12648,8.12368],[29.02942,8.63743],[29.93236,9.15117],[30.8353,9.66491],[31.73824,10.17865],[32.64119,10.6924],[33.54412,11.20614],[34.44707,11.71988],[34.5,12.72796],[34.5,13.76682],[34.5,14.80569],[34.5,15.84455],[34.5,16.88341],[34.5,17.92228],[34.5,18.96114],[34.5,20],[34.5,21.03886],[34.5,22.07772],[34.5,23.11659],[34.5,24.15545],[34.5,25.19431],[34.5,26.23318],[34.5,27.27204],[34.44707,28.28012],[33.54413,28.79386],[32.64118,29.3076],[31.73824,29.82134],[30.8353,30.33509],[29.93236,30.84883],[29.02942,31.36257],[28.12647,31.87632],[27.22354,32.39006],[26.32059,32.9038],[25.41765,33.41754],[24.51471,33.93129],[23.61177,34.44503],[22.70883,34.95877],[21.80588,35.47252],[20.90294,35.98626],[20,36.5],[19.09706,35.98626],[18.19412,35.47252],[17.29117,34.95877],[16.38823,34.44503],[15.48529,33.93129],[14.58235,33.41754],[13.67941,32.9038],[12.77646,32.39006],[11.87353,31.87632],[10.97058,31.36257],[10.06764,30.84883],[9.1647,30.33509],[8.26176,29.82134],[7.35882,29.3076],[6.45587,28.79386],[5.55293,28.28012],[5.5,27.27204],[5.5,26.23318],[5.5,25.19431],[5.5,24.15545],[5.5,23.11658],[5.5,22.07773],[5.5,21.03886],[5.5,20],[5.5,18.96114],[5.5,17.92227],[5.5,16.88342],[5.5,15.84455],[5.5,14.80569],[5.5,13.76682],[5.5,12.72796],[5.55293,11.71988],[6.45587,11.20614],[7.35882,10.6924],[8.26176,10.17865],[9.1647,9.66492],[10.06764,9.15117],[10.97058,8.63743],[11.87353,8.12368],[12.77647,7.60994],[13.67941,7.0962],[14.58235,6.58246],[15.48529,6.06871],[16.38823,5.55497],[17.29118,5.04123],[18.19411,4.52749],[19.09706,4.01374]],"cloud":[[11,32],[9.93788,31.89589],[8.90132,31.64204],[7.91159,31.24287],[6.98877,30.70685],[6.15121,30.04548],[5.41551,29.27238],[4.79659,28.40298],[4.30752,27.45446],[3.95876,26.44586],[3.75724,25.39787],[3.70534,24.33191],[3.80463,23.26934],[4.05444,22.2318],[4.44963,21.24047],[4.98151,20.31525],[5.63888,19.47453],[6.40849,18.73518],[7.27519,18.11249],[8.22177,17.61967],[9.229,17.26694],[9.93818,16.82808],[9.77295,15.77336],[9.72367,14.70693],[9.79178,13.64154],[9.97647,12.59007],[10.27514,11.56513],[10.68369,10.57882],[11.19688,9.64268],[11.80852,8.76768],[12.51156,7.96429],[13.29799,7.24231],[14.15874,6.61081],[15.08366,6.07768],[16.06149,5.64927],[17.08016,5.32981],[18.12727,5.12173],[19.19076,5.02847],[20.25806,5.05235],[21.31627,5.19333],[22.35266,5.44948],[23.35491,5.8172],[24.31127,6.29164],[25.21055,6.86698],[26.04211,7.53648],[26.79588,8.29249],[27.46246,9.12638],[28.03348,10.02839],[28.50196,10.98768],[28.86281,11.99243],[29.54203,12.48703],[30.60782,12.54873],[31.66044,12.72673],[32.68711,13.01937],[33.6754,13.42307],[34.61357,13.9325],[35.49067,14.54111],[36.29649,15.24137],[37.0215,16.025],[37.65696,16.88285],[38.19486,17.80499],[38.62832,18.78059],[38.95185,19.79795],[39.16179,20.84468],[39.2568,21.90803],[39.23682,22.97541],[39.10062,24.03425],[38.84891,25.07172],[38.4846,26.0752],[38.01251,27.03271],[37.43871,27.93297],[36.77045,28.76553],[36.0158,29.52066],[35.18357,30.1893],[34.28336,30.76317],[33.32566,31.2349],[32.32191,31.59843],[31.28429,31.84948],[30.22545,31.98582],[29.1578,32],[28.08969,32],[27.02159,32],[25.95348,32],[24.88538,32],[23.81727,32],[22.74916,32],[21.68106,32],[20.61295,32],[19.54485,32],[18.47674,32],[17.40864,32],[16.34053,32],[15.27242,32],[14.20432,32],[13.13622,32],[12.06811,32]],"drop":[[20,3],[19.34959,3.80533],[18.70669,4.61667],[18.06978,5.43273],[17.43839,6.25307],[16.81245,7.07757],[16.19193,7.90616],[15.57702,8.73892],[14.96794,9.57595],[14.36496,10.41739],[13.76836,11.26336],[13.17866,12.11416],[12.59636,12.97003],[12.02207,13.8313],[11.45652,14.69834],[10.9006,15.57158],[10.35538,16.45153],[9.82216,17.33881],[9.30257,18.23414],[8.79864,19.13837],[8.31291,20.05249],[7.84889,20.97783],[7.41114,21.91585],[7.00605,22.86842],[6.64297,23.83773],[6.33613,24.82619],[6.10879,25.83571],[6.00172,26.86442],[6.03056,27.8989],[6.14167,28.92783],[6.33405,29.9447],[6.60661,30.94307],[6.95748,31.91669],[7.38398,32.85964],[7.88283,33.7664],[8.45027,34.6319],[9.08224,35.45147],[9.77444,36.22086],[10.52237,36.93619],[11.32145,37.59392],[12.16694,38.1908],[13.05403,38.72391],[13.97777,39.19063],[14.9331,39.5887],[15.91486,39.91622],[16.91778,40.17176],[17.9365,40.35437],[18.96568,40.46371],[20.00002,40.5],[21.03435,40.46371],[22.06352,40.35437],[23.08224,40.17175],[24.08516,39.91621],[25.06692,39.58868],[26.02226,39.19062],[26.946,38.72389],[27.83308,38.19078],[28.67858,37.5939],[29.47765,36.93617],[30.22558,36.22084],[30.91777,35.45145],[31.54975,34.63187],[32.11719,33.76639],[32.61603,32.85962],[33.04253,31.91667],[33.39339,30.94305],[33.66596,29.94468],[33.85833,28.9278],[33.96945,27.89887],[33.99828,26.8644],[33.8912,25.83569],[33.66386,24.82617],[33.35702,23.83772],[32.99395,22.86841],[32.58886,21.91584],[32.15107,20.97783],[31.68709,20.05249],[31.20136,19.13836],[30.69742,18.23413],[30.17784,17.3388],[29.64462,16.45153],[29.09939,15.57158],[28.54347,14.69834],[27.97792,13.8313],[27.40363,12.97003],[26.82132,12.11416],[26.2316,11.26338],[25.63504,10.41738],[25.03206,9.57594],[24.42298,8.73891],[23.80806,7.90615],[23.18755,7.07757],[22.56161,6.25306],[21.93022,5.43273],[21.29331,4.61667],[20.65041,3.80533]]}diff --git a/art/studies/agent-symbol-companions/source/shapes.json b/art/studies/agent-symbol-companions/source/shapes.jsonnew file mode 100644index 0000000000..38cd2783a3--- /dev/null+++ b/art/studies/agent-symbol-companions/source/shapes.json@@ -0,0 +1,9 @@+{+ "circle": "<svg aria-hidden=\"true\" focusable=\"false\" data-agent-symbol=\"circle\" width=\"128\" height=\"128\" viewBox=\"0 0 40 44\" class=\"block h-full w-full\"><circle cx=\"20\" cy=\"20\" fill=\"#ffffff\" r=\"16.2\"></circle><g fill=\"#19171d\"><ellipse cx=\"15.4\" cy=\"17.2\" rx=\"2.2\" ry=\"2.3\"></ellipse><ellipse cx=\"24.6\" cy=\"17.2\" rx=\"2.2\" ry=\"2.3\"></ellipse></g><g fill=\"#ffffff\" opacity=\"0.85\"><circle cx=\"14.8\" cy=\"16.5\" r=\"0.65\"></circle><circle cx=\"24\" cy=\"16.5\" r=\"0.65\"></circle></g></svg>",+ "squircle": "<svg aria-hidden=\"true\" focusable=\"false\" data-agent-symbol=\"squircle\" width=\"128\" height=\"128\" viewBox=\"0 0 40 44\" class=\"block h-full w-full\"><path d=\"M20.00 3.80 L21.97 3.80 L23.99 3.80 L26.13 3.83 L28.44 3.93 L30.86 4.26 L33.15 5.15 L34.85 6.85 L35.74 9.14 L36.07 11.56 L36.17 13.87 L36.20 16.01 L36.20 18.03 L36.20 20.00 L36.20 21.97 L36.20 23.99 L36.17 26.13 L36.07 28.44 L35.74 30.86 L34.85 33.15 L33.15 34.85 L30.86 35.74 L28.44 36.07 L26.13 36.17 L23.99 36.20 L21.97 36.20 L20.00 36.20 L18.03 36.20 L16.01 36.20 L13.87 36.17 L11.56 36.07 L9.14 35.74 L6.85 34.85 L5.15 33.15 L4.26 30.86 L3.93 28.44 L3.83 26.13 L3.80 23.99 L3.80 21.97 L3.80 20.00 L3.80 18.03 L3.80 16.01 L3.83 13.87 L3.93 11.56 L4.26 9.14 L5.15 6.85 L6.85 5.15 L9.14 4.26 L11.56 3.93 L13.87 3.83 L16.01 3.80 L18.03 3.80Z\" fill=\"#ffffff\"></path><g fill=\"#19171d\"><ellipse cx=\"15.4\" cy=\"17.2\" rx=\"2.2\" ry=\"2.3\"></ellipse><ellipse cx=\"24.6\" cy=\"17.2\" rx=\"2.2\" ry=\"2.3\"></ellipse></g><g fill=\"#ffffff\" opacity=\"0.85\"><circle cx=\"14.8\" cy=\"16.5\" r=\"0.65\"></circle><circle cx=\"24\" cy=\"16.5\" r=\"0.65\"></circle></g></svg>",+ "pill": "<svg aria-hidden=\"true\" focusable=\"false\" data-agent-symbol=\"pill\" width=\"128\" height=\"128\" viewBox=\"0 0 40 44\" class=\"block h-full w-full\"><path d=\"M20.00 8.48 L21.40 8.48 L22.84 8.48 L24.37 8.48 L26.05 8.48 L27.95 8.49 L30.17 8.52 L32.72 8.73 L34.96 9.67 L35.85 11.68 L35.99 13.94 L36.00 16.06 L36.00 18.06 L36.00 20.00 L36.00 21.94 L36.00 23.94 L35.99 26.06 L35.85 28.32 L34.96 30.33 L32.72 31.27 L30.17 31.48 L27.95 31.51 L26.05 31.52 L24.37 31.52 L22.84 31.52 L21.40 31.52 L20.00 31.52 L18.60 31.52 L17.16 31.52 L15.63 31.52 L13.95 31.52 L12.05 31.51 L9.83 31.48 L7.28 31.27 L5.04 30.33 L4.15 28.32 L4.01 26.06 L4.00 23.94 L4.00 21.94 L4.00 20.00 L4.00 18.06 L4.00 16.06 L4.01 13.94 L4.15 11.68 L5.04 9.67 L7.28 8.73 L9.83 8.52 L12.05 8.49 L13.95 8.48 L15.63 8.48 L17.16 8.48 L18.60 8.48Z\" fill=\"#ffffff\"></path><g fill=\"#19171d\"><ellipse cx=\"15.4\" cy=\"17.2\" rx=\"2.2\" ry=\"2.3\"></ellipse><ellipse cx=\"24.6\" cy=\"17.2\" rx=\"2.2\" ry=\"2.3\"></ellipse></g><g fill=\"#ffffff\" opacity=\"0.85\"><circle cx=\"14.8\" cy=\"16.5\" r=\"0.65\"></circle><circle cx=\"24\" cy=\"16.5\" r=\"0.65\"></circle></g></svg>",+ "triangle": "<svg aria-hidden=\"true\" focusable=\"false\" data-agent-symbol=\"triangle\" width=\"128\" height=\"128\" viewBox=\"0 0 40 44\" class=\"block h-full w-full\"><path d=\"M20 5.5 L36 33.5 L4 33.5 Z\" fill=\"#ffffff\" stroke=\"#ffffff\" stroke-width=\"5\" stroke-linejoin=\"round\"></path><g fill=\"#19171d\"><ellipse cx=\"15.4\" cy=\"23\" rx=\"2.2\" ry=\"2.3\"></ellipse><ellipse cx=\"24.6\" cy=\"23\" rx=\"2.2\" ry=\"2.3\"></ellipse></g><g fill=\"#ffffff\" opacity=\"0.85\"><circle cx=\"14.8\" cy=\"22.3\" r=\"0.65\"></circle><circle cx=\"24\" cy=\"22.3\" r=\"0.65\"></circle></g></svg>",+ "hexagon": "<svg aria-hidden=\"true\" focusable=\"false\" data-agent-symbol=\"hexagon\" width=\"128\" height=\"128\" viewBox=\"0 0 40 44\" class=\"block h-full w-full\"><path d=\"M20 3.5 L34.5 11.75 L34.5 28.25 L20 36.5 L5.5 28.25 L5.5 11.75 Z\" fill=\"#ffffff\" stroke=\"#ffffff\" stroke-width=\"3\" stroke-linejoin=\"round\"></path><g fill=\"#19171d\"><ellipse cx=\"15.4\" cy=\"17.2\" rx=\"2.2\" ry=\"2.3\"></ellipse><ellipse cx=\"24.6\" cy=\"17.2\" rx=\"2.2\" ry=\"2.3\"></ellipse></g><g fill=\"#ffffff\" opacity=\"0.85\"><circle cx=\"14.8\" cy=\"16.5\" r=\"0.65\"></circle><circle cx=\"24\" cy=\"16.5\" r=\"0.65\"></circle></g></svg>",+ "cloud": "<svg aria-hidden=\"true\" focusable=\"false\" data-agent-symbol=\"cloud\" width=\"128\" height=\"128\" viewBox=\"0 0 40 44\" class=\"block h-full w-full\"><path d=\"M11 32 a7.5 7.5 0 0 1 -1 -14.9 A9.5 9.5 0 0 1 29 12.5 A7 7 0 0 1 30 32 Z\" fill=\"#ffffff\"></path><g fill=\"#19171d\"><ellipse cx=\"15.4\" cy=\"23\" rx=\"2.2\" ry=\"2.3\"></ellipse><ellipse cx=\"24.6\" cy=\"23\" rx=\"2.2\" ry=\"2.3\"></ellipse></g><g fill=\"#ffffff\" opacity=\"0.85\"><circle cx=\"14.8\" cy=\"22.3\" r=\"0.65\"></circle><circle cx=\"24\" cy=\"22.3\" r=\"0.65\"></circle></g></svg>",+ "drop": "<svg aria-hidden=\"true\" focusable=\"false\" data-agent-symbol=\"drop\" width=\"128\" height=\"128\" viewBox=\"0 0 40 44\" class=\"block h-full w-full\"><path d=\"M20 3 C20 3 6 20 6 27 a14 13.5 0 0 0 28 0 C34 20 20 3 20 3 Z\" fill=\"#ffffff\"></path><g fill=\"#19171d\"><ellipse cx=\"15.4\" cy=\"25\" rx=\"2.2\" ry=\"2.3\"></ellipse><ellipse cx=\"24.6\" cy=\"25\" rx=\"2.2\" ry=\"2.3\"></ellipse></g><g fill=\"#ffffff\" opacity=\"0.85\"><circle cx=\"14.8\" cy=\"24.3\" r=\"0.65\"></circle><circle cx=\"24\" cy=\"24.3\" r=\"0.65\"></circle></g></svg>"+}diff --git a/art/studies/agent-symbol-companions/study.json b/art/studies/agent-symbol-companions/study.jsonnew file mode 100644index 0000000000..e29986cb87--- /dev/null+++ b/art/studies/agent-symbol-companions/study.json@@ -0,0 +1,32 @@+{+ "schema": 1,+ "study": "agent-symbol-companions",+ "brief": "brief.md",+ "assets": [+ {+ "id": "symbols",+ "kind": "character",+ "source": "source/companions.blend",+ "collection": "Collection",+ "export": "exports/companions.glb"+ },+ {+ "id": "gigi",+ "kind": "character",+ "source": "source/gigi-reference.blend",+ "collection": "GigiExport",+ "export": "exports/gigi.glb"+ }+ ],+ "runtime_evidence": [+ "evidence/map-follow-first.png",+ "evidence/map-follow-second.png",+ "evidence/edit-companion.png"+ ],+ "technical_report": "evidence/technical-review.md",+ "approval": {+ "status": "pending",+ "record": "review.md",+ "evidence_sha256": ""+ }+}diff --git a/art/studies/gigi-hover-companion/.gitignore b/art/studies/gigi-hover-companion/.gitignorenew file mode 100644index 0000000000..2384deb661--- /dev/null+++ b/art/studies/gigi-hover-companion/.gitignore@@ -0,0 +1,3 @@+source/*.blend1+source/*.blend2+references/*.pngdiff --git a/art/studies/gigi-hover-companion/brief.md b/art/studies/gigi-hover-companion/brief.mdnew file mode 100644index 0000000000..c9cbe66082--- /dev/null+++ b/art/studies/gigi-hover-companion/brief.md@@ -0,0 +1,67 @@+# Gigi hover companion++## Authorized outcome++Implement the user-supplied companion brief in full: editable Blender master,+optimized GLB, optional in-world assistant, real task/audio presentation,+collision-aware following and navigation, and a consistent family of active+Gigi marks and platform icons. The specific runtime model requires user review+before broad brand replacement. This study is not approval of the Mars world,+worker design or any replacement of stored agent identities.++## Reference interpretation++The user supplied the black/yellow multi-view character sheet for this work.+It is an art-direction input, not a runtime texture. No external stock assets+are used in the model. Preserve rounded graphite housing, yellow eyes with+pupils, a small mouth, sensor pods, small arms and a continuous toothed hem.+Resolve contradictory body-symbol tiles by omitting all body emblems. The+separate Jarvis wordmark is outside this redesign. Rear service panel and+underside emitter are authored consistently from the same closed geometry.++## Scale, material and budget targets++- Nominal body height: 0.40 metres; glTF Y up, +Z forward, bottom-centred pivot.+- Model and animation names are stable, prefixed `Gigi.`. Blender master uses+ -Y forward/Z up; the manifest exporter performs the axis conversion once.+- Graphite alloy with roughness, fitted dark face lens, subdued metal trim and+ yellow PBR emissive accents. No Blender-only shader is assumed to export.+- Review at standard player view, close focus and world overview. Report+ actual viewport, FOV, distance and projected body height from that renderer.+- Provisional desktop asset budget: 1 MB GLB, 40 draw calls, 40k triangles,+ no external texture fetches. These are companion budgets, not world totals.+- Desktop target: current Windows renderer plus portable browser implementation;+ Linux/macOS runtime and resource tests remain required and unverified.+- Reduced motion removes ambient hover/blink; deliberate following stays usable.++## Ownership and integration++Gigi work owns `scripts/art/build_gigi_companion.py`, this study and+`components/society/companion/`. The Mars task owns the new world and+`MarsScene.tsx`/`MarsWorldStage.tsx`; local wiring is submitted as a separate+integration patch against its checkpoint, not written into its working tree.+World scale, colliders, ground, navigation/vehicle anchors and player pose are+injected. The existing assistant/chat/audio stack owns logical execution.++RUB-82 tracks Gigi branding alongside independent signage. RUB-81 owns normal+workers; its current capsule is only a scale proxy, never an approved figure.+RUB-69 owns the Outpost and final world integration.++## Full delivery sequence and pending acceptance++1. Inventory active and historical uses, preserve recipes and unrelated changes.+2. Author master, closed geometry, expressions and reproducible early export.+3. Show the actual runtime alongside a regular worker, at the Outpost and station,+ and at normal/close/overview distances. Compare small platform icon proposals.+4. Finish follow/run/turn, door/ceiling/bridge/interior, approach/guide/dock,+ collision, recall, user/agent attention and rover transitions.+5. Map authoritative audio/task/approval/error/completion states; verify mute,+ interruption and cancellation. Do not derive success from animation.+6. Prove optional presence, persistence, world/context isolation, two clients,+ no duplicate task/audio processes, reopen/resync, missing model and WebGL loss.+7. After specific visual approval, replace active Gigi assets and their recipes,+ including icon sizes 16/24/32/48, native variants, web marks and marketing uses.+8. Verify light/dark appearance, real performance before/after, required platform+ checks, reproducible sources, scoped commits and integration evidence.++No step is complete merely because this checklist or a placeholder exists.diff --git a/art/studies/gigi-hover-companion/exports/gigi-mark.svg b/art/studies/gigi-hover-companion/exports/gigi-mark.svgnew file mode 100644index 0000000000..32227f96d1--- /dev/null+++ b/art/studies/gigi-hover-companion/exports/gigi-mark.svg@@ -0,0 +1,23 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128" role="img" aria-label="Gigi companion mark proposal">+ <g stroke="#ffc83d" stroke-width="2.5" stroke-linejoin="round">+ <ellipse cx="22" cy="58" rx="8" ry="13" fill="#292c32"/>+ <ellipse cx="106" cy="58" rx="8" ry="13" fill="#292c32"/>+ <path d="M25 51C25 0 103 0 103 51V108L90 117L77 106L64 117L51 106L38 117L25 108Z" fill="#20242b"/>+ </g>+ <path d="M29 53C29 7 99 7 99 53V68H29Z" fill="#0d1118"/>+ <path d="M27 72H101" stroke="#c49938" stroke-width="1.5"/>+ <g fill="#ffcf45">+ <ellipse cx="48" cy="53" rx="9" ry="13"/>+ <ellipse cx="80" cy="53" rx="9" ry="13"/>+ <rect x="17" y="51" width="3" height="14" rx="1.5"/>+ <rect x="108" y="51" width="3" height="14" rx="1.5"/>+ <path d="M24 79Q13 92 20 100Q25 100 27 86Z"/>+ <path d="M104 79Q115 92 108 100Q103 100 101 86Z"/>+ </g>+ <g fill="#070a10">+ <ellipse cx="49" cy="56" rx="4" ry="8"/>+ <ellipse cx="81" cy="56" rx="4" ry="8"/>+ </g>+ <g fill="#fff7dd"><circle cx="51" cy="46" r="2.3"/><circle cx="83" cy="46" r="2.3"/></g>+ <ellipse cx="64" cy="84" rx="4" ry="6" fill="none" stroke="#ffcf45" stroke-width="2"/>+</svg>diff --git a/art/studies/gigi-hover-companion/exports/gigi.glb b/art/studies/gigi-hover-companion/exports/gigi.glbnew file mode 100644index 0000000000..ae096d4ce1Binary files /dev/null and b/art/studies/gigi-hover-companion/exports/gigi.glb differdiff --git a/art/studies/gigi-hover-companion/inventory.md b/art/studies/gigi-hover-companion/inventory.mdnew file mode 100644index 0000000000..362777e10c--- /dev/null+++ b/art/studies/gigi-hover-companion/inventory.md@@ -0,0 +1,30 @@+# Gigi usage and migration audit++Status: reference implementation in progress; no visual-family rollout approved.+The source inventory is captured separately in `usage-paths.txt`.++| Surface | Source and generated uses | Migration boundary |+| --- | --- | --- |+| 3D spirit recipe | `scripts/figures/gigi_builder.py`, `sources/gigi-mascot.json`, figure `contract.json`, `build_figures.py`, frontend `figures/catalog.json`, `figureRegistry.ts`, `assembleFigure.ts`, `assets/society/figures/spirit-gigi.glb` | Preserve existing `spirit/gigi` recipe IDs and user selections. Companion uses an independent asset, not the lead entity. Legacy presentation replacement needs the visual gate. |+| Society lead | `jarvis/society/runtime.py` lead avatar and frontend `society/data.ts` default spirit recipe | Do not delete or recreate lead, missions or saved configuration. Worker presentation is RUB-81; Gigi presence is separate. |+| Deck 3D | `components/deck/room/GigiFigure.tsx` | Replace SVG extrusion only after the new reference passes review; preserve existing press callback and resource lifecycle. |+| Animated 2D mascot | `MascotGigi.tsx`, `JarvisOrb.tsx`, `DeckOrb.tsx`, `JarvisDock.tsx`, onboarding, home greeting, overlays | Current pixel details and monochrome material must be migrated to the new simplified shape; keep all functional handlers. |+| App mark | `GigiMark.tsx`, `src/assets/jarvis-mark.png`, sidebar, top bar, composer, share card | Preserve imported fingerprinted URL; do not replace with a fixed cached public path. |+| Native icons | `scripts/make_gigi_app_icon.py`, `assets/icons/jarvis-gigi-256.png`, public PNG/ICO, `jarvis/assets/__init__.py`, `jarvis/ui/overlay_styles.py` | New icon generator must replace old geometry sources as well as outputs. Check actual 16/24/32/48 sizes and native monochrome variants. |+| Splash and favicon | frontend `index.html`, `public/jarvis-gigi.ico`, public PNG and built `dist` | Rebuild from approved sources; stage only this work's generated bundle in coordinated landing. |+| Style rules | `docs/BRAND.md`, frontend `index.css`, overlay styles | Gigi-specific black/white mandate conflicts with new direction. Update that exception during approved rollout; retain neutral UI and independent wordmark rules. |+| Website | `personaljarvisweb/src/components/mark/gigi.ts`, `TurningMark.tsx` | Read nested instructions before editing. Replacement delivery does not prove external publication. |+| Marketing/history | `wiki-video/public/gigi.svg`, `wiki-video/src/components/Ghost.tsx`, `assets/brand/social-preview.html`, `video/public/jarvis-gigi.png`, `videos/agent-mode-launch/assets/gigi.png` | Determine active template vs completed production. Preserve historical recordings/screenshots; supply reviewed replacements for active templates. |+| Regression checks | `tests/test_app_icon.py`, mascot tests, figure registry tests, onboarding/deck/sidebar tests | Update shape assertions with approved source; retain behavior/identity checks. |++## Initial findings++The existing spirit model is explicitly a pixel-ghost extrusion; its source+marks are white. The native icon generator deliberately derives from the same+old mascot geometry. Replacing only a PNG or GLB would be reverted by the next+asset build. The app mark already uses Vite fingerprinting correctly.++The new Mars runtime currently has a capsule player and unfinished Outpost+reference. Actual final-worker, rover and station docking acceptance cannot be+claimed from that foundation. Gigi work continues independently while those+world contracts are completed by their owner.diff --git a/art/studies/gigi-hover-companion/references/manifest.json b/art/studies/gigi-hover-companion/references/manifest.jsonnew file mode 100644index 0000000000..beb0b97ab2--- /dev/null+++ b/art/studies/gigi-hover-companion/references/manifest.json@@ -0,0 +1,11 @@+{+ "id": "gigi-character-sheet",+ "file": "gigi-character-sheet.png",+ "sha256": "2221c2e5d47ca70dece48422ccd631900c2950bfdbc083446685d99885061450",+ "dimensions": [+ 1448,+ 1086+ ],+ "provenance": "user supplied for this implementation",+ "redistribution": "reference retained locally; not published"+}diff --git a/art/studies/gigi-hover-companion/review.md b/art/studies/gigi-hover-companion/review.mdnew file mode 100644index 0000000000..cc1779ee05--- /dev/null+++ b/art/studies/gigi-hover-companion/review.md@@ -0,0 +1,8 @@+# Reference review++Decision: pending.++Separate visual judgement from technical results. Record defects and revisions.+After actual user approval, record its date, scope and an English summary here;+keep private conversation content and personal identifiers outside the repository.+A passing check or an agent's own opinion is not user approval.diff --git a/art/studies/gigi-hover-companion/source/README.md b/art/studies/gigi-hover-companion/source/README.mdnew file mode 100644index 0000000000..182933acb0--- /dev/null+++ b/art/studies/gigi-hover-companion/source/README.md@@ -0,0 +1,25 @@+# Editable master and export recipe++Author with Blender 5.0.1 (the exact build is in `build-report.json`):++```text+blender --background --factory-startup --disable-autoexec --python scripts/art/build_gigi_companion.py+blender --background --factory-startup --disable-autoexec --python scripts/art/export_study.py -- --manifest art/studies/gigi-hover-companion/study.json --asset gigi-companion+```++Run at the repository root. Keep `gigi.blend`, the builder and manifest together.+The builder scrubs file-browser, render and packed-image path fields including+their fixed-size unused tails, saves uncompressed, scans the complete serialized+file and reopens it with UI data for field validation. Do not enable source+compression without adding an actual decompression-aware privacy validator.+`GigiExport` owns the model; studio lights/camera stay outside that collection.+The editable eyes include blink animation sources; runtime expression control+uses the named eye/mouth/arm hierarchy. It never runs a walking animation.++The exported material recipe uses standard glTF metallic/roughness and emissive+values, without external textures. Surface detail and additional authored+expressions remain review work. No paid generation service or third-party mesh+is required to rebuild. Imported user concept art is a reference only.++Runtime loader names are sanitized by Three.js; original `Gigi.*` names remain+in `object.userData.name` and are used for expression binding.diff --git a/art/studies/gigi-hover-companion/source/build-report.json b/art/studies/gigi-hover-companion/source/build-report.jsonnew file mode 100644index 0000000000..7435c44121--- /dev/null+++ b/art/studies/gigi-hover-companion/source/build-report.json@@ -0,0 +1,16 @@+{+ "blender": "5.0.1",+ "body_height_m": 0.4,+ "forward": "glTF +Z",+ "pivot": "body bottom center",+ "objects": 37,+ "textures": "none; glTF PBR constants",+ "approval": "pending",+ "body_emblem": "none",+ "source_metadata": {+ "validated_fields": 3,+ "format": "uncompressed Blender",+ "validated_bytes": 2479697,+ "reopened_fields": 3+ }+}diff --git a/art/studies/gigi-hover-companion/study.json b/art/studies/gigi-hover-companion/study.jsonnew file mode 100644index 0000000000..1baa805e21--- /dev/null+++ b/art/studies/gigi-hover-companion/study.json@@ -0,0 +1,23 @@+{+ "schema": 1,+ "study": "gigi-hover-companion",+ "brief": "brief.md",+ "assets": [+ {+ "id": "gigi-companion",+ "export": "exports/gigi.glb",+ "source": "source/gigi.blend",+ "kind": "character",+ "collection": "GigiExport"+ }+ ],+ "runtime_evidence": [+ "evidence/runtime-close-v2.png"+ ],+ "technical_report": "evidence/technical-review.md",+ "approval": {+ "status": "pending",+ "record": "review.md",+ "evidence_sha256": ""+ }+}diff --git a/art/studies/gigi-hover-companion/usage-paths.txt b/art/studies/gigi-hover-companion/usage-paths.txtnew file mode 100644index 0000000000..623f680aa2--- /dev/null+++ b/art/studies/gigi-hover-companion/usage-paths.txt@@ -0,0 +1,65 @@+scripts\art\build_gigi_companion.py+wiki-video\public\gigi.svg+wiki-video\STORYBOARD.md+wiki-video\src\components\Ghost.tsx+assets\brand\social-preview.html+jarvis\assets\__init__.py+scripts\bulk_translate.py+scripts\ci\privacy_gate\references\distribution-denylist.txt+jarvis\society\runtime.py+scripts\figures\sources\gigi-mascot.json+scripts\figures\quadruped_builder.py+scripts\figures\gigi_builder.py+scripts\figures\contract.json+scripts\figures\build_figures.py+scripts\make_gigi_app_icon.py+jarvis\ui\overlay_styles.py+jarvis\ui\web\frontend\index.html+jarvis\ui\web\frontend\src\i18n\locales\society\es.json+jarvis\ui\web\frontend\src\i18n\locales\society\en.json+jarvis\ui\web\frontend\src\i18n\locales\society\de.json+jarvis\ui\web\frontend\src\i18n\locales\es.json+jarvis\ui\web\frontend\src\i18n\locales\en.json+jarvis\ui\web\frontend\src\i18n\locales\de.json+jarvis\ui\web\frontend\src\components\agentchat\AgentComposer.tsx+jarvis\ui\web\frontend\src\index.css+jarvis\ui\web\frontend\src\lib\bundledWallpapers.ts+jarvis\ui\web\frontend\src\store\wallpaper.ts+jarvis\ui\web\frontend\src\views\ChatsView.tsx+jarvis\ui\web\frontend\src\components\deck\DeckOrb.test.tsx+jarvis\ui\web\frontend\src\components\deck\DeckOrb.tsx+jarvis\ui\web\frontend\src\components\board\ShareCard.tsx+jarvis\ui\web\frontend\src\components\GigiMark.tsx+jarvis\ui\web\frontend\src\assets\society\figures\SOURCES.md+jarvis\ui\web\frontend\src\components\JarvisDock.tsx+jarvis\ui\web\frontend\src\components\MascotGigi.test.tsx+jarvis\ui\web\frontend\src\components\deck\room\GigiFigure.tsx+jarvis\ui\web\frontend\src\components\deck\JarvisOrb.tsx+jarvis\ui\web\frontend\src\components\home\HomeHeader.tsx+jarvis\ui\web\frontend\src\components\home\Greeting.tsx+jarvis\ui\web\frontend\src\components\overlay\OverlayStylePreviews.tsx+jarvis\ui\web\frontend\src\components\layout\TopBar.test.tsx+jarvis\ui\web\frontend\src\components\layout\Sidebar.tsx+jarvis\ui\web\frontend\src\views\MissionDeckView.tsx+jarvis\ui\web\frontend\src\views\MissionDeckView.phases.test.tsx+jarvis\ui\web\frontend\src\components\layout\Sidebar.test.tsx+jarvis\ui\web\frontend\src\views\MissionDeckView.engine.test.tsx+jarvis\ui\web\frontend\src\components\onboarding\OnboardingFlow.test.tsx+jarvis\ui\web\frontend\src\components\onboarding\IntroSequence.tsx+jarvis\ui\web\frontend\src\components\onboarding\IntroSequence.test.tsx+jarvis\ui\web\frontend\src\components\MascotGigi.tsx+jarvis\ui\web\frontend\src\components\onboarding\OnboardingFlow.tsx+jarvis\ui\web\frontend\src\components\society\mockRoster.ts+jarvis\ui\web\frontend\src\components\society\data.ts+jarvis\ui\web\frontend\src\components\society\create\CreateAgentDialog.tsx+jarvis\ui\web\frontend\src\components\society\companion\GigiCompanion.tsx+jarvis\ui\web\frontend\src\components\society\figures\assembleFigure.ts+jarvis\ui\web\frontend\src\components\society\figures\catalog.json+jarvis\ui\web\frontend\src\components\society\mars\MarsWorldStage.tsx+jarvis\ui\web\frontend\src\components\society\mars\MarsScene.tsx+jarvis\ui\web\frontend\src\components\society\mars\mars.css+jarvis\ui\web\frontend\src\components\society\figures\figureRegistry.ts+jarvis\ui\web\frontend\src\components\society\figures\figureRegistry.test.ts+jarvis\ui\web\frontend\src\views\settings\OverlayTaskbarGroup.test.tsx+jarvis\ui\web\frontend\src\components\society\figures\LobbyStage.tsx+jarvis\ui\web\frontend\src\views\WallpaperView.test.tsxdiff --git a/art/studies/mars-outpost-reference/.gitignore b/art/studies/mars-outpost-reference/.gitignorenew file mode 100644index 0000000000..d6a1e26ff3--- /dev/null+++ b/art/studies/mars-outpost-reference/.gitignore@@ -0,0 +1,3 @@+# User reference bytes and original filenames are local working inputs.+# Publication or redistribution has not been authorized.+/references/private/diff --git a/art/studies/mars-outpost-reference/brief.md b/art/studies/mars-outpost-reference/brief.mdnew file mode 100644index 0000000000..533dbdeb27--- /dev/null+++ b/art/studies/mars-outpost-reference/brief.md@@ -0,0 +1,131 @@+# Mars Communications Outpost reference++Stage: authored Outpost reference awaiting runtime integration and review.+Runtime approval: pending. Scope: RUB-69, RUB-71, RUB-79 and RUB-80.+An editable architecture source and review GLB exist; they are not finished+runtime acceptance or gameplay evidence. See `source/README.md`.++## Intent and reference hierarchy++Build a realistic science-fiction Mars colony for users exploring and operating+their actual Jarvis agents. Establish the new integrated colony foundation+first; finish the Communications Outpost at its eastern canonical location+before any other district. The rest of the colony may be explicitly unfinished+blockouts. Neither rejected world prototype supplies the new art direction.++Use `references/manifest.json`. The proposed operational layout is `ref-layout`,+a complete overview preserving the northern Foundry and the eastern Outpost.+`ref-overview-alt` is a distinct complete interpretation, not a duplicate.+District references refine appearance without moving atlas landmarks.+`ref-outpost` governs the recognizable ensemble: irregular elevated rock,+central mast and blue beacons, two prominent dishes, white radomes, support+buildings, service road, and bridge from the colony. `ref-street` governs detail+at human height: material variation, real glazing/interior depth, paving,+lights, planting, rover construction and restrained printed branding.++Shape language: engineered off-white metal shells, dark structural frames,+purposeful joints and access panels against layered orange-red rock. Use warm+practical lights and sparse blue communications accents. Give weathering a+physical cause; protect entrances, roads and silhouettes from clutter. Use PBR+materials and actual geometry for silhouette detail. No pixel/cartoon treatment,+flat colony texture, camera-facing facade, or effects hiding unfinished meshes.++## Discrepancies and unresolved inputs++- The atlas includes a southern Outpost connection as well as the colony-side+ approach. The hero emphasizes one west bridge. Preserve atlas connectivity;+ resolve its engineered junction in the foundation rather than inventing a+ new district location.+- The street image makes Control Room a dome and depicts Mine on a high ridge;+ the central/industrial references differ. Use the atlas for location and the+ relevant district image for function and silhouette. The street image does+ not redefine the world plan.+- Gigi's front concept is corrected, but the side body and logo-detail tile+ retain a loop emblem. Omit that emblem on every body surface. Headers do not+ reverse the removal instruction. Gigi does not decide all worker identities.+- No separate original mascot, verified vector/high-resolution Jarvis mark,+ Outpost rear/interior views or reference redistribution records were present+ in the inspected pack. Keep production branding unresolved until a genuine+ source or reviewed reconstruction exists. Design unseen geometry coherently+ and identify it as authored interpretation.+- Captions, tiny atlas diagrams and decorative slogans are poster overlays,+ not instructions or required 3D objects. Build useful navigation HUD separately.++## Proposed scale sheet and access++These are operational starting dimensions adopted with the foundation owner,+not measured reference dimensions or user visual approval. The parent-owned+`jarvis/society/mars/definition.json` is the layout authority; this study does not+create a second world registry. Collision, navigation, anchors and visuals must+use that shared definition/version. Detail and access proposals below remain+subject to gameplay checks and runtime review.++| Element | Proposed starting value | Resolution owner |+| --- | --- | --- |+| World units | 1 unit = 1 metre; Y up, X east, negative Z north | Foundation lead |+| Colony extent | Approximately 900 by 850 m | Foundation lead |+| Outpost plateau | Approximately 120 by 95 m, irregular perimeter | Foundation and environment owners |+| Mast | Approximately 62 m above the plateau | Environment owner, runtime composition review |+| Bridge | 7 m carriageway plus separated 1.5 m walks each side | Navigation and rover owners |+| Service entrance | 2.4 m clear width, 3 m clear height | Gameplay and environment owners |+| Worker scale | 1.75 m provisional clearance envelope | Character owner; visual direction pending |+| Rover scale | 4.8 by 2.4 m provisional envelope | Rover owner; travel mode pending |+| Near inspection | Target 0.5-1 m from selected detail | Art review; not an infinite-detail promise |++Foundation alignment: Hub centre `[0, 48, 0]`; Outpost centre `[320, 58, 50]`.+The 62 m mast height is above the Outpost plateau, not absolute elevation.+Foundry, Mine, Workshop, Water Extraction, Memory House, Harbor Gate, Gardens+and Solar Field use the foundation's shared placements and remain blockouts+until the Outpost reference gate permits their visual-family production.++| Outpost area | Access contract |+| --- | --- |+| Bridge and exterior service loop | Required continuous player/agent route; safe separated travel and railings |+| Main service entrance and station room | Required usable door, traversable interior and backend-backed workstation |+| Rover boarding bay | Required safe approach, boarding and collision-safe exit locations |+| Plateau rear and side service routes | Required coherent geometry and declared traversable paths; deliberate edge hazards |+| Mast upper levels and maintenance roof | Access scope unresolved; do not advertise access or assume decorative exclusion |+| Dish mechanisms, radomes and remaining support interiors | Access classification unresolved before final Outpost review |+| Other colony buildings and levels | Register before family rollout; no implied full interiors or silently inaccessible advertised areas |++## Camera, quality and evidence proposals++The study supports overview, continuous horizontal orbit, follow and player+inspection. Fit overview from actual bounds and aspect ratio so the Foundry+and mast stay visible. Save reference-facing, rear, left, right, overhead,+street/entrance and neutral-light presets from one world. View angles are+inspection evidence, not a fixed hero-camera restriction.++D01 economy 1080p/30 FPS and stronger-client 60 FPS are candidate goals only.+Actual named CPU/GPU/RAM/OS/browser/WebView profiles, viewport/render scale,+frame-time percentiles, visible rigs, scene triangles, draw calls, texture/GPU+memory and load size remain unmeasured. Establish per-asset and scene budgets+with the rendering owner before production; do not copy arbitrary limits.+Light/dark controls, terminal focus, reduced motion and critical status/stop+must remain usable independent of 3D rendering.++D05 worker direction and D08 route-driven ride versus direct driving require+resolution. A representative new rigged character and meaningful rover travel+are required in the completed reference. Route animation must not invent task+success or block unrelated backend work. D02 remote hosting, D03 operational+objectives, D04 recovery limits, D09 concurrency and D10 delivery budgets remain+with the integration decision register; this brief adopts none by implication.++## Production and review boundary++Retain separate editable Blender sources and reproducible recipes for the+building ensemble, terrain, representative character and rover. Blender 5.0.1+was found in the authoring environment; exporter/loader compatibility still+needs a real sample. Sources and review GLBs remain in this study. End users+receive packaged runtime assets without Blender or private reference inputs.++Check scale, axes, ground contact, rigs, proxies, embedded resources and LOD+silhouettes. Then verify actual runtime collision/navigation, interior/station+use, movement transitions and measured performance. Record front/rear/sides/+top/near screenshots and motion in intended and neutral light, plus the+build/asset/world fingerprint. No offline render or enhanced screenshot is+runtime evidence.++The user must approve that specific finished Outpost evidence before further+visual-family production. No agent-written record or technical pass provides+consent. Independent backend, tooling and test work may continue meanwhile.diff --git a/art/studies/mars-outpost-reference/exports/communications-outpost.glb b/art/studies/mars-outpost-reference/exports/communications-outpost.glbnew file mode 100644index 0000000000..7d54626835Binary files /dev/null and b/art/studies/mars-outpost-reference/exports/communications-outpost.glb differdiff --git a/art/studies/mars-outpost-reference/references/README.md b/art/studies/mars-outpost-reference/references/README.mdnew file mode 100644index 0000000000..11018f09d5--- /dev/null+++ b/art/studies/mars-outpost-reference/references/README.md@@ -0,0 +1,22 @@+# Reference pack++`manifest.json` is the portable public index: stable IDs, SHA-256 hashes,+dimensions, roles, selection state and discrepancies. It contains no private+filesystem locations or source filenames.++The nine original PNGs and `manifest.json` containing their actual filenames+are retained under ignored `private/`. Paths in that private manifest are+relative to this study. Copy that directory only through an authorized private+transfer when another authoring environment needs the reference bytes. Check+each received file against the public hash before using it. The public index+does not imply that a clean checkout contains the private inputs.++These user-supplied concepts guide newly authored geometry. Their redistribution+rights are unverified; they must not be published or packaged as game textures.+The original input folder and private pack are not production dependencies.+Record provenance and distribution permission separately for every newly+authored or acquired runtime asset.++No reference selection is approval of the runtime Outpost. The proposed layout+is `ref-layout`; `ref-outpost` controls the first finished district and+`ref-street` controls close-range material and scale quality.diff --git a/art/studies/mars-outpost-reference/references/manifest.json b/art/studies/mars-outpost-reference/references/manifest.jsonnew file mode 100644index 0000000000..afd4c062a5--- /dev/null+++ b/art/studies/mars-outpost-reference/references/manifest.json@@ -0,0 +1,197 @@+{+ "schema": 1,+ "study": "mars-outpost-reference",+ "inventory_status": "verified-local-inputs",+ "file_count": 9,+ "byte_duplicate_groups": [],+ "origin": "User-provided concept images; inspected original files and verified private copies.",+ "rights": "Reference-only inputs; redistribution unverified and publication not authorized.",+ "canonical_layout": {+ "reference_id": "ref-layout",+ "state": "proposed-operational-selection",+ "owner": "integration-lead",+ "rationale": "Complete colony bounds and keyed landmark positions; alternate overview remains secondary.",+ "user_runtime_approval": false+ },+ "references": [+ {+ "id": "ref-overview-alt",+ "media_type": "image/png",+ "sha256": "1ace38c482954907c6c422c1dc996a685841d96c3057ea5668a4b34841b382c4",+ "bytes": 3310816,+ "width": 1448,+ "height": 1086,+ "role": "Complete alternate colony overview",+ "selection": "appearance-secondary",+ "input_path": "references/private/ref-overview-alt.png",+ "visually_inspected": true,+ "redistribution": "not-authorized"+ },+ {+ "id": "ref-central",+ "media_type": "image/png",+ "sha256": "3a0053919bfa8c068779c63b773644e4d367e92454647d1bb7314cb776135d45",+ "bytes": 3358266,+ "width": 1448,+ "height": 1086,+ "role": "Hub and central district architecture and density",+ "selection": "district-reference",+ "input_path": "references/private/ref-central.png",+ "visually_inspected": true,+ "redistribution": "not-authorized"+ },+ {+ "id": "ref-industry",+ "media_type": "image/png",+ "sha256": "eb48da3a5e10fbbf2064f8f5523b846511eafe6adc31ce9db4b4d735f7213ed2",+ "bytes": 3416094,+ "width": 1448,+ "height": 1086,+ "role": "Foundry, Mine and Solar Field",+ "selection": "district-reference",+ "input_path": "references/private/ref-industry.png",+ "visually_inspected": true,+ "redistribution": "not-authorized"+ },+ {+ "id": "ref-logistics",+ "media_type": "image/png",+ "sha256": "33c3e82f22cd16df21efd71254a8dfa7e1192ee533a30907562b037d0b8a9ef6",+ "bytes": 3499976,+ "width": 1448,+ "height": 1086,+ "role": "Harbor Gate and Gardens",+ "selection": "district-reference",+ "input_path": "references/private/ref-logistics.png",+ "visually_inspected": true,+ "redistribution": "not-authorized"+ },+ {+ "id": "ref-outpost",+ "media_type": "image/png",+ "sha256": "e3bb9e76b2da9c957d30860ca3118365314def35b0130a0090973beb897dee78",+ "bytes": 2816557,+ "width": 1448,+ "height": 1086,+ "role": "Communications Outpost first finished district",+ "selection": "primary-outpost-reference",+ "input_path": "references/private/ref-outpost.png",+ "visually_inspected": true,+ "redistribution": "not-authorized"+ },+ {+ "id": "ref-resources",+ "media_type": "image/png",+ "sha256": "1fee45fc5f8e5a1a73d83d502375ef042183cafb542889beda7791d8f386e6d6",+ "bytes": 3298347,+ "width": 1448,+ "height": 1086,+ "role": "Workshop and Water Extraction",+ "selection": "district-reference",+ "input_path": "references/private/ref-resources.png",+ "visually_inspected": true,+ "redistribution": "not-authorized"+ },+ {+ "id": "ref-street",+ "media_type": "image/png",+ "sha256": "4fd74a2de6776e4d5e8c4c94e2c746db9ac653393310226ae5d5fcc4953b980f",+ "bytes": 2554276,+ "width": 1672,+ "height": 941,+ "role": "Street-level materials, rover, glazing and interior depth",+ "selection": "primary-close-detail-reference",+ "input_path": "references/private/ref-street.png",+ "visually_inspected": true,+ "redistribution": "not-authorized"+ },+ {+ "id": "ref-layout",+ "media_type": "image/png",+ "sha256": "bde63e07d79c372ffdc615d3e129b8c207a764d1ec17c0fd5c0c3e5c87f932ff",+ "bytes": 3387374,+ "width": 1448,+ "height": 1086,+ "role": "Complete colony atlas with northern Foundry and eastern Outpost",+ "selection": "proposed-canonical-layout",+ "input_path": "references/private/ref-layout.png",+ "visually_inspected": true,+ "redistribution": "not-authorized"+ },+ {+ "id": "ref-gigi",+ "media_type": "image/png",+ "sha256": "7bcb494559e9028c3e7ae65afb17611a2cdd3928d5a0fecb0ef7b185d7c13559",+ "bytes": 1664314,+ "width": 1449,+ "height": 1086,+ "role": "Gigi multi-view concept; remove all loop/wave body emblems",+ "selection": "mascot-direction-only",+ "input_path": "references/private/ref-gigi.png",+ "visually_inspected": true,+ "redistribution": "not-authorized"+ }+ ],+ "discrepancies": [+ {+ "id": "map-approach",+ "references": [+ "ref-layout",+ "ref-outpost"+ ],+ "finding": "Atlas retains a southern Outpost connection while the hero emphasizes one west bridge.",+ "resolution": "Use atlas topology and author an engineered junction with the foundation owner."+ },+ {+ "id": "street-landmarks",+ "references": [+ "ref-layout",+ "ref-central",+ "ref-industry",+ "ref-street"+ ],+ "finding": "Street view changes Control Room silhouette to a dome and depicts an elevated Mine.",+ "resolution": "Atlas controls location; district references control function and silhouette; street view controls near-detail quality."+ },+ {+ "id": "gigi-body-mark",+ "references": [+ "ref-gigi"+ ],+ "finding": "Side body and logo-detail tile retain a loop emblem despite corrected frontal views.",+ "resolution": "Omit the loop/wave symbol on every body surface; headers and detail tiles do not override the explicit removal."+ },+ {+ "id": "poster-overlays",+ "references": [+ "ref-overview-alt",+ "ref-layout",+ "ref-outpost"+ ],+ "finding": "Concepts include editorial captions, inset minimaps and decorative slogans.",+ "resolution": "Separate useful runtime HUD from scene geometry; do not treat reference text as instructions."+ }+ ],+ "missing_inputs": [+ {+ "id": "brand-master",+ "finding": "No separate verified vector or high-resolution Jarvis mark in the inspected pack.",+ "scope": "Obtain a genuine source or create a clean reconstruction for review before production decals."+ },+ {+ "id": "original-mascot",+ "finding": "No separate original mascot raster in the inspected pack.",+ "scope": "Use the available multi-view sheet only as direction; no worker identity decision is inferred."+ },+ {+ "id": "unseen-outpost-views",+ "finding": "No dedicated Outpost rear, side, top or interior construction views.",+ "scope": "Author consistent unseen geometry and validate all views from the same runtime world."+ },+ {+ "id": "reference-rights",+ "finding": "No redistribution records accompanied the image inputs.",+ "scope": "Keep original bytes private and outside runtime delivery."+ }+ ]+}diff --git a/art/studies/mars-outpost-reference/review.md b/art/studies/mars-outpost-reference/review.mdnew file mode 100644index 0000000000..fff09c633c--- /dev/null+++ b/art/studies/mars-outpost-reference/review.md@@ -0,0 +1,31 @@+# Reference review++Decision: pending.++Current stage: authored Outpost reference awaiting runtime integration and+review. `source/communications-outpost.blend` and+`exports/communications-outpost.glb` contain the new architecture, terrain,+bridge and operations interior. No runtime walkthrough, performance result+or user visual approval exists in this study.++`ref-layout` is the proposed operational atlas. Its selection does not approve+the future runtime Outpost, character treatment or visual family rollout.++Open decisions: worker direction, rover mode, named target+hardware/budgets, verified branding source and complete Outpost access register.+The removed Gigi loop/wave body symbol must be absent from every side.++Submit the actual integrated Outpost with a usable bridge/interior/station,+new animated figure, meaningful rover travel and front/rear/sides/top/near+views plus motion under intended and neutral lighting. Keep artistic findings+separate from navigation, collision, animation and performance results.++After actual user approval, record its date, scope and an English summary here,+then bind the study manifest to the reviewed evidence fingerprint. Keep private+conversation content and personal identifiers outside the repository. A passing+check, a concept image or an agent's own opinion is not user approval.++Structural evidence only: `source/geometry-contract.json` records editable+source geometry, canonical placements, collider/anchor metadata and source+hash. `source/export-report.json` records actual GLB bounds, counts, extensions+and hash. These do not validate runtime navigation, collision or visual quality.diff --git a/art/studies/mars-outpost-reference/source/README.md b/art/studies/mars-outpost-reference/source/README.mdnew file mode 100644index 0000000000..c14ad75758--- /dev/null+++ b/art/studies/mars-outpost-reference/source/README.md@@ -0,0 +1,112 @@+# Communications Outpost authored source++Status: first authored reference; runtime integration and visual review pending.+The study remains `approval.status: pending` and cannot pass the reference gate+without actual runtime evidence. It has not entered the production catalog.++## Rebuild and export++Run from the repository root with Blender 5.0.1 available in the authoring+environment. The command name below denotes its installed executable; Blender+is not a game-server or end-user dependency.++```text+blender --background --factory-startup --disable-autoexec --python scripts/art/build_outpost_reference.py+blender --background --factory-startup --disable-autoexec --python scripts/art/build_outpost_reference.py -- --validate-source+blender --background --factory-startup --disable-autoexec --python scripts/art/export_study.py -- --manifest art/studies/mars-outpost-reference/study.json --asset communications-outpost-reference+python scripts/art/build_outpost_reference.py -- --validate-export art/studies/mars-outpost-reference/exports/communications-outpost.glb+python scripts/art_pipeline.py check art/studies/mars-outpost-reference/study.json+```++The recipe reads only the canonical `jarvis/society/mars/definition.json` and+the study manifest. It does not read private concept PNGs, old world assets,+third-party textures or a local profile path. All geometry, materials and+wayfinding text in this source are newly authored by the recipe for this+project. No third-party model or copied concept-image logo is embedded.+Private reference redistribution remains unauthorized.++`communications-outpost.blend` retains 1,215 individually named editable source+objects in architectural collections. They are hidden in the default view;+unhide `Editable architecture` and hide `Export` to edit them without drawing+both copies. The `Export` collection contains evaluated geometry batched by+material, plus collider/anchor empties. Changing source objects requires+rebatching through the authoring workflow before exporting; the existing+manifest exporter exports the named `Export` collection only.++The surface maps in `materials/` are newly authored procedural normal and roughness maps, retained with the source and embedded in the GLB. Metre-scaled UVs and material-aware vertex tinting carry painted-alloy, mineral, dust and metal variation into the runtime. This adds delivery size; it is not a measured load-time or fidelity result.++The procedural seed and shared placements are deterministic. Blender source+metadata and exporter versions may change bytes; compare geometry contracts+and actual hashes rather than promising byte-identical `.blend`/GLB output.+Rebuilding refuses an already approved study so a new unreviewed artifact+cannot silently overwrite approved evidence.++## Coordinate and integration contract++- The exported origin is the Outpost plateau top. Runtime units are metres,+ Y-up, X-east and negative Z-north. Place the GLB at `[320, 58, 50]` once.+ Source conversion is `(x,y,z) -> (x,-z,y)` into Blender; `export_yup=True`+ returns the runtime convention.+- The canonical operations building is centred at `[-26, 0, 14]`, with a+ 20 by 14 m footprint. Its south entrance is at `[-26, 0, 21]`; jambs leave+ 2.4 m clear width and the lintel 3 m clear height. Door panels are visibly+ parked open. The desk is north of the clear console anchor.+- The bridge deck top interpolates the exact local graph endpoints+ `[-195, -10, -10]` to `[-64, 0, 0]`, 10 m wide. Remove duplicate coarse+ Outpost/route-01 visual geometry when integrating this study asset.+- `geometry-contract.json` contains the canonical definition hash, layout+ version, placements, colliders and anchors. GLB empties repeat each record+ in `extras.mars_contract` as JSON; `extras.mars_kind` distinguishes+ `collider` and `anchor`. The JSON coordinates remain **asset-local runtime+ coordinates**, regardless of the empty's transform. Do not apply the+ empty translation to those JSON coordinates a second time.+- Collider records describe box solids, a graded bridge deck, and a plateau+ footprint/top/bottom. They are integration data, not self-executing physics.+ Runtime collision/navigation owners must consume or deliberately map them.+ The plateau footprint is a reference boundary, not a navigation mesh.+- `communications-console`, `console-display`, `operations-door`, navigation+ endpoints and reserved branding slots are stable anchors. Blank screens+ convey no invented task status. Backend authority supplies real state.+- Dishes, radomes, mast and support interiors remain exterior-only in this+ asset. The operations room is the usable interior. Roof/maintenance access+ is unadvertised and unresolved. No character, rover, rig or animation is+ included until the respective direction and control decisions resolve.++## Measured export and remaining checks++Second reference export: 20 meshes/material batches, 211,968 triangles, 14,571,224 bytes;+target was fewer than 300,000 triangles. These are asset counts, not an FPS or+quality result. Inspect the current `export-report.json` for the exact hash,+bounds and material extensions. The GLB embeds its buffer and requires no+external resource URI; it uses transmission, IOR and emissive-strength glTF+material extensions. Actual loader behavior still needs runtime verification.++The generic exporter verified a structurally valid GLB with position data and+embedded resources. Geometry tests check closed outward plateau/dish shells,+coordinate handedness, graded bridge endpoints and the real door opening.+Neither proves traversal, legibility, lighting, near-view fidelity, collision+alignment, performance, or user visual acceptance in the actual application.+No offline beauty render has been recorded as runtime evidence.++## Portable editable-source metadata++Image paths become study-relative before packing. The authoring save also+sanitizes each packed image's separate filepath snapshot and clears the saved+file-browser directory and render-output default. These serialized fields can+retain an authoring machine's profile path even when `Image.filepath` appears+relative. Fixed-size path arrays are fully overwritten through Blender's RNA+properties before assigning their neutral relative values.++`--validate-source` reopens the actual saved source with its workspace data and+checks 38 portable path fields without logging their rejected values. Windows+native separators after Blender's `//` prefix are normalized for validation;+absolute and network-share paths remain rejected. All 18 authored material+images remain packed and the editable geometry remains intact.++The current `.blend` is saved uncompressed so byte inspection can verify the+serialized content directly. `public-source-report.json` records the field+classes, marker-absence checks and successful reopen. The sanitized source+reproduces the same GLB hash and numeric material data; sanitization changes+neither the model nor the runtime appearance.++Numeric material validation reads actual accessor buffers with their strides and offsets. It rejects nonfinite or out-of-range linear colors, mismatched counts, invalid embedded-buffer bounds and invalid normal directions. The source also reads back assigned UVs and colors before saving. Blender custom-data layer handles are reacquired after all layers are allocated; retaining a UV handle across color-layer allocation was reproduced to overwrite color channels with UV coordinates.diff --git a/art/studies/mars-outpost-reference/source/export-report.json b/art/studies/mars-outpost-reference/source/export-report.jsonnew file mode 100644index 0000000000..b89dd1a398--- /dev/null+++ b/art/studies/mars-outpost-reference/source/export-report.json@@ -0,0 +1,151 @@+{+ "kind": "structural-export-evidence-only",+ "iteration": 3,+ "runtime_visual_approval": "pending",+ "path": "exports/communications-outpost.glb",+ "sha256": "dde2c6c384f6c05daca459e3def952eb76b56540a220ed9bd6f272b52e27c324",+ "bytes": 15089320,+ "meshes": 20,+ "materials": 20,+ "triangles": 212724,+ "local_runtime_bounds": {+ "min": [+ -195.43536376953125,+ -63.18514633178711,+ -49.922935485839844+ ],+ "max": [+ 63.38080978393555,+ 62.0,+ 51.0+ ]+ },+ "world_translation": [+ 320,+ 58,+ 50+ ],+ "collider_nodes": 24,+ "anchor_nodes": 15,+ "animations": 0,+ "external_resource_uris": [],+ "extensions_used": [+ "KHR_materials_transmission",+ "KHR_materials_emissive_strength",+ "KHR_materials_ior"+ ],+ "embedded_images": 19,+ "primitives_with_vertex_tint": 13,+ "materials_with_normal_maps": 13,+ "materials_with_roughness_maps": 13,+ "authored_material_sources": [+ {+ "path": "source/materials/ceramic-roughness.png",+ "bytes": 21832,+ "sha256": "7138d38bce99c4d4dcaa1c3057871471a0faee291a15b513f1ab1963a6ef65dc"+ },+ {+ "path": "source/materials/ceramic-warm-roughness.png",+ "bytes": 21601,+ "sha256": "926df6ea323856de64b46a1e74f35257cadffcdbbd2353a1e9fc3f1af36595a4"+ },+ {+ "path": "source/materials/cliff-roughness.png",+ "bytes": 36311,+ "sha256": "a2038e6b76817851fccb03544120662c6344e7f7f538a618f9f61d204a439c59"+ },+ {+ "path": "source/materials/concrete-normal.png",+ "bytes": 58224,+ "sha256": "cfca0a24dfb24db7faa5655a4f38c66c5995abe33cd035dfa05d690105582bfd"+ },+ {+ "path": "source/materials/concrete-roughness.png",+ "bytes": 28684,+ "sha256": "0a1552d60d873664f823ee3cf574170fe3bab81b8d8c421bdb44d6d8c5cc7b50"+ },+ {+ "path": "source/materials/dust-coated-roughness.png",+ "bytes": 28596,+ "sha256": "ff690f07b6ea26ef6e09aadd5031e8a8bb81538a602d9121f9bcd94b3a140c5f"+ },+ {+ "path": "source/materials/gold-roughness.png",+ "bytes": 26256,+ "sha256": "414893eda013522ca0cffdb8a6b120335e212ffed7e721414cd86ab75a151c8d"+ },+ {+ "path": "source/materials/metal-normal.png",+ "bytes": 30123,+ "sha256": "b35cfc0532d94bdbe7ef174ca6a67cc2fa4d7c296314c33d452745447686ccbd"+ },+ {+ "path": "source/materials/metal-roughness.png",+ "bytes": 26370,+ "sha256": "b266cc2606aa24788fc56f77ac5da15a82bc8ae958112cbed2d926c27d4f5c53"+ },+ {+ "path": "source/materials/mineral-normal.png",+ "bytes": 111656,+ "sha256": "22650091823796ba41550ce7c2c586f993062a54d60d1133af896b575c3b5a54"+ },+ {+ "path": "source/materials/paint-normal.png",+ "bytes": 38208,+ "sha256": "a5e80146adb0810356ab5d2e95705ae4e1a7cc506f9dd4ec04829457cc5ae630"+ },+ {+ "path": "source/materials/painted-alloy-roughness.png",+ "bytes": 21545,+ "sha256": "01781249d97517606f6b389a90cd8ce88466763e0bbb23497a12cfe39611528e"+ },+ {+ "path": "source/materials/paving-normal.png",+ "bytes": 49615,+ "sha256": "4b411cb1f4c8f485dc20e0632d52aa6e9cf535f31f74f2be74185fa42642ab56"+ },+ {+ "path": "source/materials/paving-roughness.png",+ "bytes": 26364,+ "sha256": "03fc35fbad6b3fc923d4f845575b0175933342d77a39f9b39a21c5ceb77259fe"+ },+ {+ "path": "source/materials/road-normal.png",+ "bytes": 59985,+ "sha256": "61e41f51babcc4d842e09d571b97dafd382bc08fb32e8385802cdc3a6aee66e3"+ },+ {+ "path": "source/materials/road-roughness.png",+ "bytes": 30650,+ "sha256": "907b47e9f0f02765e51387bf74a4a8acc8158b7d949e5a9e943c0b321ca8de8c"+ },+ {+ "path": "source/materials/rock-highlight-roughness.png",+ "bytes": 36350,+ "sha256": "152274ef9320659abd3ba3f4a784c6eb0911e16d543db6d98ca7180ee7048d6b"+ },+ {+ "path": "source/materials/rock-shadow-roughness.png",+ "bytes": 31865,+ "sha256": "21fcdb40a4fc6d4f0c00e485973e1a5c9f25d9ca018c36e6c8b2d739d09b0d02"+ },+ {+ "path": "source/materials/roof-alloy-roughness.png",+ "bytes": 26366,+ "sha256": "862bb10ab8319dd099f140afa3d58c2caf01f7a46ad8435595e23c5252838acd"+ },+ {+ "path": "source/materials/structure-roughness.png",+ "bytes": 26345,+ "sha256": "6d6bd2fa8a13b6d01bebd7434a6ede70f70c69c37391c81facde3f1b66aae188"+ }+ ],+ "numeric_material_validation": {+ "colored_primitives": 13,+ "linear_color_range": [+ 0.032668162137269974,+ 0.7518854141235352+ ],+ "uv_abs_max": 977.0883178710938+ }+}diff --git a/art/studies/mars-outpost-reference/source/geometry-contract.json b/art/studies/mars-outpost-reference/source/geometry-contract.jsonnew file mode 100644index 0000000000..9c1f72968b--- /dev/null+++ b/art/studies/mars-outpost-reference/source/geometry-contract.json@@ -0,0 +1,1325 @@+{+ "source_objects": 1279,+ "export_meshes": 20,+ "triangles": 212724,+ "asset_id": "communications-outpost-reference",+ "stage": "authored-reference-unreviewed",+ "blender_version": "5.0.1",+ "seed": 6901,+ "layout_version": 1,+ "definition_sha256": "1dae7897e477201b1a859fcc813e7ff5111982a2f2a330bd872245b67eb35c2d",+ "world_translation": [+ 320,+ 58,+ 50+ ],+ "source_axes": "Blender Z-up; runtime (x,y,z) maps to Blender (x,-z,y)",+ "export_axes": "Runtime Y-up via glTF exporter export_yup=True",+ "triangle_target": 300000,+ "source_bytes": 29804549,+ "source_sha256": "c233ea227eca1d3d9f4d1e565f6e6e9659ef04024ca56331ea240cb0f28bcec1",+ "source_metadata_validation": {+ "validated_fields": 42,+ "packed_image_files": 20,+ "file_browser_defaults": 1+ },+ "material_profiles": {+ "paint": {+ "seed": 41,+ "tile_metres": 0.24,+ "relief_metres": 0.00012,+ "roughness_span": 0.025+ },+ "metal": {+ "seed": 87,+ "tile_metres": 0.2,+ "relief_metres": 6e-05,+ "roughness_span": 0.04+ },+ "mineral": {+ "seed": 129,+ "tile_metres": 1.8,+ "relief_metres": 0.018,+ "roughness_span": 0.1+ },+ "concrete": {+ "seed": 173,+ "tile_metres": 0.8,+ "relief_metres": 0.0012,+ "roughness_span": 0.05+ },+ "paving": {+ "seed": 191,+ "tile_metres": 0.65,+ "relief_metres": 0.0006,+ "roughness_span": 0.04+ },+ "road": {+ "seed": 219,+ "tile_metres": 0.6,+ "relief_metres": 0.001,+ "roughness_span": 0.06+ }+ },+ "walk_surfaces": {+ "coordinates": "asset-local runtime Y-up metres",+ "route-01": {+ "surface": "bridge",+ "node_height_offset": 0+ },+ "route-02": {+ "surface": "road",+ "node_height_offset": 0.006+ },+ "route-03": {+ "surface": "footpath",+ "node_height_offset": 0.006+ },+ "route-04": {+ "surface": "operations-entry",+ "approach_surface": "terrace",+ "interior_surface": "operations"+ },+ "route-05": {+ "surface": "road",+ "node_height_offset": 0.006+ },+ "perimeter": {+ "top_y": 0.006+ },+ "terrace": {+ "top_y": -0.03,+ "footprint": [+ [+ 55.0,+ 28.0+ ],+ [+ 54.880228059233346,+ 29.827366691080723+ ],+ [+ 54.52296156804695,+ 31.623466631435292+ ],+ [+ 53.93431345515801,+ 33.35756805311126+ ],+ [+ 53.124355652982146,+ 35.0+ ],+ [+ 52.10694676407729,+ 36.52266000612209+ ],+ [+ 50.89949493661167,+ 37.89949493661167+ ],+ [+ 49.52266000612209,+ 39.10694676407729+ ],+ [+ 48.0,+ 40.12435565298214+ ],+ [+ 46.35756805311126,+ 40.93431345515801+ ],+ [+ 44.62346663143529,+ 41.52296156804695+ ],+ [+ 42.82736669108073,+ 41.880228059233346+ ],+ [+ 41.0,+ 42.0+ ],+ [+ -41.0,+ 42.0+ ],+ [+ -42.82736669108072,+ 41.880228059233346+ ],+ [+ -44.62346663143529,+ 41.52296156804695+ ],+ [+ -46.35756805311126,+ 40.93431345515801+ ],+ [+ -48.0,+ 40.124355652982146+ ],+ [+ -49.52266000612209,+ 39.10694676407729+ ],+ [+ -50.89949493661166,+ 37.89949493661167+ ],+ [+ -52.10694676407729,+ 36.522660006122095+ ],+ [+ -53.124355652982146,+ 35.0+ ],+ [+ -53.93431345515801,+ 33.35756805311126+ ],+ [+ -54.52296156804695,+ 31.623466631435296+ ],+ [+ -54.880228059233346,+ 29.827366691080723+ ],+ [+ -55.0,+ 28.0+ ],+ [+ -55.0,+ -28.0+ ],+ [+ -54.880228059233346,+ -29.82736669108072+ ],+ [+ -54.52296156804695,+ -31.623466631435292+ ],+ [+ -53.93431345515802,+ -33.35756805311126+ ],+ [+ -53.12435565298214,+ -35.0+ ],+ [+ -52.10694676407729,+ -36.52266000612209+ ],+ [+ -50.89949493661167,+ -37.89949493661166+ ],+ [+ -49.522660006122095,+ -39.10694676407729+ ],+ [+ -48.00000000000001,+ -40.12435565298214+ ],+ [+ -46.35756805311125,+ -40.93431345515802+ ],+ [+ -44.62346663143529,+ -41.52296156804695+ ],+ [+ -42.82736669108073,+ -41.880228059233346+ ],+ [+ -41.0,+ -42.0+ ],+ [+ 41.0,+ -42.0+ ],+ [+ 42.82736669108072,+ -41.880228059233346+ ],+ [+ 44.623466631435285,+ -41.52296156804696+ ],+ [+ 46.35756805311126,+ -40.93431345515801+ ],+ [+ 48.0,+ -40.12435565298214+ ],+ [+ 49.52266000612209,+ -39.10694676407729+ ],+ [+ 50.89949493661166,+ -37.89949493661167+ ],+ [+ 52.10694676407729,+ -36.522660006122095+ ],+ [+ 53.12435565298214,+ -35.00000000000001+ ],+ [+ 53.93431345515802,+ -33.35756805311125+ ],+ [+ 54.52296156804695,+ -31.62346663143529+ ],+ [+ 54.880228059233346,+ -29.827366691080723+ ],+ [+ 55.0,+ -28.000000000000004+ ]+ ]+ },+ "operations": {+ "structural_slab_top_y": -0.04,+ "finished_floor_top_y": 0,+ "finished_floor_xz_bounds": [+ [+ -35.6,+ 7.4+ ],+ [+ -16.4,+ 20.6+ ]+ ],+ "south_door_threshold_z": 21.0,+ "approach_terrace_top_y": -0.03+ }+ },+ "colliders": [+ {+ "id": "plateau-surface",+ "shape": "plateau",+ "top_y": -0.12,+ "footprint": [+ [+ 59.191634094389656,+ 0.0+ ],+ [+ 61.749241934778546,+ 8.514104199157142+ ],+ [+ 61.03500148354229,+ 12.597731490924577+ ],+ [+ 59.67266156242975,+ 15.61855150291954+ ],+ [+ 59.7138129811923,+ 18.5285314444432+ ],+ [+ 59.30010118534338,+ 21.03260979086601+ ],+ [+ 58.127763352592396,+ 23.038316347469532+ ],+ [+ 58.03849366748464,+ 25.3147658224957+ ],+ [+ 55.75826751047471,+ 26.475351387987235+ ],+ [+ 56.59208625730029,+ 29.02009076235758+ ],+ [+ 56.03539862020041,+ 30.847483771922832+ ],+ [+ 55.34532451553743,+ 32.56036857604752+ ],+ [+ 52.84886548328642,+ 33.11431138481073+ ],+ [+ 54.619411079831984,+ 36.358418023384644+ ],+ [+ 51.86646688792663,+ 36.61419465719866+ ],+ [+ 51.847763104210145,+ 38.770664206101536+ ],+ [+ 49.04277102045934,+ 38.825527057863646+ ],+ [+ 48.53913043782187,+ 40.68211219407126+ ],+ [+ 46.47577983007412,+ 41.26183928516427+ ],+ [+ 44.30590777699401,+ 41.714629657462076+ ],+ [+ 42.105670735922594,+ 42.115818832959796+ ],+ [+ 39.15382820533572,+ 41.71099744219333+ ],+ [+ 37.447872416737155,+ 42.633853476046816+ ],+ [+ 37.24984033273295,+ 45.52668955958615+ ],+ [+ 35.01636271728066,+ 46.21929204878478+ ],+ [+ 31.822978024801873,+ 45.72647836343249+ ],+ [+ 30.035766997147554,+ 47.49592171667565+ ],+ [+ 27.244404589622437,+ 48.142020044492085+ ],+ [+ 24.035414601950507,+ 48.54786562306265+ ],+ [+ 20.186148638070165,+ 48.336237321697645+ ],+ [+ 15.690645759286092,+ 47.644431369715136+ ],+ [+ 10.140889957685634,+ 46.094961644522186+ ],+ [+ 2.3538673894362126e-08,+ 47.192768451211116+ ],+ [+ -10.076797394463751,+ 45.803631765612295+ ],+ [+ -15.613918221040205,+ 47.41144924863453+ ],+ [+ -19.38289796176808,+ 46.412833505809395+ ],+ [+ -23.15713758058382,+ 46.77388021364629+ ],+ [+ -26.498575686326486,+ 46.82410869524163+ ],+ [+ -29.222481994402926,+ 46.20986430294711+ ],+ [+ -32.732604407473836,+ 47.033521691484324+ ],+ [+ -35.375972410402,+ 46.69395315405564+ ],+ [+ -36.15254375575048,+ 44.185575606644505+ ],+ [+ -37.657348743103014,+ 42.872339201099436+ ],+ [+ -39.58907522753542,+ 42.1746708111034+ ],+ [+ -41.21147121521594,+ 41.221403796781054+ ],+ [+ -44.367785835119825,+ 41.77288871157364+ ],+ [+ -45.01255033071367,+ 39.96276392460727+ ],+ [+ -47.180899419108236,+ 39.543737728143036+ ],+ [+ -48.7299830482537,+ 38.577903246534184+ ],+ [+ -51.15414028925211,+ 38.25198768788074+ ],+ [+ -51.748275381943344,+ 36.53075950021659+ ],+ [+ -53.76680286452355,+ 35.790863645014525+ ],+ [+ -52.9872502387113,+ 33.20102120989676+ ],+ [+ -53.341430610094314,+ 31.38145193368136+ ],+ [+ -54.56101326526335,+ 30.035834717398476+ ],+ [+ -54.55022684285722,+ 27.973037199749818+ ],+ [+ -57.18073992626661,+ 27.150775118481285+ ],+ [+ -57.96774482697371,+ 25.283907159278016+ ],+ [+ -57.01160468244118,+ 22.595938814707168+ ],+ [+ -60.77621388505199,+ 21.556158685382687+ ],+ [+ -59.930492808535405,+ 18.59576478282621+ ],+ [+ -61.39220867371084,+ 16.06862083812328+ ],+ [+ -61.99083808561336,+ 12.795017844154813+ ],+ [+ -60.675757659126624,+ 8.36609012331292+ ],+ [+ -60.65042374326891,+ 2.8341477861709704e-08+ ],+ [+ -59.403552067659575,+ -8.190675970375738+ ],+ [+ -59.85617450284751,+ -12.354419531948796+ ],+ [+ -57.496705306251805,+ -15.049022945530488+ ],+ [+ -58.24035208920829,+ -18.071332931967003+ ],+ [+ -58.405183359908285,+ -20.715199583446015+ ],+ [+ -57.52890661872706,+ -22.800965895880427+ ],+ [+ -59.399371054645485,+ -25.908342433330574+ ],+ [+ -57.05376132642987,+ -27.090482659631096+ ],+ [+ -57.43530098358175,+ -29.452486341089003+ ],+ [+ -55.96299998932042,+ -30.80762832971715+ ],+ [+ -56.142246830344476,+ -33.02920825715391+ ],+ [+ -54.21582754204536,+ -33.97082943587998+ ],+ [+ -52.069212986806036,+ -34.66083164382529+ ],+ [+ -49.97192113564797,+ -35.27677433298823+ ],+ [+ -48.80437308307304,+ -36.49488130837946+ ],+ [+ -49.18454012117508,+ -38.9377609292636+ ],+ [+ -48.22239934632797,+ -40.41665029388307+ ],+ [+ -46.507833210575676,+ -41.290296719114515+ ],+ [+ -45.49707440427719,+ -42.8361296381768+ ],+ [+ -43.81446294860957,+ -43.82502289015341+ ],+ [+ -40.96608170497727,+ -43.64161073220753+ ],+ [+ -39.54546052382939,+ -45.0219267693883+ ],+ [+ -35.88468285271775,+ -43.85819648049005+ ],+ [+ -33.39279791384885,+ -44.0762934622151+ ],+ [+ -31.079320977533587,+ -44.65791658850292+ ],+ [+ -29.13846369707489,+ -46.077005152953014+ ],+ [+ -25.745978223853296,+ -45.49423701444813+ ],+ [+ -23.001458136452005,+ -46.45943151953585+ ],+ [+ -20.003722233898202,+ -47.89941273846971+ ],+ [+ -15.63596445811381,+ -47.47839234615448+ ],+ [+ -10.58590818209214,+ -48.117772075433656+ ],+ [+ -4.652712747556009e-08,+ -49.325259139067164+ ],+ [+ 10.422792995555774,+ -47.37633929207795+ ],+ [+ 16.1069664978563,+ -48.90858360161811+ ],+ [+ 19.357278737223286,+ -46.35148763246826+ ],+ [+ 22.76429592047279,+ -45.980400074357824+ ],+ [+ 25.589014696718298,+ -45.2168757953865+ ],+ [+ 28.82367794470846,+ -45.57923063454836+ ],+ [+ 31.643729826496973,+ -45.46891639499936+ ],+ [+ 34.318187035951446,+ -45.29774614245369+ ],+ [+ 37.40390361783422,+ -45.71498543658008+ ],+ [+ 39.33802720474895,+ -44.785766978164155+ ],+ [+ 41.557065331655046,+ -44.271191993366976+ ],+ [+ 43.0557045872154,+ -43.06608165663433+ ],+ [+ 44.25556995259373,+ -41.66723589423783+ ],+ [+ 45.483602394459695,+ -40.38097045326148+ ],+ [+ 47.053827947064875,+ -39.437235287005244+ ],+ [+ 48.37220519760009,+ -38.294662448100084+ ],+ [+ 49.384711541668196,+ -36.92884617314821+ ],+ [+ 51.10266159723224,+ -36.075000120310115+ ],+ [+ 51.72401521718379,+ -34.431044383938485+ ],+ [+ 52.98115255199477,+ -33.19720049028789+ ],+ [+ 54.468027453812255,+ -32.04424339419163+ ],+ [+ 55.31635820191013,+ -30.451652062311886+ ],+ [+ 57.47521835954482,+ -29.47295573796154+ ],+ [+ 59.623320489631766,+ -28.31057045639083+ ],+ [+ 58.8969662617972,+ -25.689207530348433+ ],+ [+ 59.638392989413525,+ -23.637038222347872+ ],+ [+ 59.13116215996268,+ -20.972690355177786+ ],+ [+ 59.071988085620966,+ -18.32938032402883+ ],+ [+ 57.65811895381695,+ -15.09127089126919+ ],+ [+ 60.198047473582314,+ -12.42498271347805+ ],+ [+ 60.37226430933056,+ -8.324243876736428+ ]+ ],+ "bottom_y": -63.18514451062192,+ "walkable": true+ },+ {+ "id": "bridge-deck",+ "shape": "graded-deck",+ "start": [+ -195,+ -10,+ -10+ ],+ "end": [+ -64,+ 0,+ 0+ ],+ "width": 10,+ "thickness": 0.65,+ "walkable": true+ },+ {+ "id": "communications-mast",+ "shape": "box",+ "center": [+ 0,+ 31,+ -4+ ],+ "size": [+ 14,+ 62,+ 14+ ]+ },+ {+ "id": "dish-west base",+ "shape": "box",+ "center": [+ -42,+ 4.5,+ -4+ ],+ "size": [+ 13.13,+ 9,+ 13.13+ ]+ },+ {+ "id": "dish-east base",+ "shape": "box",+ "center": [+ 31,+ 4.5,+ -29+ ],+ "size": [+ 15.600000000000001,+ 9,+ 15.600000000000001+ ]+ },+ {+ "id": "radome-north",+ "shape": "box",+ "center": [+ -22,+ 8.5,+ -29+ ],+ "size": [+ 17.0,+ 17,+ 17.0+ ]+ },+ {+ "id": "radome-south",+ "shape": "box",+ "center": [+ 31,+ 9.0,+ 19+ ],+ "size": [+ 20.4,+ 18,+ 20.4+ ]+ },+ {+ "id": "operations-west",+ "shape": "box",+ "center": [+ -35.81,+ 4.0,+ 14+ ],+ "size": [+ 0.38,+ 8,+ 14+ ]+ },+ {+ "id": "operations-east",+ "shape": "box",+ "center": [+ -16.19,+ 4.0,+ 14+ ],+ "size": [+ 0.38,+ 8,+ 14+ ]+ },+ {+ "id": "operations-north",+ "shape": "box",+ "center": [+ -26,+ 4.0,+ 7.19+ ],+ "size": [+ 20,+ 8,+ 0.38+ ]+ },+ {+ "id": "operations-south-west",+ "shape": "box",+ "center": [+ -31.75,+ 4.0,+ 20.81+ ],+ "size": [+ 8.5,+ 8,+ 0.38+ ]+ },+ {+ "id": "operations-south-east",+ "shape": "box",+ "center": [+ -20.25,+ 4.0,+ 20.81+ ],+ "size": [+ 8.5,+ 8,+ 0.38+ ]+ },+ {+ "id": "operations-lintel",+ "shape": "box",+ "center": [+ -26,+ 5.5,+ 20.81+ ],+ "size": [+ 3.0,+ 5,+ 0.38+ ]+ },+ {+ "id": "operations-jamb-west",+ "shape": "box",+ "center": [+ -27.35,+ 1.5,+ 21.0+ ],+ "size": [+ 0.3,+ 3,+ 0.6+ ]+ },+ {+ "id": "operations-jamb-east",+ "shape": "box",+ "center": [+ -24.65,+ 1.5,+ 21.0+ ],+ "size": [+ 0.3,+ 3,+ 0.6+ ]+ },+ {+ "id": "operations-roof",+ "shape": "box",+ "center": [+ -26,+ 7.8,+ 14+ ],+ "size": [+ 20,+ 0.4,+ 14+ ]+ },+ {+ "id": "console-desk",+ "shape": "box",+ "center": [+ -26,+ 0.85,+ 11.1+ ],+ "size": [+ 5.4,+ 1.7,+ 1.5+ ]+ },+ {+ "id": "equipment-rack--7.3",+ "shape": "box",+ "center": [+ -33.3,+ 1.35,+ 9.2+ ],+ "size": [+ 1.8,+ 2.7,+ 1.3+ ]+ },+ {+ "id": "equipment-rack-7.3",+ "shape": "box",+ "center": [+ -18.7,+ 1.35,+ 9.2+ ],+ "size": [+ 1.8,+ 2.7,+ 1.3+ ]+ },+ {+ "id": "service-east",+ "shape": "box",+ "center": [+ 43,+ 6,+ -5+ ],+ "size": [+ 12,+ 12,+ 12+ ]+ },+ {+ "id": "service-module-0",+ "shape": "box",+ "center": [+ 3,+ 2.5,+ -24+ ],+ "size": [+ 8,+ 5,+ 7+ ]+ },+ {+ "id": "service-module-1",+ "shape": "box",+ "center": [+ 14,+ 2.5,+ -24+ ],+ "size": [+ 8,+ 5,+ 7+ ]+ },+ {+ "id": "service-module-2",+ "shape": "box",+ "center": [+ 13,+ 2.5,+ 20+ ],+ "size": [+ 8,+ 5,+ 7+ ]+ },+ {+ "id": "district-sign",+ "shape": "box",+ "center": [+ 27,+ 2,+ 35+ ],+ "size": [+ 25,+ 3.5,+ 0.5+ ]+ }+ ],+ "anchors": [+ {+ "id": "outpost-origin",+ "position": [+ 0,+ 0,+ 0+ ],+ "kind": "district",+ "layout_version": 1+ },+ {+ "id": "outpost-west",+ "position": [+ -64,+ 0,+ 0+ ],+ "kind": "navigation"+ },+ {+ "id": "outpost-arrival",+ "position": [+ -52,+ 0,+ 18+ ],+ "kind": "navigation"+ },+ {+ "id": "console-approach",+ "position": [+ -26,+ 0,+ 25+ ],+ "kind": "navigation"+ },+ {+ "id": "outpost-south",+ "position": [+ 5,+ 0,+ 46+ ],+ "kind": "navigation"+ },+ {+ "id": "bridge-colony-end",+ "position": [+ -195,+ -10,+ -10+ ],+ "kind": "navigation"+ },+ {+ "id": "bridge-outpost-end",+ "position": [+ -64,+ 0,+ 0+ ],+ "kind": "navigation"+ },+ {+ "id": "mast-brand-slot",+ "position": [+ 0,+ 12.6,+ -0.14000000000000012+ ],+ "kind": "branding-slot",+ "verified_source": false+ },+ {+ "id": "dish-west mechanism",+ "position": [+ -42,+ 14.8,+ -4+ ],+ "kind": "exterior-equipment",+ "access": "not-accessible"+ },+ {+ "id": "dish-east mechanism",+ "position": [+ 31,+ 18.2,+ -29+ ],+ "kind": "exterior-equipment",+ "access": "not-accessible"+ },+ {+ "id": "communications-console",+ "position": [+ -26,+ 0,+ 14+ ],+ "kind": "station",+ "station_id": "communications-console",+ "backend_authoritative": true+ },+ {+ "id": "console-display",+ "position": [+ -26,+ 1.65,+ 10.81+ ],+ "kind": "display",+ "station_id": "communications-console"+ },+ {+ "id": "operations-door",+ "position": [+ -26,+ 0,+ 21.0+ ],+ "kind": "door",+ "clear_width": 2.4,+ "clear_height": 3.0,+ "state": "open"+ },+ {+ "id": "operations-brand-slot",+ "position": [+ -20.2,+ 5.7,+ 21.2+ ],+ "kind": "branding-slot",+ "verified_source": false+ },+ {+ "id": "district-brand-slot",+ "position": [+ 10,+ 1.6,+ 35.2+ ],+ "kind": "branding-slot",+ "verified_source": false+ }+ ],+ "runtime_evidence": [],+ "limitations": [+ "Runtime appearance, movement and collision integration are not yet verified.",+ "Source includes no character, rover, approved logo or fabricated task activity.",+ "No visual approval or production-catalog promotion is granted.",+ "Material batching reduces object selection granularity; stable anchors remain separate.",+ "Editable source rebuilds may vary in Blender metadata; byte identity is not promised."+ ]+}diff --git a/art/studies/mars-outpost-reference/source/material-attribute-regression.json b/art/studies/mars-outpost-reference/source/material-attribute-regression.jsonnew file mode 100644index 0000000000..0add767525--- /dev/null+++ b/art/studies/mars-outpost-reference/source/material-attribute-regression.json@@ -0,0 +1,66 @@+{+ "kind": "source-and-buffer-regression-evidence",+ "blender_version": "5.0.1",+ "invalid_export_sha256": "c9076e247f6a762c06efde5767a8ecc7dd29167f8c43b5accf868620cf0c0ca5",+ "cause": "Retained UV-layer RNA handle became stale when the color custom-data layer was allocated; later UV writes overwrote color values.",+ "minimal_probe": {+ "intended_color": [+ 0.2,+ 0.3,+ 0.4,+ 1+ ],+ "stale_handle_result": [+ [+ 0.2,+ 0.3,+ 21,+ 31+ ],+ [+ 22,+ 32,+ 0.4,+ 1+ ],+ [+ 0.2,+ 0.3,+ 0.4,+ 1+ ]+ ],+ "reacquired_handles_result": [+ [+ 0.2,+ 0.3,+ 0.4,+ 1+ ],+ [+ 0.2,+ 0.3,+ 0.4,+ 1+ ],+ [+ 0.2,+ 0.3,+ 0.4,+ 1+ ]+ ]+ },+ "invalid_export_rejected": "COLOR_0 outside linear [0, 1] in Batched ceramic",+ "corrected_export_sha256": "c697b08e0b49ad462be7b2e32230183ebb5bb1c2956d21580dc71bd9e95c802e",+ "corrected_numeric_validation": {+ "colored_primitives": 13,+ "linear_color_range": [+ 0.03191685676574707,+ 0.7687839865684509+ ],+ "uv_abs_max": 244.27207946777344+ },+ "geometry_changed": false,+ "runtime_visual_approval": "pending"+}diff --git a/art/studies/mars-outpost-reference/source/material-quality-report.json b/art/studies/mars-outpost-reference/source/material-quality-report.jsonnew file mode 100644index 0000000000..57408cbb9f--- /dev/null+++ b/art/studies/mars-outpost-reference/source/material-quality-report.json@@ -0,0 +1,83 @@+{+ "kind": "material-and-source-buffer-verification",+ "runtime_visual_approval": "pending",+ "glb_sha256": "dde2c6c384f6c05daca459e3def952eb76b56540a220ed9bd6f272b52e27c324",+ "glb_bytes": 15089320,+ "source_sha256": "c233ea227eca1d3d9f4d1e565f6e6e9659ef04024ca56331ea240cb0f28bcec1",+ "source_bytes": 29804549,+ "numeric_material_validation": {+ "colored_primitives": 13,+ "linear_color_range": [+ 0.032668162137269974,+ 0.7518854141235352+ ],+ "uv_abs_max": 977.0883178710938+ },+ "normal_maps": [+ {+ "family": "paint",+ "maximum_encoding_error": 0.0019607912463026067,+ "maximum_normal_tilt_degrees": 1.5883864605532065+ },+ {+ "family": "metal",+ "maximum_encoding_error": 0.0019607698272156027,+ "maximum_normal_tilt_degrees": 0.9531881531811416+ },+ {+ "family": "mineral",+ "maximum_encoding_error": 0.0019608281560691276,+ "maximum_normal_tilt_degrees": 27.268268316224578+ },+ {+ "family": "concrete",+ "maximum_encoding_error": 0.0019607915743717896,+ "maximum_normal_tilt_degrees": 4.313815920532387+ },+ {+ "family": "paving",+ "maximum_encoding_error": 0.0019607244389230893,+ "maximum_normal_tilt_degrees": 2.927041436948962+ },+ {+ "family": "road",+ "maximum_encoding_error": 0.0019607825760971642,+ "maximum_normal_tilt_degrees": 4.713162903302976+ }+ ],+ "bounds_unchanged": true,+ "local_runtime_bounds": {+ "min": [+ -195.43536376953125,+ -63.18514633178711,+ -49.922935485839844+ ],+ "max": [+ 63.38080978393555,+ 62.0,+ 51.0+ ]+ },+ "anchors_unchanged": true,+ "colliders_unchanged": true,+ "unchanged_geometry_batches": [+ "Batched blue",+ "Batched ceramic",+ "Batched ceramic-warm",+ "Batched dust-coated",+ "Batched glass",+ "Batched gold",+ "Batched marking",+ "Batched metal",+ "Batched ochre",+ "Batched painted-alloy",+ "Batched roof-alloy",+ "Batched rubber",+ "Batched screen",+ "Batched structure",+ "Batched warm-light"+ ],+ "source_profile_marker_occurrences": 0,+ "material_profile_count": 6,+ "definition_sha256": "1dae7897e477201b1a859fcc813e7ff5111982a2f2a330bd872245b67eb35c2d"+}diff --git a/art/studies/mars-outpost-reference/source/materials/ceramic-roughness.png b/art/studies/mars-outpost-reference/source/materials/ceramic-roughness.pngnew file mode 100644index 0000000000..4c8148684cBinary files /dev/null and b/art/studies/mars-outpost-reference/source/materials/ceramic-roughness.png differdiff --git a/art/studies/mars-outpost-reference/source/materials/ceramic-warm-roughness.png b/art/studies/mars-outpost-reference/source/materials/ceramic-warm-roughness.pngnew file mode 100644index 0000000000..e28a3e0056Binary files /dev/null and b/art/studies/mars-outpost-reference/source/materials/ceramic-warm-roughness.png differdiff --git a/art/studies/mars-outpost-reference/source/materials/cliff-roughness.png b/art/studies/mars-outpost-reference/source/materials/cliff-roughness.pngnew file mode 100644index 0000000000..ac8de75191Binary files /dev/null and b/art/studies/mars-outpost-reference/source/materials/cliff-roughness.png differdiff --git a/art/studies/mars-outpost-reference/source/materials/concrete-normal.png b/art/studies/mars-outpost-reference/source/materials/concrete-normal.pngnew file mode 100644index 0000000000..b9892d26ecBinary files /dev/null and b/art/studies/mars-outpost-reference/source/materials/concrete-normal.png differdiff --git a/art/studies/mars-outpost-reference/source/materials/concrete-roughness.png b/art/studies/mars-outpost-reference/source/materials/concrete-roughness.pngnew file mode 100644index 0000000000..96c1a760e6Binary files /dev/null and b/art/studies/mars-outpost-reference/source/materials/concrete-roughness.png differdiff --git a/art/studies/mars-outpost-reference/source/materials/dust-coated-roughness.png b/art/studies/mars-outpost-reference/source/materials/dust-coated-roughness.pngnew file mode 100644index 0000000000..df2463f03aBinary files /dev/null and b/art/studies/mars-outpost-reference/source/materials/dust-coated-roughness.png differdiff --git a/art/studies/mars-outpost-reference/source/materials/gold-roughness.png b/art/studies/mars-outpost-reference/source/materials/gold-roughness.pngnew file mode 100644index 0000000000..d3aa90c280Binary files /dev/null and b/art/studies/mars-outpost-reference/source/materials/gold-roughness.png differdiff --git a/art/studies/mars-outpost-reference/source/materials/metal-normal.png b/art/studies/mars-outpost-reference/source/materials/metal-normal.pngnew file mode 100644index 0000000000..4f4bbc7aabBinary files /dev/null and b/art/studies/mars-outpost-reference/source/materials/metal-normal.png differdiff --git a/art/studies/mars-outpost-reference/source/materials/metal-roughness.png b/art/studies/mars-outpost-reference/source/materials/metal-roughness.pngnew file mode 100644index 0000000000..142a4b933bBinary files /dev/null and b/art/studies/mars-outpost-reference/source/materials/metal-roughness.png differdiff --git a/art/studies/mars-outpost-reference/source/materials/mineral-normal.png b/art/studies/mars-outpost-reference/source/materials/mineral-normal.pngnew file mode 100644index 0000000000..6c95e68347Binary files /dev/null and b/art/studies/mars-outpost-reference/source/materials/mineral-normal.png differdiff --git a/art/studies/mars-outpost-reference/source/materials/paint-normal.png b/art/studies/mars-outpost-reference/source/materials/paint-normal.pngnew file mode 100644index 0000000000..9c4687a63dBinary files /dev/null and b/art/studies/mars-outpost-reference/source/materials/paint-normal.png differdiff --git a/art/studies/mars-outpost-reference/source/materials/painted-alloy-roughness.png b/art/studies/mars-outpost-reference/source/materials/painted-alloy-roughness.pngnew file mode 100644index 0000000000..0d1b449c66Binary files /dev/null and b/art/studies/mars-outpost-reference/source/materials/painted-alloy-roughness.png differdiff --git a/art/studies/mars-outpost-reference/source/materials/paving-normal.png b/art/studies/mars-outpost-reference/source/materials/paving-normal.pngnew file mode 100644index 0000000000..8d6bbda095Binary files /dev/null and b/art/studies/mars-outpost-reference/source/materials/paving-normal.png differdiff --git a/art/studies/mars-outpost-reference/source/materials/paving-roughness.png b/art/studies/mars-outpost-reference/source/materials/paving-roughness.pngnew file mode 100644index 0000000000..018c67188eBinary files /dev/null and b/art/studies/mars-outpost-reference/source/materials/paving-roughness.png differdiff --git a/art/studies/mars-outpost-reference/source/materials/road-normal.png b/art/studies/mars-outpost-reference/source/materials/road-normal.pngnew file mode 100644index 0000000000..fa9fc56d07Binary files /dev/null and b/art/studies/mars-outpost-reference/source/materials/road-normal.png differdiff --git a/art/studies/mars-outpost-reference/source/materials/road-roughness.png b/art/studies/mars-outpost-reference/source/materials/road-roughness.pngnew file mode 100644index 0000000000..b441487616Binary files /dev/null and b/art/studies/mars-outpost-reference/source/materials/road-roughness.png differdiff --git a/art/studies/mars-outpost-reference/source/materials/rock-highlight-roughness.png b/art/studies/mars-outpost-reference/source/materials/rock-highlight-roughness.pngnew file mode 100644index 0000000000..4cf5eceb54Binary files /dev/null and b/art/studies/mars-outpost-reference/source/materials/rock-highlight-roughness.png differdiff --git a/art/studies/mars-outpost-reference/source/materials/rock-shadow-roughness.png b/art/studies/mars-outpost-reference/source/materials/rock-shadow-roughness.pngnew file mode 100644index 0000000000..5d8cf7ce54Binary files /dev/null and b/art/studies/mars-outpost-reference/source/materials/rock-shadow-roughness.png differdiff --git a/art/studies/mars-outpost-reference/source/materials/roof-alloy-roughness.png b/art/studies/mars-outpost-reference/source/materials/roof-alloy-roughness.pngnew file mode 100644index 0000000000..3c7989af46Binary files /dev/null and b/art/studies/mars-outpost-reference/source/materials/roof-alloy-roughness.png differdiff --git a/art/studies/mars-outpost-reference/source/materials/structure-roughness.png b/art/studies/mars-outpost-reference/source/materials/structure-roughness.pngnew file mode 100644index 0000000000..1e12dfa8b6Binary files /dev/null and b/art/studies/mars-outpost-reference/source/materials/structure-roughness.png differdiff --git a/art/studies/mars-outpost-reference/source/public-source-report.json b/art/studies/mars-outpost-reference/source/public-source-report.jsonnew file mode 100644index 0000000000..05cd1cb458--- /dev/null+++ b/art/studies/mars-outpost-reference/source/public-source-report.json@@ -0,0 +1,27 @@+{+ "kind": "public-editable-source-metadata-verification",+ "field_classes_sanitized": {+ "Image.filepath": 20,+ "ImagePackedFile.filepath": 20,+ "FileSelectParams.dir": 1,+ "RenderData.pic": 1+ },+ "source_native_encoding": "uncompressed",+ "profile_marker_families_checked": 4,+ "raw_marker_occurrences": 0,+ "serialized_content_marker_occurrences": 0,+ "blender_reopen": {+ "version": "5.0.1",+ "portable_fields_validated": 42,+ "export_meshes": 20,+ "triangles": 212724,+ "packed_material_images": 20+ },+ "source_bytes": 29804549,+ "source_sha256": "c233ea227eca1d3d9f4d1e565f6e6e9659ef04024ca56331ea240cb0f28bcec1",+ "glb_sha256": "dde2c6c384f6c05daca459e3def952eb76b56540a220ed9bd6f272b52e27c324",+ "glb_unchanged": false,+ "geometry_changed": true,+ "runtime_visual_approval": "pending",+ "scope": "Normal-map source packing and portable path records were verified after a clean rebuild and Blender reopen; source remains editable."+}diff --git a/art/studies/mars-outpost-reference/study.json b/art/studies/mars-outpost-reference/study.jsonnew file mode 100644index 0000000000..5db560e1d2--- /dev/null+++ b/art/studies/mars-outpost-reference/study.json@@ -0,0 +1,25 @@+{+ "schema": 1,+ "study": "mars-outpost-reference",+ "brief": "brief.md",+ "assets": [+ {+ "id": "communications-outpost-reference",+ "kind": "building",+ "source": "source/communications-outpost.blend",+ "collection": "Export",+ "export": "exports/communications-outpost.glb"+ }+ ],+ "runtime_evidence": [],+ "technical_report": "",+ "approval": {+ "status": "pending",+ "record": "review.md",+ "evidence_sha256": ""+ },+ "reference_manifest": {+ "path": "references/manifest.json",+ "sha256": "c2367be8a0328851253f70695cb12c0c6b8976887986fa5c4907bf0fec5aade5"+ }+}diff --git a/docs/adr/0035-realtime-native-tools-except-computer-use.md b/docs/adr/0035-realtime-native-tools-except-computer-use.mdindex 09b01ee677..039fabd2d7 100644--- a/docs/adr/0035-realtime-native-tools-except-computer-use.md+++ b/docs/adr/0035-realtime-native-tools-except-computer-use.md@@ -2,6 +2,11 @@**Status:** Accepted · **Date:** 2026-08-19 · **Phase:** Voice UX, realtime engine (every transport, every provider)+**Continuous voice amendment (2026-09-19):** The new GPT-Live and native live+orchestrators follow [ADR-0036](0036-continuous-voice-and-agent-selection.md).+This decision remains the reference for the legacy realtime session during+migration qualification.+## ContextMaintainer mandate (2026-08-19): the realtime voice model must be allowed todiff --git a/docs/adr/0036-continuous-voice-and-agent-selection.md b/docs/adr/0036-continuous-voice-and-agent-selection.mdnew file mode 100644index 0000000000..13f14c6a00--- /dev/null+++ b/docs/adr/0036-continuous-voice-and-agent-selection.md@@ -0,0 +1,80 @@+# ADR-0036 — Continuous voice and one active agent selection++**Status:** Implemented; cross-platform release acceptance pending+**Date:** 2026-09-19+**Reference:** GPT-Live migration; ADR-0035++## Context++The legacy realtime session combines provider events, turn routing, task+delegation, audio and transcript handling. The separate Tool Model setting can+also select a different billing account from the user's active agent. GPT-Live+provides continuous voice with managed Responses delegation, requiring different+session and continuation semantics from the older Realtime API.++## Decision++The continuous voice adapters use `jarvis/live` and a shared tool gateway.+OpenAI uses the explicitly chosen Responses thinking model for delegation and+voice-triggered computer control, with the same OpenAI credential. Gemini and+local providers use their own tool-capable protocol; capability failures are+reported explicitly. All local actions still pass through ToolExecutor.++Browser/WebView audio owns simultaneous microphone capture and playback.+OpenAI uses WebRTC with a server control connection, or a primary WebSocket for+server audio. Native provider adapters preserve their required turn mechanics.+Neither the routing heuristics nor forced result readback in ADR-0035 apply to+the continuous OpenAI adapter. Cloud recording is disabled by default.++Text chat and scheduled tasks use the selected `brain.worker` access. A task+captures that selection at entry and carries it through nested operations;+changing settings only affects later tasks. Subscription execution uses scoped+Jarvis MCP grants and fails explicitly when runner isolation is unavailable.++Speech termination leaves already-started work alive. Explicit task cancellation+invalidates the current execution generation and its approvals. A new user+request can proceed without reviving the cancelled work. Receipts, revisions,+argument validation and approval checks remain application responsibilities.++Reconnection pays a shared budget and adds jitter. Only sessions without pending+actions, uncertain results or approvals recover automatically. Recovery seeds+bounded history and verified receipts, discards buffered audio and requires new+user input before further execution. Interrupted usage stays unconfirmed.++## Consequences++- One OpenAI credential serves voice and its thinking backend; connected plugins+ still require their own authorization.+- Model changes require an explicit settings choice; no hidden billing fallback+ substitutes another account for a selected agent.+- The full catalog remains reachable through discovery and invocation even when+ the initial provider declaration set is bounded.+- Unsafe-to-replay sessions end with an actionable error instead of resuming an+ action whose outcome is unknown.+- Legacy sessions and configuration aliases remain during qualification.+ Their removal is not established by a synthetic API test.++## Alternatives considered++- Renaming the legacy Realtime model: rejected because Live delegation and+ continuous audio have different event and continuation contracts.+- Removing local authorization with the old router: rejected because model+ intelligence does not provide action receipts or user approval.+- Replaying every disconnected tool call: rejected because the transport can+ fail after an external side effect has already happened.++## Acceptance still required++This is a T3 change. Contract tests and forced-loss probes cover protocol and+execution semantics, not the complete product matrix. A fresh Python 3.11 slim+wheel installation boots without PortAudio, passes the Live contracts and an+isolated one-key synthetic tool/reconnect probe. The settings form has been+inspected in both themes. Native Windows, macOS and Linux audio, fresh desktop+installations, complete one-key and subscription journeys, offline tools, all+tool families, long conversations, and a comparative median-latency/success-rate+benchmark remain release gates. The catalog still needs per-model capability+qualification, including reasoning levels and native asynchronous tool support.++Keep the migration draft until those results are recorded. Do not remove the+legacy recovery path or claim a latency improvement from the synthetic probe's+single first-audio measurement.diff --git a/docs/agent-society/mars-runtime.md b/docs/agent-society/mars-runtime.mdnew file mode 100644index 0000000000..7c0c2a4be8--- /dev/null+++ b/docs/agent-society/mars-runtime.md@@ -0,0 +1,198 @@+# Mars runtime reference++Status: development reference, not the completed colony. **Agents > Map** opens+Mars directly in both normal and Dev instances and offers no previous-world+selector, including when an older URL requests another world. The Agents workspace and communications-station+controls remain separate from rendering. Final character/rover art, player+boarding and remaining districts are unfinished.+The art study has no user visual approval and must not be rolled out by family.++The communications-station button is available in the Agents workspace+without mounting the map or selecting a preview first. Browser fullscreen exit preserves a focused Mars+form or player view; use the Agents tab to leave that view explicitly.++## Boundaries++The packaged `jarvis/society/mars/definition.json` defines metre/Y-up placement,+stable district/building/station IDs and navigation version. The frontend copy+is synchronized by `python scripts/sync_mars_definition.py --check` and a+contract test. No old-world terrain or figure art is the new visual foundation.+Existing agent IDs, custom imports, recipes and old-world preferences remain+unchanged. Existing world URL parameters cannot restore the retired map surface.++The communications console accepts a bounded draft request through the existing+Society scheduler and the chosen agent's read-only chat runner. It does not send+mail or publish content. Credential-shaped input is rejected before persistence.+Request identity, station ownership, fencing and task/result references are+durable; failed or uncertain outcomes never become animation-driven success.+The renderer is not an execution dependency. Unknown outcomes are reconciled+without blindly repeating dispatch or cancellation.++The `mars` OpenAPI group provides definition, snapshot, bounded cursor events,+draft submission and scoped cancellation, plus physical visit snapshots,+pedestrian visit requests and movement-only stops. Dynamic CLI discovery respects the+selected server and isolates cached schemas by its full base URL. Example:++```text+jarvis --url http://127.0.0.1:47869 api mars --help+jarvis --url http://127.0.0.1:47869 --json api mars get-mars-snapshot+jarvis --url http://127.0.0.1:47869 --json api mars get-mars-navigation-snapshot+```++## Physical visits++The communications panel can send a real active roster member to the console,+operations entrance or bridge waiting area. Visiting does not start a provider+turn, and stopping a visit does not cancel the agent's work. A stopped agent+remains physically present; moving it to the bridge waiting area frees the+console route. The entrance is a usable destination on that route, so waiting+there deliberately blocks through traffic.++Visit identity, graph version, position and occupancy are durable. Physical+bodies survive intent-lease expiry, cancellation and process restart; only+actual departure clears their occupied resources. Movement rechecks roster+authority and the kill switch. Routes, snapshots and actor counts are bounded.+The process advances movement independently of renderer frames and draft-task+inspection; clients display confirmed positions, with only short interpolation+on the same graph segment. Spawn queues are not rendered as physical actors.+The visit API remains pedestrian-only. Rover journeys have a separate explicit+reservation and boarding contract, described below.++The renderer currently uses named location markers while final worker art is+pending. An optional Gigi companion uses the existing assistant's presentation+state and opens its existing chat. It creates no second assistant or audio+session. Camera focus requests live outside the Canvas so graphics recovery+cannot replay an already-consumed focus action.++Choose an agent in the follow control or beside its location marker to follow+its confirmed position. The camera keeps the same identity across replacement+visits and holds its last confirmed view offline. A fresh snapshot showing a+missing actor ends follow safely. Stopping a visit leaves its physical actor+present; stopping camera follow does not change the visit or the agent's work.+Dragging the view, choosing another camera mode, focusing Gigi or pressing+Escape in the focused viewport relinquishes follow. Browser fullscreen exit+also stops focused follow while preserving the map and unrelated forms.+Follow identity and camera preferences are local to the client and world.++## Route-driven rover development slice++The communications panel exposes one rover for real active roster agents. Reserve+its seat, wait for the agent to reach the boarding anchor, explicitly board, and+choose Operations approach or South overlook. The two stops share the existing+Outpost road. Stop retains the vehicle and passenger in place; Exit succeeds only+at a stopped dock with a free, supported exit. If the primary exit is occupied,+the server checks the alternative. An interrupted response retains the exact+request identity for an explicit retry, including after the original agent is+archived. New actions still require current authority.++This is a functional transport slice with location labels. Final authored rover+geometry, animations and player boarding remain unfinished. The local walk+controller is not a server-owned passenger. Camera selection does not release a+seat, and an attached agent has no second pedestrian body at its earlier location.+Agent work continues through the existing scheduler independently of travel.++Seats, bodies, ride receipts and pedestrian/vehicle conflict resources use one+transaction in `navigation.db`. The existing process owner advances journeys with+zero clients. Process downtime preserves exact placement; ten-minute wall-clock+deadlines continue to expire. Expiry cancels an unboarded reservation or stops a+boarded journey without dropping its passenger. A new travel action starts a fresh+bounded journey. Revoked authority stops motion; it does not silently erase a body.++Packaged support and wall geometry is projected from the authored Outpost contract+with `python scripts/art/project_mars_collision.py --check`. Graph subdivisions+retain the existing rendered roads. A stored placement migrates only when its+source graph and unchanged geometry can be proved. An unmapped physical body+stops further motion and admission until a valid migration is available; changed+edge identifiers cannot make the old obstacle disappear.++The dynamic `mars` CLI group exposes `reserve-mars-rover`, `board-mars-rover`,+`travel-mars-rover`, `cancel-mars-rover` and `exit-mars-rover`. Use the named agent+and ride identifiers and preserve `request_id` when retrying an uncertain action.+These controls never dispatch a model task or allow animation to grant a seat.++The `ea3aab13a` installed wheel passed fourteen headless checks in a fresh Linux+venv, including actual rover boarding, route completion, safe exit and completed+action replay. A separate one-key communication draft completed with durable+references and clean shutdown. These operational checks do not establish visual+quality, player boarding or a browser walkthrough of the rover controls.++## Window ownership++Background mode is explicit, default-off and session-only. On supported Windows+hosts it requires persistent WebView storage and confirmed native tray presence.+Closing the real client window then retains a blank hidden GUI keeper and the+owning backend. Reopening restores a new authenticated window; disabling the+mode restores the ordinary close-to-quit policy. Explicit Quit still ends work.+Browser-dependent voice is not retained by the keeper.++Other desktop backends currently report this mode unavailable until native tray+registration can be proved. Their ordinary windows and headless server remain+available. No Windows SYSTEM service or server-side graphics renderer is added.+Local work cannot continue when its execution host is stopped or asleep.++Windows native closure/reopening and a real draft continuing after window+destruction have been measured. A clean installed wheel in an isolated Linux+venv also completed real station work with one Gemini key, no display, graphics+GPU, browser or Blender, and retained the result after clean process shutdown.+Direct tray-menu interaction, other native OSes, host sleep/reboot and final graphics/performance+acceptance are still open; the private issue tracker retains the full ledger.++## Restart recovery++An existing `mars/ordinary.db` or `mars/navigation.db` under the configured data directory schedules+recovery after the server boot chain yields. No browser tab, desktop renderer or+HTTP request is needed to start that recovery. An installation without either+journal does not construct the Society runtime or create Mars storage for it.+The initial HTTP request and deferred recovery share one application-owned+initialization task with a thirty-second deadline, service and journal owner.+An individual HTTP disconnect cannot cancel initialization for other waiters.+Explicit server stop fences late initialization, cancels and joins the owned+startup/reconciliation/movement tasks, then closes both journals before Society shutdown.+A collaborator that ignores cancellation produces an explicit shutdown timeout+after five seconds; it cannot publish a late station owner. The server retains+the Mars stop latch and task references, completes independent browser, chat,+plugin, watcher, terminal and server teardown, then reports the incomplete Mars+cleanup. A Mars timeout must not leave those unrelated resources running.++Society teardown also fences lazy creation before its first await, rejects late+roster requests, and releases the complete runtime and SQLite connection.+Browser cleanup retains ownership and terminates its children even when graceful+shutdown is cancelled. These paths have real-process and startup-race regressions.+In the installed Linux navigation run, boot took 6.013 seconds and graceful exit+took 1.823 seconds; the separate single-key draft run exited in 0.916 seconds.+These are observations of those runs, not latency guarantees.++Acknowledged queued requests are checked against current agent authority before+dispatch. Previously owned work receives a new fence and an interruption event;+the existing executor inspects its stable command/task identity rather than+dispatching it again. Completed result references remain unchanged. An outcome+the executor cannot establish stays uncertain and holds the station for+reconciliation; this does not promise exactly-once external effects.++The portable lifecycle contract exercises separate abrupt-exit and recovery+processes at queued, active and result-committed checkpoints, using real SQLite+and a clearly labeled test executor. It also covers concurrent first access,+authority revocation, startup/shutdown races and private error logging. This is+local process-failure evidence; actual host power loss, sleep/reboot, unavailable+provider recovery and live external-outcome reconciliation remain separate+acceptance work. SQLite rollback is joined even if cancellation occurs while+BEGIN is executing or a second cancellation arrives during rollback, before+the connection lock is released for reuse. No OS-specific lifecycle API or new execution scheduler is+introduced by this recovery path.++## Art and verification++Editable Blender source, recipes and isolated exports live in+`art/studies/mars-outpost-reference`. Runtime users need only the packaged GLB;+they do not install Blender or obtain private reference images. Original concept+inputs remain private. The source recipe validates packed portable paths,+geometry, UVs, normals and linear vertex colors; numeric tests do not approve+appearance. See the study source README for rebuild commands and limitations.+The Gigi companion's separate editable source is under+`art/studies/gigi-hover-companion`. Neither study grants colony-family rollout+or replaces imported user figures. Full Outpost visual approval remains open.++Focused checks live in `tests/contract/test_mars_*.py`, the Mars unit tests,+`tests/unit/test_outpost_reference.py`, and frontend `components/society/mars`.+Keep functional, visual and operational acceptance separate. A successful+compile or technical export is not approval of the finished Outpost.diff --git a/docs/gpt-live.md b/docs/gpt-live.mdindex c0849a3420..b29db621d0 100644--- a/docs/gpt-live.md+++ b/docs/gpt-live.md@@ -17,6 +17,12 @@ Text chat and background work follow the active Agents selection. The OpenAIvoice thinking model is also used for voice-triggered computer control withoutanother model key. Connected services retain their own credentials.+Voice setup is a single provider panel with a shared credential, conversation+settings and thinking/tool settings. Inspecting a provider does not activate it;+the Live profile saves its provider and model together. The separate Tool Model+tab and inline computer-control model pickers are removed. Saving only refreshes+the affected voice queries and preserves a draft when a key becomes available.+## Execution and mediaThe `jarvis/live` package separates the provider connection, transcript stream,@@ -37,26 +43,68 @@ and already-started work can finish after speech closes. Subscription tasks usethe same gateway with a scoped tool grant; unsupported isolation is reportedinstead of silently using another account.+An explicit task cancellation invalidates queued calls and pending approvals.+The next user request gets a new cancellation token, while interrupted work+retains its cancelled token. Scheduled turns keep their starting agent selection+through settings changes, including nested computer-control calls.+Transcripts keep their original fragments and timestamps. The legacy archivestores one compatibility group at close, not a fabricated provider turn boundary.Voice duration updates are cumulative snapshots. Backend completion, generatedspeech and actual playback are separate states.+## WebRTC wire limits++SDP offers and answers retain their terminal CRLF through browser and server+validation. Trimming an otherwise valid offer was reproduced as HTTP 400 from+Live, while the unchanged offer was accepted.++The initial tool declarations have both a count and a 24 KB JSON budget. A count+limit alone allowed large imported schemas to overflow a 64 KiB RTC data-channel+message before `session.started`. Discovery returns pages with `next_offset`;+the full catalog remains reachable through discovery and `call_tool`.+## QualificationSynthetic live API probes have exercised tool execution, response continuationand spoken results on OpenAI and Gemini. Contract tests run on Windows and in a-headless Python 3.11 Linux container. These checks do not establish native audio-parity or release readiness. Native macOS/Linux audio, fresh installations,-long-session recovery and comparative latency still require qualification.+headless Python 3.11 Linux container. A fresh base wheel installation on+`python:3.11-slim` boots a healthy API without PortAudio. An isolated OpenAI+synthetic probe using exactly one credential also passes there, including a+forced reconnect and exactly one tool execution. These checks do not establish+native audio parity or release readiness. Native-device audio, fresh desktop+installations, long-session recovery and comparative latency still require qualification.-Transport failures currently stop the call. Automatic reconnection with restored-conversation state still needs implementation and verification before full migration.+Safe transport failures reconnect with jitter and a shared connection budget.+Recovery restores bounded conversation history and completed tool receipts;+it never replays buffered microphone audio. New actions wait for fresh user+input. Pending approvals, running actions or uncertain outcomes prevent automatic+reconnection. Missing final usage remains marked unconfirmed across reconnects.++Synthetic OpenAI and Gemini probes have recovered from forced connection loss,+spoken the previous verified result and kept the tool execution count at one.+These probes do not replace long-call or native-device qualification.Run `python scripts/verify_gpt_live.py --run-live` for the opt-in OpenAI syntheticprobe. The test uses configured credentials and incurs normal API usage; itcaptures neither microphone nor screen data. Gemini is selectable with`--provider gemini --model gemini-3.1-flash-live-preview`.+Add `--reconnect` to verify recovery after a forced connection loss.++The architecture decision and remaining acceptance requirements are recorded in+[ADR-0036](adr/0036-continuous-voice-and-agent-selection.md).++The settings form has been inspected in light and dark themes. Its provider+test uses the continuous session contract and waits for `session.started`;+browser-owned media no longer waits for the legacy desktop offer broker.+The separate Live profile owns model and voice selection without duplicate+legacy pickers on the provider card.++A synthetic check through the running application's authenticated `/ws/audio`+route now establishes WebRTC, receives `session.started`, completes the real+read-only `describe-app-settings` tool through the gateway and receives spoken+confirmation as non-silent RTP audio. It captures no microphone or screen data.+The transport checks do not replace physical device and acoustic-echo tests.References: [OpenAI architecture](https://developers.openai.com/api/docs/guides/live),[delegation](https://developers.openai.com/api/docs/guides/live-delegation),diff --git a/docs/os-parity.md b/docs/os-parity.mdindex 67af938319..a8f2131757 100644--- a/docs/os-parity.md+++ b/docs/os-parity.md@@ -1,5 +1,20 @@# OS Feature Parity — macOS / Linux Gap Register+## Window caption (2026-09-21, T2)++The desktop window is frameless on Windows, macOS and Linux. The page draws+one title strip: drag to move, and theme, restart, minimize, maximize and+close at the end of that row. macOS puts the window buttons on the left;+Windows and Linux put them on the right. A browser tab and a headless server+draw no window buttons (`frameless: false`).++Windows adds edge resize and a maximized work-area inset in+`jarvis/ui/window_frame.py`, so the missing native frame does not cover the+taskbar. macOS keeps pywebview's resizable window mask. Linux stays+undecorated: moving and the buttons work; dragging an edge to resize depends+on the window manager and is not claimed as parity. Tests:+`tests/unit/ui/test_window_command.py` and `tests/unit/ui/test_window_frame.py`.+## Prepaid search hop (2026-09-17, T2)`search_web` may use an optional Apifare HTTP hop@@ -16,9 +31,11 @@ transports. Browser audio is selected by provider capability and owns echocancellation on desktop and remote surfaces. OS-specific capture and actuationremain behind the existing screen/desktop adapters and ToolExecutor.-Windows contract tests, an OpenAI API synthetic tool-and-audio test, and a Python-3.11 Linux-container contract run passed. Native macOS audio, native Linux audio,-fresh installations, long-call recovery and comparative latency remain unverified.+Windows contract tests, OpenAI/Gemini synthetic tool-and-audio recovery probes,+and a fresh Python 3.11 slim installation passed. The Linux installation boots+without PortAudio and passes the 34 Live contract cases plus an isolated OpenAI+one-key synthetic tool/reconnect probe. Native-device audio, fresh desktop+installations, long-call recovery and comparative latency remain unverified.See [the continuous voice architecture](gpt-live.md).## Full Chrome window preview (2026-09-12, T3; acceptance open)@@ -53,6 +70,63 @@ tested for all three platform values, and HTTP requests use fake transports.Real account consent and live AMD hardware remain separate acceptance steps.See [coverage and provider limits](marketplace/service-connector-coverage.md).+## Mars world reference foundation (2026-09-19, in progress)++The new Mars namespace uses a packaged metre/Y-up definition and the existing+React/Three client on Windows, macOS and Linux. Rendering is optional and gated+by the shared WebGL capability probe; Agents/status remains accessible without+it. Authoring uses Blender only in development. No native graphics or authoring+dependency enters the Python definition or station interfaces.++The implementation is T3 and unfinished. Windows native close/reopen and+clientless task progress are verified: 213 observations recorded an active+real draft after main-window destruction, followed by completion and an+authenticated reopen under the same backend. The default close policy remains+Quit unless the user enables background mode for that session. This mode needs+persistent WebView storage and verified native tray registration. The blank+keeper has no application URL; browser-dependent voice is not kept alive.++Native tray registration is currently proved on Windows only. Other desktop+backends report background mode unavailable while ordinary windows and the+headless server remain usable. Native macOS/Linux WebViews and integrated-GPU+performance remain unverified. Tests with fakes do not establish those device results.++A clean wheel from `9e155de95` was installed into a new isolated Linux venv in+a container without a display, graphics GPU, browser or Blender. Its 3,436+package members matched the wheel and `pip check` passed. Actual HTTP visits,+occupancy, idempotency, status and clientless progress passed. A separate+isolated runtime used one existing Gemini key for a real station draft with+durable task/result references and no tool calls. The result remained after+clean backend and container exit. Client readiness waited for a live active+brain from `/api/providers`; early roster readiness alone does not prove it.+These results cover headless operation and process shutdown. Native desktop+parity, active-task cancellation in that installed-wheel run, and final visual+acceptance remain separate checks.+See [the Mars runtime](agent-society/mars-runtime.md) for current support boundaries.++The route-driven rover increment uses the same SQLite/asyncio owner on Windows,+macOS and Linux. It requires packaged collision/dock data and an explicit rover+authorization callback; pedestrian authority alone grants no seat. Agent rides+need no renderer, GPU, audio or native API. Portable contracts cover exclusive+seats, safe exits, interrupted travel, graph migration and authenticated HTTP/CLI+actions. A fresh Linux venv then installed the rover wheel from `ea3aab13a`:+all 3,439 package members matched, dependency validation passed, and fourteen+headless checks passed, including real-agent boarding, travel and safe exit.+A separate runtime in that fresh environment completed a real communication+draft with one Gemini key and retained its result after clean shutdown. No+browser, display, graphics GPU or Blender was required. Final rover art, player+control and native cross-platform presentation remain unverified.++Physical pedestrian visits use the same bounded SQLite/asyncio graph controller+on Windows, macOS and Linux, with no native graphics requirement. The existing+world owner resumes either station or navigation journals after boot; no-client+movement, process-abort recovery, authority checks and repeated-cancellation+rollback are covered by portable contracts. The ordinary-world HTTP surface is+pedestrian-only; rover control and per-Swarm adapters remain unfinished. These+contracts do not establish live native macOS/Linux rendering or fresh-install+acceptance. Gigi is a client presentation over the existing assistant, not a+new provider, worker scheduler or audio process.+**Managed agent browser, 2026-09-10:** The Browser-Use environment and browserare provisioned per host with one shared installer. The live viewport usesCDP pixels over the authenticated app WebSocket, including on headless Linux;@@ -532,6 +606,32 @@ install verification are not claimed. See [the inventory and design](chat-tool-p## Internal agent messaging — RUB-14 (2026-09-07)+### Contextual communication and reply expectations (2026-09-23)++The lead, realtime directive and teammate briefings share the same guidance:+compose an actionable objective with known context, scope and completion evidence.+The existing envelope JSON carries optional `reply_policy` metadata+(`none`, `on_error`, `always`). Questions require an answer; answers close the+exchange. Delivery receipts remain separate from task outcomes. Legacy assignments+keep completion reporting. No SQL status, REST field or frontend enum is added:+SQLite and Pydantic preserve the payload and TypeScript exposes it as an opaque+record; the UI continues to render message text and existing delivery states.++Windows, macOS and Linux use identical pure Python, asyncio and SQLite paths,+behind the existing runtime/chat-service capability boundary. No native, GPU or+audio dependency is added. API and CLI seats receive the same guidance. The chat+completion hook sends one correlated answer when a receiver only writes its final+response. Explicit answers suppress that fallback. Task completion remains in the+board even when notifications are suppressed. An explicit blocker is reflected in+the assignment outcome, and the runtime alone forwards that outcome.++The legacy mission runner retains its existing reporting for `always`; it refuses+quiet policies when no agent chat service is available instead of promising silence+it cannot enforce. `tests/contract/test_society_communication.py` covers the reporting+matrix, scheduler delivery, durable reply identity, terminal answers, semantic+blockers and compatibility. Windows execution does not establish native macOS/Linux+or a fresh single-key live-provider qualification; those require separate evidence.+The message tool, durable SQLite queue, task-local sender provenance, and chatreceipts use the same Python/React implementation on Windows, macOS and Linux.There are no native imports, GPU requirements, or provider-name gates. The@@ -635,3 +735,176 @@ provider authorization may remain at the provider because revoking it could alsoinvalidate a shared existing grant. Users can revoke it in the provider's appsettings. The release audit separately requires a real safe action, disconnect,reconnect and persistence after restart.++## Routine model seat pinning (2026-09-20, T2)++| Capability | Windows | macOS | Linux / headless |+| --- | --- | --- | --- |+| Routine runs on its pinned seat (or the owner's live seat) | Same portable resolution | Same portable resolution | Same portable resolution |+| No silent reroute onto an API-key chain | Fails honestly with a readable error | Same | Same |+| Per-routine seat picker in the routine editor | Same React component | Same | Same |++One surface (society routine execution); the shared `AgentAction` contract gains+four optional seat fields that default empty, so stored rows from before this+change still validate and behave as before (follow the owner). Seat kinds are+decided by asking the runner/catalog (AP-21), never by provider name; a vendor+CLI that is not installed on the host fails the run honestly instead of billing+a key. Portable contracts: `tests/unit/society/test_routines.py` (pin, inherit,+update), `tests/unit/tasks/test_runner_agent_result.py` (no API fallback for+society tags, generic fallback kept), `tests/unit/ui/web/test_routine_editor.py`.+Physical macOS/Linux runs and a fresh-install end-to-end check remain open+acceptance and must not be inferred from these tests.++## Browser media presentation (T3)++| Surface | Windows | macOS | Linux / headless |+| --- | --- | --- | --- |+| Browser microphone and audible-output meters | Shared Web Audio measurement | Same browser adapter | Same adapter; remote browser owns headless audio |+| Native bar state and amplitude | Existing bus and level channels | Existing companion bridge | Existing overlay; no native window on headless hosts |+| Unsupported media capability | Existing browser capability check | Same check | Same check |++The `media_levels` control is a frozen, validated, transient snapshot: normalized+input/output levels and input/playback activity. It carries no PCM or text and+is never written to SQL, usage records, or the event journal. The existing+`AudioOutFirst` event is emitted after the speaking state on an actual playback+edge; generated text and backend completion do not prove audible playback.+Microphone activity outranks background thinking; audible output takes priority.+Close and a 1.5-second measurement expiry clear stale meters. Legacy clients+retain the existing `playback_state` edge contract.++`tests/contract/test_live_media_feedback.py` covers both Live session families,+the real native bridge with a recording surface, invalid snapshots, cleanup,+and Python/TypeScript field parity without opening a device. Browser tests+cover level forwarding, word-gap hysteresis and stale thinking messages.+Physical macOS/Linux device verification remains pending; portable contracts+and headless tests must not be reported as physical-device acceptance.++## Agent profile companions (T3)++| Capability | Windows | macOS | Linux / headless |+| --- | --- | --- | --- |+| Companion settings in existing avatar JSON | Portable Pydantic + SQLite | Same implementation | Same; no GPU or credentials required |+| Character and companion editor | Shared React UI | Same browser UI | Same browser UI |+| In-map follower | Existing WebGL capability probe | Same capability probe | Available in a WebGL browser; headless API still works |+| No WebGL / lost context | Profile stays SVG/PNG; existing context recovery | Same fallback | Same fallback |++`avatar.companion` stores shape, colour, eye style and visibility independently+of the preserved character recipe. Companions use a fixed 0.50 m size and 1 m+following distance; earlier saved slider values normalize to these constants. No additional SQL+column, provider setting, inference request or credential is required. Old avatars+retain deterministic identity defaults. Per-agent settings survive reload and+world changes; hidden followers still retain their profile identity.++`tests/contract/test_agent_companion.py` exercises a fresh, credential-free,+headless API/database through creation, edit, rejection and reopening. A shared+JSON corpus is accepted/rejected by Python and TypeScript. Browser verification+on Windows covers real creation, appearance editing and rendering; physical+macOS/Linux verification is not inferred from this portable implementation.+Follower tests cover route corners, following gaps, height changes, bounded+history and background-tab catch-up. Existing WebGL lifecycle hooks own context+release/recovery; each follower shares the map canvas and cached geometry.+++## Wake-to-browser startup audio (T3)++| Capability | Windows | macOS | Linux / headless |+| --- | --- | --- | --- |+| Wake microphone handoff | Existing capture lease, kept until browser capture | Same portable lease | Same; no native lease in headless mode |+| Retained first sentence | Web Audio worklet feeds the negotiated RTP track | Same browser capability probe | Same browser path, including remote clients |+| Gemini/local input | Prefix precedes existing PCM stream | Same adapter | Same adapter |+| Missing Web Audio capability | Existing explicit unsupported-browser result | Same result | Same result |++The one-use `input_prefix` message carries bounded mono PCM16 and its sample+rate. Python validates its typed envelope; TypeScript decodes and resamples it+before browser input. The desktop cuts the prefix at `capture_started_at_ms`,+a wall-clock estimate of browser capture start, to exclude overlapping audio.+Capture clocks are not sample-synchronized: device/graph latency can affect+this boundary and requires physical-device acceptance. The source is released+on its owning event loop. Audio is memory-only; no SQL, transcript or journal+field is added. Closing or cancelling clears the offered lease, and no prefix+or captured audio is retained through reconnection.++GPT-Live input stays on RTP. The startup worklet emits silence until+`session.started`, then drains retained speech once. Only excess near-digital+silence is skipped to catch up; quiet speech is preserved. The native meter+continues receiving wake levels during connection and browser levels before+the RTP handshake completes. No billed idle session or extra provider call is+introduced.++`test_live_startup_audio.py`, `test_live_media_feedback.py`, capture-first+pipeline tests and the browser audio tests cover overlap trimming, once-only+consumption, cross-thread release, cancellation, PCM ordering and RTP startup.+Windows Chrome verification supplied a synthetic sentence entirely before+readiness with an extra three-second handshake delay: its complete transcript+arrived and assistant playback followed. This does not establish physical+wake/microphone acceptance or physical macOS/Linux acceptance.++A fresh Linux wheel installation passed all eight startup handoff contracts and+a one-key synthetic Live speech/tool proof (one tool receipt, spoken result, no+session failure). This checks the installed package without native audio devices.+++## Continuous voice conversation history (T3)++| Surface | Windows | macOS | Linux / headless |+| --- | --- | --- | --- |+| Speaker segments | Portable Live adapter projection | Same implementation | Same; no audio device required by projection |+| Live conversation and trace | Shared React voice stage and existing theme tokens | Same browser surface | Same surface in a remote browser |+| Persisted history | Existing session event JSON in SQLite | Same schema | Same schema |+| Legacy Live conversations | Read-only projection of existing transcript fragments | Same projection | Same projection |++`VoiceTranscriptUpdated` is a frozen, revisioned snapshot identified by session+and segment. Python, recorded JSON, API serialization and the TypeScript field+contract are exercised together by `test_live_conversation.py`. Independent+speaker rows allow overlapping audio and repeated phrases without overwriting+previous turns. Presentation grouping does not send model turn-control events.+Gemini/local snapshots and final markers use the same projection; older voice+adapters keep their existing final-transcript path.++Responses delegation publishes its real model-start event and exposes only+provider-supplied public reasoning summaries as `ReasoningSummaryUpdated`.+Raw/private reasoning and encrypted reasoning payloads are never projected.+The existing tool-execution events continue to supply tool progress/results.+Models that emit no summary still show their observable model/tool steps.+Configured reasoning backends request the provider's automatic summary format;+the selected model and credential stay unchanged.++The session recorder stores both event types in its existing event table. The+conversation API reconstructs the latest snapshot of each segment, with traces+attached to the corresponding answer interval. Pre-fix Live fragment history+is read without changing the original database. Physical OS audio acceptance+is separate from this portable presentation/storage contract.++Browser-owned calls also hold the native activation gate. A competing wake or+card start must not publish a replacement session and erase the active+conversation. This ownership is released with the Live runtime lease.++Validation includes a real GPT-Live browser session with synthetic speech and+a read-only test tool: three user segments, four assistant segments and two+stored trace intervals survived retrieval after restart. Both light and dark+voice-stage rendering were inspected. The fresh Linux backend installation+passed all seven conversation contracts; physical macOS/Linux audio behavior+is not inferred from these checks.+++## Startup audio catch-up (T2)++The existing WebRTC input worklet now repays startup audio delay with bounded+waveform-aligned overlap-add processing. It no longer depends on digitally+silent microphone samples, which left the previous queue permanently behind+in rooms with background noise. Quiet input is retained without an amplitude+speech gate. After catch-up, microphone samples pass through unchanged.+The native prefix shares the existing memory bound; reconnection clears both+queued audio and a partly rendered overlap grain. Assistant playback is not+processed by this input queue.++This changes the shared Web Audio implementation on Windows, macOS and Linux;+Gemini/local PCM adapters and headless boot are unchanged. No provider session,+credential setting or always-on billed connection is added. Tests cover 16,+24, 44.1 and 48 kHz, low amplitudes, waveform gain/pitch, noise/hum, prefix+ordering and cancellation. An actual Chrome AudioWorklet comparison with the+same two-second setup delay and background noise removed the old two-second+steady input lag. Paired GPT-Live probes retained the same recognized words in+German and English, including a quieter English sample. First response text+arrived 0.4–1.4 seconds earlier in those three comparisons; these small+synthetic comparisons are not a physical-device latency guarantee.diff --git a/docs/routines.md b/docs/routines.mdindex 7bab5943df..3412893a4b 100644--- a/docs/routines.md+++ b/docs/routines.md@@ -5,6 +5,19 @@ to an agent, appears in its Routines rail and in Automations, and executesthrough that agent's canonical chat with its current instructions and permissions.Creating a routine never grants additional plugin permissions.+## Model seat++A routine is pinned to a model seat at creation: by default the seat its owner+runs on at that moment (provider, model, effort, subscription account). The run+stays on that seat — it is never silently rerouted onto another provider chain+(such as an API-key chain) when the seat has trouble. A failed seat fails the+run honestly with a readable error instead of billing a different credential.++The seat is part of the routine and can be changed afterwards: the routine+editor has a Model section (provider, model, effort, account) with a "follow+the agent" choice that clears the pin so the routine tracks the owner's live+seat again. Title, prompt or schedule edits keep the pinned seat untouched.+## Configuring routines by chatExamples of supported requests:diff --git a/jarvis/agent_chat/cli_catalog.py b/jarvis/agent_chat/cli_catalog.pynew file mode 100644index 0000000000..fcf783a25c--- /dev/null+++ b/jarvis/agent_chat/cli_catalog.py@@ -0,0 +1,210 @@+"""Bounded CLI model discovery, scoped to the executable and login that run it."""++from __future__ import annotations++import asyncio+import copy+import hashlib+import json+import logging+import threading+import time+from collections.abc import Callable, Mapping+from datetime import UTC, datetime+from pathlib import Path+from typing import Any++from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS++log = logging.getLogger(__name__)+Rows = list[dict[str, Any]]+++def catalog_key(argv: list[str], env: Mapping[str, str], cwd: Path) -> str:+ """Fingerprint settings without storing credentials in the cache or logs.++ Include file metadata: replacing a login or updating the CLI in place must+ invalidate discovery even when its path and environment did not change.+ """+ homes = [+ Path.home() / name+ for name in (".codex", ".gemini", ".config/opencode", ".local/share/opencode")+ ]+ homes += [+ Path(value)+ for key, value in env.items()+ if value and key.endswith(("_HOME", "_CONFIG_DIR", "_DATA_HOME"))+ ]+ paths = [Path(part) for part in argv if Path(part).is_file()]+ paths += [path.parent.parent / "package.json" for path in paths]+ paths += [Path(env[key]) for key in ("OPENCODE_CONFIG",) if env.get(key)]+ for home in homes:+ paths.extend(+ home / name+ for name in (+ "auth.json",+ "oauth_creds.json",+ "opencode/auth.json",+ "opencode/opencode.json",+ "opencode/opencode.jsonc",+ "config.toml",+ "settings.json",+ "opencode.json",+ "opencode.jsonc",+ )+ )+ paths += [cwd / name for name in ("opencode.json", "opencode.jsonc", ".codex/config.toml")]+ stamps: list[tuple[str, int | None, int | None]] = []+ for path in paths:+ try:+ stat = path.stat()+ stamps.append((str(path), stat.st_mtime_ns, stat.st_size))+ except OSError:+ stamps.append((str(path), None, None))+ payload = json.dumps([argv, sorted(env.items()), str(cwd), stamps], sort_keys=True)+ return hashlib.sha256(payload.encode()).hexdigest()+++class CatalogCache:+ """Small single-flight cache; unknown models refresh, failed probes back off."""++ def __init__(self) -> None:+ self._lock = threading.Lock()+ self._entries: dict[str, tuple[float, Rows | None]] = {}++ def read(+ self, key: str, load: Callable[[], Rows | None], *, required_model: str = ""+ ) -> Rows | None:+ with self._lock:+ now = time.monotonic()+ entry = self._entries.get(key)+ if entry is not None:+ at, rows = entry+ ttl = 300.0 if rows is not None else 10.0+ missing = bool(required_model) and not any(+ row["id"] == required_model for row in rows or []+ )+ # A missing model gets a new discovery after a short cooldown,+ # including when it appears before the ordinary cache expires.+ if now - at < ttl and (not missing or now - at < 10.0):+ return copy.deepcopy(rows)+ rows = load()+ if key not in self._entries and len(self._entries) >= 32:+ self._entries.pop(next(iter(self._entries)))+ self._entries[key] = (time.monotonic(), copy.deepcopy(rows))+ return rows+++async def _codex_models(argv: list[str], env: dict[str, str], cwd: Path) -> Rows:+ proc = await asyncio.create_subprocess_exec(+ *argv,+ "app-server",+ env=env,+ cwd=str(cwd),+ stdin=asyncio.subprocess.PIPE,+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.DEVNULL,+ limit=4 * 1024 * 1024,+ creationflags=NO_WINDOW_CREATIONFLAGS,+ )+ assert proc.stdin is not None and proc.stdout is not None++ async def send(payload: dict[str, Any]) -> None:+ assert proc.stdin is not None+ proc.stdin.write((json.dumps(payload) + "\n").encode("utf-8"))+ await proc.stdin.drain()++ async def call(request_id: int, method: str, params: dict[str, Any]) -> dict[str, Any]:+ await send({"id": request_id, "method": method, "params": params})+ assert proc.stdout is not None+ while True:+ line = await proc.stdout.readline()+ if not line:+ raise ValueError("Codex model discovery ended before replying")+ reply = json.loads(line)+ if not isinstance(reply, dict) or reply.get("id") != request_id:+ continue+ result = reply.get("result")+ if not isinstance(result, dict):+ # Provider error bodies may contain private data.+ raise ValueError("Codex model discovery rejected the request")+ return result++ try:+ await call(1, "initialize", {"clientInfo": {"name": "jarvis", "version": "1.0.0"}})+ await send({"method": "initialized"})+ rows: Rows = []+ cursor: str | None = None+ seen: set[str] = set()+ for page in range(100):+ result = await call(+ page + 2, "model/list", {"limit": 100, "includeHidden": False, "cursor": cursor}+ )+ models = result.get("data")+ if not isinstance(models, list):+ raise ValueError("Codex returned an invalid model catalog")+ rows.extend(parse_codex_models(models))+ cursor = result.get("nextCursor")+ if cursor is None:+ return rows+ if not isinstance(cursor, str) or cursor in seen:+ raise ValueError("Codex returned an invalid model cursor")+ seen.add(cursor)+ raise ValueError("Codex model catalog exceeded the page limit")+ finally:+ if proc.returncode is None:+ try:+ proc.kill()+ except ProcessLookupError:+ pass # The child exited between returncode and kill.+ await proc.wait()+++def parse_codex_models(models: list[Any]) -> Rows:+ """Translate the CLI's model/list response without a hard-coded model ladder."""+ rows: Rows = []+ for model in models:+ if not isinstance(model, dict) or model.get("hidden") is True:+ continue+ slug = model.get("model") or model.get("id")+ if not isinstance(slug, str) or not slug.strip():+ continue+ note = ""+ upgrade = model.get("upgradeInfo")+ retired = upgrade.get("retirementAt") if isinstance(upgrade, dict) else None+ if isinstance(retired, (float, int)):+ if retired <= time.time():+ continue+ note = f"retires {datetime.fromtimestamp(retired, UTC).date()}"+ levels = model.get("supportedReasoningEfforts")+ if not isinstance(levels, list):+ raise ValueError("Codex model has no reasoning metadata")+ efforts = [+ entry["reasoningEffort"]+ for entry in levels+ if isinstance(entry, dict) and isinstance(entry.get("reasoningEffort"), str)+ ]+ rows.append(+ {+ "id": slug,+ "label": model.get("displayName") or slug,+ "efforts": efforts,+ "note": note,+ }+ )+ return rows+++def discover_codex_models(+ argv: list[str], env: dict[str, str], cwd: Path, timeout_s: float = 8.0+) -> Rows | None:+ """Run off the event loop. Discovery never starts a model turn or runs tools."""++ async def bounded() -> Rows:+ return await asyncio.wait_for(_codex_models(argv, env, cwd), timeout_s)++ try:+ return asyncio.run(bounded())+ except (OSError, ValueError, TimeoutError) as exc:+ log.debug("Codex model discovery unavailable (%s)", type(exc).__name__)+ return Nonediff --git a/jarvis/agent_chat/control.py b/jarvis/agent_chat/control.pyindex 3f68cbd94f..4eba58585f 100644--- a/jarvis/agent_chat/control.py+++ b/jarvis/agent_chat/control.py@@ -366,7 +366,9 @@ class ChatControls:executor = getattr(brain, "_tool_executor", None)if runtime is None or executor is None:raise ValueError("Agent tools are still starting")- agent_id = sid.removeprefix("society:") if session.surface == "society" else "jarvis"+ from jarvis.society.surface import agent_id_of++ agent_id = (agent_id_of(sid) or "") if session.surface == "society" else "jarvis"tool: Anyif command == "message":match = re.fullmatch(r'@(?P<target>"[^"]+"|\S+)\s+(?P<text>[\s\S]+)', arguments)diff --git a/jarvis/agent_chat/runner_brain.py b/jarvis/agent_chat/runner_brain.pyindex fb4b7d1f7b..dc82490546 100644--- a/jarvis/agent_chat/runner_brain.py+++ b/jarvis/agent_chat/runner_brain.py@@ -531,6 +531,11 @@ async def run_brain_turn(await emit("assistant_text", {"turn_id": turn_id, "message_id": message_id, "text": answer})+ # Keep the safe explanation visible, but distinguish provider success+ # from an answer rejected by the execution/evidence backstop.+ if override.receipt.guard_failure:+ status = "error"+ error = override.receipt.failure_reason or "guarded_response"await finish(status, override.receipt.usage(), error)diff --git a/jarvis/agent_chat/runner_cli.py b/jarvis/agent_chat/runner_cli.pyindex 3ab93253fa..7e15a0016d 100644--- a/jarvis/agent_chat/runner_cli.py+++ b/jarvis/agent_chat/runner_cli.py@@ -63,6 +63,7 @@ import shutilimport timeimport uuidfrom collections.abc import Callable+from contextlib import contextmanagerfrom contextvars import ContextVarfrom dataclasses import dataclass, fieldfrom pathlib import Path@@ -70,6 +71,7 @@ from typing import Any, Finalfrom jarvis.agent_chat import jarvis_harnessfrom jarvis.agent_chat.approval_bridge import approval_ref+from jarvis.agent_chat.cli_catalog import CatalogCache, catalog_key, discover_codex_modelsfrom jarvis.agent_chat.effort import ORDER, normalize_effort, snap_to_ladderfrom jarvis.agent_chat.events import make_eventfrom jarvis.agent_chat.permissions import normalize_permission@@ -227,21 +229,79 @@ def cursor_argv_prefix() -> list[str]:ACCOUNT_OVERRIDE: ContextVar[str] = ContextVar("agent_chat.account_override", default="")+_CATALOG_IGNORE_CONFIG: ContextVar[bool] = ContextVar("cli_catalog.ignore_config", default=False)+_CATALOG_CWD: ContextVar[Path | None] = ContextVar("cli_catalog.cwd", default=None)+_ACCOUNT_ENVS: ContextVar[dict[str, dict[str, str]] | None] = ContextVar(+ "cli_catalog.envs", default=None+)+_PREPARED_MODELS: ContextVar[dict[str, list[dict[str, Any]] | None] | None] = ContextVar(+ "cli_catalog.models", default=None+)+++@contextmanager+def cli_catalog_scope(+ *, account_id: str | None = None, cwd: Path | None = None, ignore_user_config: bool = False+):+ """One request/turn uses one account environment for discovery and spawning."""+ account_token = ACCOUNT_OVERRIDE.set(account_id) if account_id is not None else None+ config_token = _CATALOG_IGNORE_CONFIG.set(ignore_user_config)+ cwd_token = _CATALOG_CWD.set(cwd)+ env_token = _ACCOUNT_ENVS.set({})+ model_token = _PREPARED_MODELS.set({})+ try:+ yield+ finally:+ _PREPARED_MODELS.reset(model_token)+ _ACCOUNT_ENVS.reset(env_token)+ _CATALOG_CWD.reset(cwd_token)+ _CATALOG_IGNORE_CONFIG.reset(config_token)+ if account_token is not None:+ ACCOUNT_OVERRIDE.reset(account_token)+++def _catalog_cwd() -> Path:+ return _CATALOG_CWD.get() or Path.home()+++def _remember_models(runner: str, rows: list[dict[str, Any]] | None) -> None:+ prepared = _PREPARED_MODELS.get()+ if prepared is not None:+ prepared[runner] = rows++def _account_env(platform: str) -> dict[str, str]:"""The child environment for the subscription seat of ``platform`` — theturn's pinned account when its session names one, else the active one."""+ snapshot = _ACCOUNT_ENVS.get()+ if snapshot is not None and platform in snapshot:+ return dict(snapshot[platform])+ pinned_platform: str | None = Nonetry:from jarvis import agent_accounts- pinned = agent_accounts.resolve(ACCOUNT_OVERRIDE.get() or None)+ requested = ACCOUNT_OVERRIDE.get()+ pinned = agent_accounts.resolve(requested or None)+ if requested and pinned is None:+ raise CliUnavailable(+ "The selected subscription account no longer exists. Choose an account and retry."+ )+ pinned_platform = pinned.platform if pinned is not None else Noneif pinned is not None and pinned.platform == platform:account = pinnedelse:account = agent_accounts.active_account(platform) # type: ignore[arg-type]env = agent_accounts.spawn_env(platform, account.id, base=os.environ) # type: ignore[arg-type]- except Exception: # noqa: BLE001 — no account layer for this platform → plain env+ except CliUnavailable:+ raise+ except Exception as exc: # noqa: BLE001 — unsupported platforms use native credentials+ if ACCOUNT_OVERRIDE.get() and pinned_platform in (None, platform):+ raise CliUnavailable("The selected subscription account could not be loaded.") from exc+ log.debug("CLI account layer unavailable for %s (%s)", platform, type(exc).__name__)env = dict(os.environ)env.setdefault("PYTHONIOENCODING", "utf-8")+ if snapshot is not None:+ snapshot[platform] = dict(env)return env@@ -696,62 +756,23 @@ def plan_agy(return CliPlan(argv, env, prompt, "agy", resume)-def read_codex_models() -> list[dict[str, Any]] | None:- """Codex's account catalog from ``$CODEX_HOME/models_cache.json``.+_CODEX_CATALOG = CatalogCache()- The CLI refreshes that file itself (TTL 5 min, ETag) on every run; it is- the same list the Codex TUI's model picker shows for this login. Rows:- ``{id, label, efforts, note}`` for ``visibility: list`` models, ordered- by the catalog's ``priority``. ``None`` when the file is missing or- unreadable (the caller falls back to the bundled list).- """++def read_codex_models(*, required_model: str = "") -> list[dict[str, Any]] | None:+ """Ask the installed CLI, never trust another client's models_cache.json."""env = _account_env("codex")- home = Path(env.get("CODEX_HOME") or Path.home() / ".codex")- path = home / "models_cache.json"- try:- data = json.loads(path.read_text(encoding="utf-8"))- except (OSError, ValueError) as exc:- log.debug("agent chat: codex models cache unreadable at %s: %s", path, exc)- return None- models = data.get("models") if isinstance(data, dict) else None- if not isinstance(models, list):- return None- rows: list[tuple[int, dict[str, Any]]] = []- for m in models:- if not isinstance(m, dict):- continue- if str(m.get("visibility") or "list") != "list":- continue- slug = str(m.get("slug") or m.get("id") or "").strip()- if not slug:- continue- levels = m.get("supported_reasoning_levels") or []- efforts = [- str(lvl.get("effort") if isinstance(lvl, dict) else lvl)- for lvl in levels- if (lvl.get("effort") if isinstance(lvl, dict) else lvl)- ]- note = ""- upgrade = m.get("upgrade")- if isinstance(upgrade, dict) and upgrade.get("retirement_at"):- note = f"retires {str(upgrade['retirement_at'])[:10]}"- try:- prio = int(m.get("priority") or 0)- except (TypeError, ValueError):- prio = 0- rows.append(- (- prio,- {- "id": slug,- "label": str(m.get("display_name") or slug),- "efforts": efforts,- "note": note,- },- )- )- rows.sort(key=lambda r: r[0])- return [r[1] for r in rows] or None+ argv = codex_argv_prefix()+ if _CATALOG_IGNORE_CONFIG.get():+ argv = [*argv, "--ignore-user-config", "--ignore-rules"]+ cwd = _catalog_cwd()+ rows = _CODEX_CATALOG.read(+ catalog_key(argv, env, cwd),+ lambda: discover_codex_models(argv, env, cwd),+ required_model=required_model,+ )+ _remember_models("codex-cli", rows)+ return rowsdef read_grok_models() -> list[dict[str, Any]] | None:@@ -819,11 +840,15 @@ _AGY_CATALOG_TTL_S: Final[float] = 600.0def _agy_catalog_cached() -> list[dict[str, Any]] | None:- rows = _AGY_CATALOG.get("rows")+ prepared = _PREPARED_MODELS.get()+ if prepared is not None and "agy-cli" in prepared:+ return prepared["agy-cli"]+ key = catalog_key(agy_argv_prefix(), _account_env("antigravity"), _catalog_cwd())+ rows = _AGY_CATALOG.get("rows") if _AGY_CATALOG.get("key") == key else Nonereturn rows if isinstance(rows, list) else None-def read_agy_models(timeout_s: float = 8.0) -> list[dict[str, Any]]:+def read_agy_models(timeout_s: float = 8.0, *, required_model: str = "") -> list[dict[str, Any]]:"""``agy --output-format json models`` -> the folded catalog (cached 10 min).Blocking (a ~2 s subprocess) — call it off the event loop. Any failure@@ -832,19 +857,26 @@ def read_agy_models(timeout_s: float = 8.0) -> list[dict[str, Any]]:"""import subprocess+ env = _account_env("antigravity")+ argv = agy_argv_prefix()+ cwd = _catalog_cwd()+ key = catalog_key(argv, env, cwd)now = time.monotonic()- if _AGY_CATALOG["rows"] is not None and now - _AGY_CATALOG["at"] < _AGY_CATALOG_TTL_S:- return list(_AGY_CATALOG["rows"])+ cached = _agy_catalog_cached()+ model_known = not required_model or any(row["id"] == required_model for row in cached or [])+ if cached is not None and model_known and now - _AGY_CATALOG["at"] < _AGY_CATALOG_TTL_S:+ _remember_models("agy-cli", cached)+ return list(cached)raw: list[dict[str, Any]] | None = Nonetry:- argv = [*agy_argv_prefix(), "--output-format", "json", "models"]- env = dict(os.environ)+ argv = [*argv, "--output-format", "json", "models"]env.setdefault("AGY_CLI_HIDE_LOGO", "1")proc = subprocess.run( # noqa: S603 — fixed argv, no shellargv,capture_output=True,timeout=timeout_s,env=env,+ cwd=str(cwd),creationflags=NO_WINDOW_CREATIONFLAGS,)text = proc.stdout.decode("utf-8", errors="replace")@@ -861,8 +893,8 @@ def read_agy_models(timeout_s: float = 8.0) -> list[dict[str, Any]]:except (CliUnavailable, OSError, ValueError, subprocess.SubprocessError) as exc:log.debug("agent chat: agy models unavailable: %s", exc)rows = agy_model_catalog(raw)- _AGY_CATALOG["rows"] = rows- _AGY_CATALOG["at"] = now+ _AGY_CATALOG.update(rows=rows, at=now, key=key)+ _remember_models("agy-cli", rows)return list(rows)@@ -923,8 +955,14 @@ def plan_codex(# The account's catalog says which levels THIS model takes (5.5 stops# at xhigh, terra goes to ultra); an unsupported level is snapped# rather than sent for the server to reject.- for row in read_codex_models() or []:- if row.get("id") == model and row.get("efforts"):+ prepared = _PREPARED_MODELS.get()+ models = (+ prepared.get("codex-cli")+ if prepared is not None and "codex-cli" in prepared+ else read_codex_models()+ )+ for row in models or []:+ if row.get("id") == model and "efforts" in row:effort = snap_to_ladder(effort, list(row["efforts"]))breakif effort:@@ -955,21 +993,26 @@ def read_opencode_models(timeout_s: float = 20.0) -> list[dict[str, Any]]:"""import subprocess+ env = _registry_env("opencode", _account_env("opencode"))+ prefix = opencode_argv_prefix()+ cwd = _catalog_cwd()+ key = catalog_key(prefix, env, cwd)now = time.monotonic()if (- _OPENCODE_CATALOG["rows"] is not None+ _OPENCODE_CATALOG.get("key") == key+ and _OPENCODE_CATALOG["rows"] is not Noneand now - _OPENCODE_CATALOG["at"] < _OPENCODE_CATALOG_TTL_S):return list(_OPENCODE_CATALOG["rows"])rows: list[dict[str, Any]] = []try:- argv = [*opencode_argv_prefix(), "models"]- env = _registry_env("opencode", dict(os.environ))+ argv = [*prefix, "models"]proc = subprocess.run( # noqa: S603 — fixed argv, no shellargv,capture_output=True,timeout=timeout_s,env=env,+ cwd=str(cwd),creationflags=NO_WINDOW_CREATIONFLAGS,)for line in proc.stdout.decode("utf-8", errors="replace").splitlines():@@ -980,8 +1023,7 @@ def read_opencode_models(timeout_s: float = 20.0) -> list[dict[str, Any]]:rows.append({"id": mid, "label": model, "note": provider})except (CliUnavailable, OSError, ValueError, subprocess.SubprocessError) as exc:log.debug("agent chat: opencode models unavailable: %s", exc)- _OPENCODE_CATALOG["rows"] = rows- _OPENCODE_CATALOG["at"] = now+ _OPENCODE_CATALOG.update(rows=rows, at=now, key=key)return list(rows)@@ -2687,46 +2729,65 @@ async def _run_cli_once(vendor_session: str | None = Nonetry:- if runner == "agy-cli":- # A chat can start before the model picker has loaded its catalog.- # Resolve the installed CLI's effort ladder off the event loop so- # newly available models keep the required model/effort pairing.- await asyncio.to_thread(read_agy_models)- plan: CliPlan = planner(- prompt=user_text,+ with cli_catalog_scope(cwd=cwd,- model=session.model,- effort=effort,- permission_mode=session.permission_mode,- resume=resume,- identity=identity,- )- if getattr(handle, "tools_disabled", False):- from .native_control import disable_cli_tools-- disable_cli_tools(plan, runner)- if getattr(handle, "gateway_only", False):- if runner == "claude-cli":- plan.argv += ["--tools", "", "--strict-mcp-config"]- elif runner == "codex-cli":- plan.argv += ["--ignore-user-config", "--ignore-rules"]- for feature in (- "shell_tool",- "apps",- "hooks",- "multi_agent",- "browser_use",- "web_search_request",- "goals",- "memories",- "plugins",- "computer_use",- "image_generation",- "multi_agent_v2",+ ignore_user_config=identity is not None or bool(getattr(handle, "gateway_only", False)),+ ):+ if runner == "codex-cli":+ models = await asyncio.to_thread(read_codex_models, required_model=session.model)+ if session.model and (+ models is None or not any(row["id"] == session.model for row in models)):- plan.argv += ["--disable", feature]- else:- raise CliUnavailable("The selected runner cannot isolate task tools.")+ raise CliUnavailable(+ "The selected model could not be confirmed for this Codex "+ "installation and account. "+ "Refresh the model list, check the selected account, or update Codex "+ "in the CLIs page, then retry."+ )+ for row in models or []:+ if row["id"] == session.model:+ effort = snap_to_ladder(session.effort, list(row.get("efforts", [])))+ break+ if runner == "agy-cli":+ # A chat can start before the model picker has loaded its catalog.+ # Resolve the installed CLI's effort ladder off the event loop so+ # newly available models keep the required model/effort pairing.+ await asyncio.to_thread(read_agy_models, required_model=session.model)+ plan: CliPlan = planner(+ prompt=user_text,+ cwd=cwd,+ model=session.model,+ effort=effort,+ permission_mode=session.permission_mode,+ resume=resume,+ identity=identity,+ )+ if getattr(handle, "tools_disabled", False):+ from .native_control import disable_cli_tools++ disable_cli_tools(plan, runner)+ if getattr(handle, "gateway_only", False):+ if runner == "claude-cli":+ plan.argv += ["--tools", "", "--strict-mcp-config"]+ elif runner == "codex-cli":+ plan.argv += ["--ignore-user-config", "--ignore-rules"]+ for feature in (+ "shell_tool",+ "apps",+ "hooks",+ "multi_agent",+ "browser_use",+ "web_search_request",+ "goals",+ "memories",+ "plugins",+ "computer_use",+ "image_generation",+ "multi_agent_v2",+ ):+ plan.argv += ["--disable", feature]+ else:+ raise CliUnavailable("The selected runner cannot isolate task tools.")except CliUnavailable as exc:return _Outcome("error", str(exc), {}, None, None)diff --git a/jarvis/agent_chat/service.py b/jarvis/agent_chat/service.pyindex c55fb02d45..d314f310bd 100644--- a/jarvis/agent_chat/service.py+++ b/jarvis/agent_chat/service.py@@ -106,6 +106,49 @@ def resolve_runner(provider: str, *, surface: str = "agent") -> str:_CLI_SEATS_RETIRED: Final[int] = 1+def stop_cli_at_cwd(cwd: str) -> int:+ """Stop a leftover chat CLI whose working folder is exactly ``cwd``.++ Used when the stop button finds no in-memory turn. The match is one+ command-line argument, not a substring of the prompt, so a mention of+ the folder inside the task text does not count.+ """+ root = Path(cwd).expanduser()+ try:+ root = root.resolve()+ except OSError:+ return 0+ if not root.is_dir():+ return 0+ needles = {str(root).rstrip("\\/"), str(root).replace("\\", "/").rstrip("/")}+ if all(len(item) < 16 for item in needles):+ return 0+ try:+ import psutil+ except ImportError:+ log.warning("agent chat: cannot stop a leftover CLI without psutil")+ return 0+ import os++ me = {os.getpid(), os.getppid()}+ stopped = 0+ for proc in psutil.process_iter(["pid", "cmdline"]):+ pid = proc.info.get("pid")+ if pid in me:+ continue+ parts = [str(part).rstrip("\\/") for part in (proc.info.get("cmdline") or [])]+ if not any(needle in parts for needle in needles):+ continue+ try:+ for child in proc.children(recursive=True):+ child.terminate()+ proc.terminate()+ stopped += 1+ except Exception:+ log.warning("agent chat: could not stop leftover CLI %s", pid, exc_info=True)+ return stopped++class _Running:__slots__ = ("task", "cancel", "turn_id")@@ -269,6 +312,52 @@ class AgentChatService:run = self._running.get(session_id)return bool(run and run.task and not run.task.done())+ async def seal_stopped_turn(self, session_id: str) -> bool:+ """Close a turn the stop button can still see after its runner is gone.++ A restart keeps the transcript and drops the in-memory task. The CLI+ can still be working. Stop has to end that turn, or the button does+ nothing and the chat stays on Working.+ """+ if self.is_running(session_id):+ return False+ events = self.store.list_events(session_id)+ turn_id = ""+ started_ms = 0+ for event in reversed(events):+ kind = event["kind"]+ payload = event.get("payload") or {}+ if kind == "turn_finished":+ return False+ if kind == "turn_started":+ turn_id = str(payload.get("turn_id") or "")+ started_ms = int(event.get("ts_ms") or 0)+ break+ if not turn_id:+ return False+ now_ms = int(time.time() * 1000)+ await self._emit(+ session_id,+ make_event(+ "turn_finished",+ {+ "turn_id": turn_id,+ "status": "cancelled",+ "duration_ms": max(0, now_ms - started_ms) if started_ms else 0,+ "usage": {},+ "error": None,+ },+ ),+ )+ session = self.store.get_session(session_id)+ if session is not None and session.cwd:+ await asyncio.to_thread(stop_cli_at_cwd, session.cwd)+ if session is not None and session.surface in ("jarvis", "society"):+ from jarvis.society.browser.tool import stop_chat_browser++ await stop_chat_browser(session_id)+ return True+def pending_approvals(self, session_id: str) -> list[str]:return [aid for aid, sid in self._approval_session.items() if sid == session_id]@@ -794,11 +883,14 @@ class AgentChatService:)return turn_id- def signal_cancel(self, session_id: str) -> bool:+ def signal_cancel(self, session_id: str, *, expected_turn_id: str | None = None) -> bool:"""Stop planning synchronously before releasing an in-flight tool reply."""run = self._running.get(session_id)if run is None or run.task is None or run.task.done():return False+ # A resumed station must never cancel a newer unrelated conversation turn.+ if expected_turn_id is not None and run.turn_id != expected_turn_id:+ return Falserun.cancel.set()for aid in self.pending_approvals(session_id):fut = self._approvals.get(aid)@@ -806,9 +898,9 @@ class AgentChatService:fut.set_result("cancel")return True- async def cancel(self, session_id: str) -> bool:+ async def cancel(self, session_id: str, *, expected_turn_id: str | None = None) -> bool:run = self._running.get(session_id)- if not self.signal_cancel(session_id):+ if not self.signal_cancel(session_id, expected_turn_id=expected_turn_id):return Falseassert run is not None and run.task is not Nonetry:diff --git a/jarvis/agent_chat/store.py b/jarvis/agent_chat/store.pyindex 0a60d72908..769df9eb63 100644--- a/jarvis/agent_chat/store.py+++ b/jarvis/agent_chat/store.py@@ -363,6 +363,22 @@ class AgentChatStore:receipt.update(payload)return receipt+ def turn_terminal(self, session_id: str, turn_id: str) -> dict[str, Any] | None:+ """Read one durable terminal event for an exact owned turn without loading history."""+ with self._lock:+ row = self._conn.execute(+ "SELECT seq, ts_ms, kind, payload FROM agent_chat_events "+ "WHERE session_id = ? AND kind = 'turn_finished' "+ "AND json_extract(payload, '$.turn_id') = ? ORDER BY seq DESC LIMIT 1",+ (session_id, turn_id),+ ).fetchone()+ if row is None:+ return None+ return {+ "seq": int(row["seq"]), "ts_ms": int(row["ts_ms"]), "kind": row["kind"],+ "payload": json.loads(row["payload"]),+ }+def list_events(self, session_id: str, *, after_seq: int = 0) -> list[dict[str, Any]]:with self._lock:rows = self._conn.execute(diff --git a/jarvis/agent_chat/tool_catalog.py b/jarvis/agent_chat/tool_catalog.pyindex 815a37609b..2790d27d05 100644--- a/jarvis/agent_chat/tool_catalog.py+++ b/jarvis/agent_chat/tool_catalog.py@@ -111,6 +111,25 @@ def build_catalog(servers.setdefault(server, []).append(name)category: Category = "mcp"group = server+ elif name == "create_artifact":+ # The explicit artifact pin for the Add menu: bilingual label so+ # DE "Artefakt" and EN "Artifact" both find it via prefix and+ # substring search, brand "artifact" for the shared Shapes mark.+ label = "Artifact / Artefakt"+ category = category_for(name)+ group = "Artifact"+ rows.append(+ ToolChoice(+ id=f"tool:{name}",+ label=label,+ description=str(tool.description),+ category=category,+ group=group,+ brand="artifact",+ tool_names=(name,),+ )+ )+ continueelse:label = namecategory = category_for(name)diff --git a/jarvis/audio/mic_level.py b/jarvis/audio/mic_level.pyindex f70264dcc4..f97acd6131 100644--- a/jarvis/audio/mic_level.py+++ b/jarvis/audio/mic_level.py@@ -105,6 +105,22 @@ class LevelNormalizer:_norm = LevelNormalizer()+_external_owner: str | None = None+++def claim_external(owner: str) -> None:+ """A browser session owns the meter while its measurements are fresh."""+ global _external_owner+ with _lock:+ _external_owner = owner+++def release_external(owner: str) -> None:+ """An older session cannot release a newer session's meter."""+ global _external_owner+ with _lock:+ if _external_owner == owner:+ _external_owner = Nonedef subscribe(sink: Callable[[float], None]) -> Callable[[], None]:@@ -131,8 +147,15 @@ def feed(rms: float) -> None:"""Normalize a raw per-frame RMS (float, [0,1] scale) and publish the 0..1level to all sinks. Swallows sink errors so a bad UI handler never breaksaudio capture."""- level = _norm.push(float(rms))+ publish(_norm.push(float(rms)))+++def publish(level: float, *, owner: str | None = None) -> None:+ """Publish an already normalized level from a browser-owned microphone."""+ level = max(0.0, min(1.0, float(level)))with _lock:+ if _external_owner != owner:+ returnsinks = tuple(_subscribers)for sink in sinks:try:@@ -158,6 +181,8 @@ def reset() -> None:def reset_for_tests() -> None:"""Test helper: drop all subscribers and reset the normalizer."""+ global _external_ownerwith _lock:_subscribers.clear()+ _external_owner = None_norm.reset()diff --git a/jarvis/brain/artifact_gate.py b/jarvis/brain/artifact_gate.pyindex 62cf28b27b..d6de535c33 100644--- a/jarvis/brain/artifact_gate.py+++ b/jarvis/brain/artifact_gate.py@@ -1,19 +1,24 @@"""Explicit-request gate for the ``create_artifact`` tool (ask-only, never ambient).-Building an artifact — a page, a dashboard, a diagram the user looks at — is-the one capability a user must be able to switch on with their own words. An+Building an artifact — a page the user looks at and keeps — is the one+capability a user must switch on with their own words, literally. Anassistant that decides on its own when an answer "would be clearer as a page"-produces a stream of artifacts nobody asked for, and every one of them costs a-background mission on the strongest model, a file in the archive, and a jump-of the UI to another section. So the tool is not merely *discouraged*+produces a stream of artifacts nobody asked for, and every one of them costs+a background mission on the strongest model, a file in the archive, and a+jump of the UI to another section. So the tool is not merely *discouraged*ambiently — it is withheld from the model's tool set on every turn that didnot ask for it (see ``BrainManager._hide_artifact_tool_without_request``),which also keeps its schema out of the request on the ~99% of turns that areabout something else.-Regex-only, provider-agnostic, no model in the detection path (AP-11): the gate-runs on every single turn, so an LLM here would tax exactly the turns this-module exists to keep cheap.+The second explicit path is the composer Add menu: pinning the artifact+capability there hands the tool to the turn through the override's extra+hands (applied AFTER this gate), so no word is needed in that case. This+module only judges the words.++Regex-only, provider-agnostic, no model in the detection path (AP-11): the+gate runs on every single turn, so an LLM here would tax exactly the turns+this module exists to keep cheap.Three rules, in order:@@ -23,14 +28,15 @@ Three rules, in order:would produce a brand-new page instead of showing the old ones.2. A **definition question** ("was ist ein Artefakt?") is answered withwords. The word appearing in a question about the word is not a request.-3. Otherwise: an explicit artifact VERB or NOUN on its own ("visualisier",- "Artefakt", "Dashboard"), or a build/show verb together with a visual NOUN- ("mach mir ein Diagramm", "show me that as a page"), is a request.+3. Otherwise: only the artifact said BY NAME ("Artefakt", "Artifact",+ "Artefacto") is a request. Visual verbs and page shapes on their own+ ("visualisier", "Dashboard", "Diagramm", "mach mir eine Seite dazu")+ are NOT requests — the user says the literal word or pins it via Add.A false negative is cheap and self-correcting — the user says "mach einArtefakt draus" and gets it on the next turn. A false positive is the whole-problem this module was written for, so every pattern here is deliberately-narrow.+problem this module was written for, so the pattern here is deliberately+a single noun.Every literal below is input-matching vocabulary in the user's spoken languages(DE/EN/ES), which the language policy allows on the input surface.@@ -50,13 +56,11 @@ _NAV_VERBS = (r"open|go\s+to|switch\s+to|navigate\s+to|show|"r"abre|ve\s+a|muestra(?:me)?" # i18n-allow: input vocab)-_NAV_ARTICLES = (- r"(?:mir\s+|me\s+)?(?:die|den|das|the|la|el|los|las)?" # i18n-allow: input vocab-)+_NAV_ARTICLES = r"(?:mir\s+|me\s+)?(?:die|den|das|the|la|el|los|las)?" # i18n-allow: input vocab_NAV_SECTION_NOUNS = (r"visualisierung(?:s\w*)?(?:en)?|" # i18n-allow: input vocabr"visualiz(?:ation|aciones|aci[oó]n)s?|visualisations?|visuals|"- r"artefakte?|artifacts?|artefactos?" # i18n-allow: input vocab+ r"artefakt\w*|artifact\w*|artefact\w*|artefactos?" # i18n-allow: input vocab)_NAV_SUFFIX = (r"(?:\s*[-–]?\s*"@@ -83,71 +87,27 @@ _DEFINITION_RE = re.compile(re.IGNORECASE,)-# --- 3a. Words strong enough on their own --------------------------------------# "visualisier mir das", "visualize this", "mach eine Mindmap draus", "ein-# Artefakt bitte", "als Dashboard". Each of these names the ACT of building a-# picture or the artifact itself; no second signal is needed. Stems are matched-# so every inflection is covered ("visualisiere", "visualizing", "visualízalo").+# --- 3. The artifact said by name — the only word that builds ---------------+# "mach ein Artefakt draus", "build me an artifact", "hazme un artefacto".+# Nothing else builds: "visualisier", "Dashboard", "Diagramm", "Seite",+# "Bericht" are ordinary conversation until the user says the literal word+# or pins the capability via the Add menu (which bypasses this gate through+# the turn override's extra hands, applied after it)._EXPLICIT_RE = re.compile(r"\b(?:"- # One stem for all three languages and every inflection, accents included:- # visualisieren, visualize, visualising, visualízamelo.- r"visual[ií]\w*|" # i18n-allow: input vocab- r"veranschaulich\w*|skizzier\w*|" # i18n-allow: input vocab- r"schaubild|flussdiagramm|ablaufdiagramm|organigramm|" # i18n-allow: input vocab- r"mindmap|mind\s+map|flowchart|flow\s+chart|org\s+chart|"- r"esquematiza\w*|diagrama\s+de\s+flujo|" # i18n-allow: input vocab- # The artifact by name, and the page shapes that ARE artifacts.- r"artefakte?s?|artifacts?|artefactos?|" # i18n-allow: input vocab- r"dashboards?|infografik\w*|infographics?|infograf[ií]as?|" # i18n-allow: input vocab- r"landing\s*pages?|one-?pagers?"- r")\b",- re.IGNORECASE,-)--# --- 3b. Build/show verb + visual noun — a request only in combination --------# "diagramm" or "chart" alone is ordinary conversation ("der Chart ist rot").-# Paired with a verb that PRODUCES or DISPLAYS something, it is a request.-_VERB_RE = re.compile(- r"\b(?:"- r"mach|mache|erstell\w*|bau\w*|zeichne|zeichnen|mal|male|" # i18n-allow: input vocab- r"stell\w*|gib\s+mir|zeig\w*|erkl[äa]r\w*|fass\w*|" # i18n-allow: input vocab- r"make|create|build|draw|sketch|render|turn\s+(?:it|this|that)\s+into|"- r"give\s+me|show|explain|summari[sz]e|map\s+out|"- # "chart"/"graph"/"plot" are nouns as often as verbs, and _NOUN_RE already- # matches them. Without an object they would let ONE word play both halves- # of the combination and fire on "wie ist der bitcoin chart gerade".- r"(?:plot|chart|graph|map)\s+(?:it|this|that|these|those|the)|"- r"haz(?:me)?|crea|dibuja|muestra(?:me)?|resume" # i18n-allow: input vocab- r")\b",- re.IGNORECASE,-)--_NOUN_RE = re.compile(- r"\b(?:"- r"diagramm\w*|grafik\w*|schaubild\w*|zeitstrahl|" # i18n-allow: input vocab- r"bildlich|grafisch|visuell|anschaulich|als\s+bild|" # i18n-allow: input vocab- r"diagram|chart|graphic|timeline|infographic|"- r"visually|graphically|as\s+(?:a\s+)?(?:picture|image|drawing)|"- r"diagrama|gr[áa]fic[oa]s?|l[íi]nea\s+de\s+tiempo|" # i18n-allow: input vocab- r"visualmente|gr[áa]ficamente|" # i18n-allow: input vocab- # Page shapes — a request only next to a build/show verb ("mach mir eine- # Seite dazu", "build me a report page"), never on their own: "die Seite- # war langsam" is conversation.- r"html(?:-?(?:seite|datei|page|file))?|webseite|websites?|web\s*pages?|" # i18n-allow- r"p[áa]ginas?(?:\s+web)?|als\s+seite|as\s+a\s+page|" # i18n-allow: input vocab- r"bericht(?:sseite)?|reports?|informes?|" # i18n-allow: input vocab- r"übersicht(?:sseite)?|uebersicht|overview\s+page" # i18n-allow: input vocab+ r"artefakt\w*|artifact\w*|artefact\w*|artefactos?" # i18n-allow: input vocabr")\b",re.IGNORECASE,)def wants_artifact(text: str) -> bool:- """True when the utterance explicitly asks for an artifact to be built.+ """True when the utterance literally names an artifact to be built.- The single decision point for offering the ``create_artifact`` tool at- all. See the module docstring for the three rules and why each is narrow.+ The single WORD decision point for offering the ``create_artifact`` tool+ at all. See the module docstring for the three rules. The Add-menu pin+ is the second path and bypasses this function through the turn+ override's extra hands."""t = (text or "").strip()if not t:@@ -156,9 +116,7 @@ def wants_artifact(text: str) -> bool:return Falseif _DEFINITION_RE.search(t):return False- if _EXPLICIT_RE.search(t):- return True- return bool(_VERB_RE.search(t) and _NOUN_RE.search(t))+ return bool(_EXPLICIT_RE.search(t))__all__ = ["wants_artifact"]diff --git a/jarvis/brain/cost.py b/jarvis/brain/cost.pyindex e751e93409..3e821c62c0 100644--- a/jarvis/brain/cost.py+++ b/jarvis/brain/cost.py@@ -111,6 +111,11 @@ PRICING_USD_PER_MTOK: dict[str, tuple[float, float]] = {"gemini-live-2.5-flash-native-audio": (0.50, 2.0),# ── OpenAI (Frontier: GPT-5.5 + 5.5-pro, released 2026-04-23) ──"gpt-5.5": (5.0, 30.0),+ # OpenAI standard short-context rates, verified 2026-09-23:+ # https://developers.openai.com/api/docs/pricing+ "gpt-5.6-terra": (2.0, 12.0),+ "gpt-5.6-sol": (4.0, 20.0),+ "gpt-5.6-luna": (0.20, 1.20),# Not a vendor model: Codex's review pass, which runs on the session's own# model. Tracks gpt-5.6-sol, the default that pass runs on."codex-auto-review": (2.0, 10.0),diff --git a/jarvis/brain/local_outcome_gate.py b/jarvis/brain/local_outcome_gate.pyindex bc272cb601..3816e891ca 100644--- a/jarvis/brain/local_outcome_gate.py+++ b/jarvis/brain/local_outcome_gate.py@@ -194,6 +194,49 @@ RUN_SHELL_TIMER_DIRECTIVE = ()+# Preserve filename dots and coordinated prohibitions: commas alone must not+# turn "do not send, run commands, or change files" into positive requests.+_TASK_CLAUSE_RE = re.compile(+ r"[;!?\r\n]+|(?<!\d)\.(?=\s|$)|"+ r"\b(?:but|however|instead(?!\s+of)|aber|sondern|stattdessen)\b|" # i18n-allow+ r",\s+(?:and|und)\s+(?=(?:please\s+|bitte\s+)?" # i18n-allow+ + _FS_VERB_RE.pattern + r")"+)+_QUOTED_LITERAL_RE = re.compile(+ r'''(?<!\w)(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`[^`]*`)'''+)+_COMMAND_LITERAL_PREFIX_RE = re.compile(+ r"\b(?:run|execute|launch|fuehre|starte)\s+(?:(?:the|this|following)\s+)?$", # i18n-allow+ re.IGNORECASE,+)+_NEGATED_TASK_RE = re.compile(+ r"\b(?:do\s+not|does\s+not|did\s+not|don['\u2019]t|never|without|avoid|"+ r"instead\s+of|not(?=\s+(?:create|delete|remove|copy|move|rename|run|execute|open)\b)|"+ r"nicht|keine?\w*|ohne|vermeide\w*)\b" # i18n-allow+)+_ACTION_BOUNDARY_RE = re.compile(r",|\b(?:and|und)\b") # i18n-allow+_EXPLANATORY_FOLLOWUP_RE = re.compile(+ r"^\s*(?:(?:and|then|please)\s+)*(?:show|list|explain|describe|give|include|"+ r"write|outline|provide|read)\b|"+ r"^\s*(?:(?:und|dann|bitte)\s+)*(?:zeig\w*|erklaer\w*|liste\w*|beschreib\w*)\b" # i18n-allow+)+++def _positive_task_prefix(clause: str) -> str:+ """Keep an earlier positive action, never the following prohibited list."""+ negative = _NEGATED_TASK_RE.search(clause)+ if negative is None:+ return clause+ prefix = clause[:negative.start()]+ marker = negative.group()+ if marker == "nicht" or marker.startswith("kein"):+ # German postposed negation also negates its preceding action.+ # English noun filters such as "files not ending in .tmp" do not.+ boundaries = list(_ACTION_BOUNDARY_RE.finditer(prefix))+ return prefix[:boundaries[-1].start()] if boundaries else ""+ return prefix++def resolve_local_outcome_mandate(utterance: str) -> tuple[str, str] | None:"""Map a local file/folder/system request to ``(tool_name, directive)``.@@ -207,30 +250,45 @@ def resolve_local_outcome_mandate(utterance: str) -> tuple[str, str] | None:# Whisper artefacts, not commands.if len(raw) < 6:return None- t = _normalize(raw)- if _HOWTO_DEFINITION_RE.search(t):- return None- if _GUI_VEHICLE_RE.search(t) or _OTHER_VEHICLE_RE.search(t):- return None- if _CLOUD_STORAGE_RE.search(t):- return None- if _FOREIGN_DOMAIN_RE.search(t):- return None- # External dispatch ("schick … per Mail") — checked on the RAW text,- # the detector does its own normalisation.- if requires_external_integration(raw):- return None- # Timer class first: a timer noun plus a set/stop verb or a bare duration- # ("Timer 10 Minuten"). Independent of the file-system nouns below.- if _TIMER_OBJECT_RE.search(t) and (- _TIMER_VERB_RE.search(t) or _DURATION_RE.search(t)- ):- return ("run_shell", RUN_SHELL_TIMER_DIRECTIVE)- if not _FS_OBJECT_RE.search(t):- return None- if not _FS_VERB_RE.search(t):+ # A quoted filename or example is a literal, not an instruction/context+ # marker. Preserve apostrophes inside words such as "don't".+ def mask_literal(match: re.Match[str]) -> str:+ # An explicit "run <quoted command>" still names an executable object.+ # Its contents remain shielded from negation and vehicle detection.+ prefix = _normalize(raw[:match.start()])+ return " command " if _COMMAND_LITERAL_PREFIX_RE.search(prefix) else " quoted_literal "++ normalized = _normalize(_QUOTED_LITERAL_RE.sub(mask_literal, raw))+ tasks = [_positive_task_prefix(clause).strip() for clause in _TASK_CLAUSE_RE.split(normalized)]+ # An explicitly selected vehicle governs the subsequent action, even+ # across a sentence boundary ("Use the mouse. Create a folder.").+ if any(_GUI_VEHICLE_RE.search(task) or _OTHER_VEHICLE_RE.search(task) for task in tasks):return None- return ("run_shell", RUN_SHELL_OUTCOME_DIRECTIVE)+ explanatory = False+ for t in tasks:+ # Resolve each task independently. A verb in the handoff footer must+ # not borrow "files" from an earlier prohibition or quoted subject.+ if not t:+ continue+ if _HOWTO_DEFINITION_RE.search(t):+ explanatory = True+ continue+ # "Show the commands" following a how-to question requests content,+ # not execution. An independent imperative ("Now create a folder")+ # still reaches the normal action detector.+ if explanatory and _EXPLANATORY_FOLLOWUP_RE.search(t):+ continue+ if _CLOUD_STORAGE_RE.search(t) or _FOREIGN_DOMAIN_RE.search(t):+ continue+ if requires_external_integration(t):+ continue+ if _TIMER_OBJECT_RE.search(t) and (+ _TIMER_VERB_RE.search(t) or _DURATION_RE.search(t)+ ):+ return ("run_shell", RUN_SHELL_TIMER_DIRECTIVE)+ if _FS_OBJECT_RE.search(t) and _FS_VERB_RE.search(t):+ return ("run_shell", RUN_SHELL_OUTCOME_DIRECTIVE)+ return None__all__ = [diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.pyindex 3cc2784dba..6191c3a4d7 100644--- a/jarvis/brain/manager.py+++ b/jarvis/brain/manager.py@@ -98,7 +98,7 @@ from jarvis.voice.action_phrases import ()from jarvis.voice.contextual_readback import render_readback-from .action_honesty import replace_unbacked_action_claim+from .action_honesty import has_unbacked_action_claim, replace_unbacked_action_claimfrom .assistant_name import (DEFAULT_ASSISTANT_NAME,resolve_assistant_name,@@ -3226,6 +3226,11 @@ class BrainManager:self, name: str, fallback: str | None = None) -> str | None:"""Resolve an explicit Tool Model pin before a caller's model choice."""+ from jarvis.core.model_selection import operation_model, worker_selection++ selection = operation_model.get() or worker_selection(self._config)+ if selection is not None and selection.provider == name:+ return selection.model or fallback or get_tier_default_model("worker", name)cfg = self._provider_cfg(name)if cfg is None:return fallback or get_tier_default_model("router", name)@@ -3239,6 +3244,11 @@ class BrainManager:def _tool_model_provider(self) -> str:"""Return the canonical Tool Model provider or its legacy fallback."""+ from jarvis.core.model_selection import operation_model, worker_selection++ selection = operation_model.get() or worker_selection(self._config)+ if selection is not None:+ return selection.providertry:brain_cfg = self._config.braincanonical = getattr(brain_cfg, "tool_model", None)@@ -3444,6 +3454,12 @@ class BrainManager:self, chain: list[tuple[str, str | None]]) -> list[tuple[str, str | None]]:"""Filter a delegated turn to tool-capable cross-family candidates."""+ from jarvis.core.model_selection import operation_model, worker_selection++ selection = operation_model.get() or worker_selection(self._config)+ if selection is not None:+ # A selected subscription must not silently turn into metered API usage.+ return [(selection.provider, selection.model)]configured = self._tool_model_provider()candidates = list(chain)if configured and configured != "auto":@@ -12533,8 +12549,11 @@ class BrainManager:self._evidence_required_is_write,)response_text = _replacement+ if turn_override is not None:+ turn_override.receipt.mark_guard_failure("mandated_tool_unfulfilled")execution_evidence = set(_turn_executed)+ full_action_fallback = not execution_evidence and has_unbacked_action_claim(response_text)honest_response = replace_unbacked_action_claim(response_text,executed_tools=execution_evidence,@@ -12545,6 +12564,8 @@ class BrainManager:"Blocked a model action promise with no execution evidence.")response_text = honest_response+ if full_action_fallback and turn_override is not None:+ turn_override.receipt.mark_guard_failure("unbacked_action_claim")# 4. History + Eventsif use_history:@@ -13410,6 +13431,32 @@ class BrainManager:model_tier: str = "auto",trace_id: UUID | None = None,prefer_api: bool = False,+ ) -> str:+ """Keep the selected agent and billing account for the entire scheduled turn."""+ from jarvis.core.model_selection import (+ operation_model,+ use_operation_model,+ worker_selection,+ )++ selected = operation_model.get() or worker_selection(self._config)+ with use_operation_model(selected):+ return await self._run_task_with_selection(+ prompt=prompt,+ allowed_tools=allowed_tools,+ model_tier=model_tier,+ trace_id=trace_id,+ prefer_api=prefer_api,+ )++ async def _run_task_with_selection(+ self,+ *,+ prompt: str,+ allowed_tools: tuple[str, ...] = (),+ model_tier: str = "auto",+ trace_id: UUID | None = None,+ prefer_api: bool = False,) -> str:"""Run one isolated agentic turn for a scheduled task.@@ -13421,9 +13468,10 @@ class BrainManager:actions still hit the approval gate (which, with no human present,means they block until the unattended-approval wave wires Option B).- Provider order (BUG-212): the Tool Model leads, then every other- credential-ready, tool-capable provider of a different family — see- :meth:`_task_provider_chain`. A credential / credit / rate-limit+ An explicit agent selection stays fixed, including subscription tasks.+ Until migration selects an agent, the legacy credential-ready provider+ chain remains available — see :meth:`_task_provider_chain`.+ A credential / credit / rate-limiterror (401/402/403/429 — the same classes the chat path dead-listsor cools down) moves the SAME turn on to the next candidate; anyother error propagates so the runner records it in ``last_error``.@@ -13438,6 +13486,14 @@ class BrainManager:del prefer_apiintent = "deep" if model_tier == "deep" else "fast"tools = self._select_task_tools(allowed_tools)+ from jarvis.core.model_selection import operation_model, worker_selection+ from jarvis.core.task_agent import run_selected, subscription_seat++ selected = operation_model.get() or worker_selection(self._config)+ if selected is not None and subscription_seat(selected.provider) is not None:+ return await run_selected(+ selection=selected, prompt=prompt, tool_names=tuple(tools), trace_id=trace_id+ )# The per-turn context (date/time, awareness, wiki) rides on the user# message in cache-optimized mode; without it a scheduled turn did not# know what day it was (BUG-212 — the morning brief prompts say "the@@ -13505,6 +13561,11 @@ class BrainManager:an unattended background turn. Capped so an unattended run cannotwalk a long chain for minutes."""+ from jarvis.core.model_selection import operation_model, worker_selection++ selected = operation_model.get() or worker_selection(self._config)+ if selected is not None:+ return [(selected.provider, selected.model)]try:ready = self._hoist_tool_model(self._tool_model_base_chain())except Exception: # noqa: BLE001 — a broken probe must not kill the taskdiff --git a/jarvis/brain/provider_test.py b/jarvis/brain/provider_test.pyindex ec8ae38f28..deb70569cd 100644--- a/jarvis/brain/provider_test.py+++ b/jarvis/brain/provider_test.py@@ -391,6 +391,35 @@ async def _default_realtime_probe(spec: Any, cfg: Any, *, timeout_s: float) -> fprovider = (from_runtime_config(cfg) if callable(from_runtime_config) else provider_cls())+ if getattr(provider, "continuous_conversation", False):+ from jarvis.core.protocols import ContinuousVoiceStart+ from jarvis.live.recovery import connection_permit++ profile = cfg.live+ config = profile.session_config(language="en", tools=[])+ config["instructions"] = "Connection validation only. Do not speak."++ async def continuous_probe() -> float:+ started = perf_counter()+ await connection_permit()+ session = await provider.open_session(ContinuousVoiceStart(session=config))+ try:+ while True:+ event = await session.receive()+ if event.get("type") == "session.started":+ latency_ms = (perf_counter() - started) * 1000.0+ await session.send({"type": "session.close"})+ return latency_ms+ if event.get("type") in {"error", "session.closed"}:+ raise RuntimeError(+ "Continuous voice rejected the selected session. "+ "Check the Live model, voice and thinking-model settings."+ )+ finally:+ await session.close()++ return await asyncio.wait_for(continuous_probe(), timeout=timeout_s)+session_config = RealtimeSessionConfig(instructions="Connection validation only. Do not respond until audio arrives.",language="en",diff --git a/jarvis/brain/tool_use_loop.py b/jarvis/brain/tool_use_loop.pyindex 4bf890e48a..9e9f83befd 100644--- a/jarvis/brain/tool_use_loop.py+++ b/jarvis/brain/tool_use_loop.py@@ -1595,7 +1595,10 @@ class ToolUseLoop:"type": "tool_result","tool_use_id": call_id,"content": _cap_tool_result_json(- json.dumps(tool_result_payload, ensure_ascii=False, default=str)+ json.dumps(+ tool_result_payload, ensure_ascii=False,+ separators=(",", ":"), default=str,+ )),}],tool_call_id=call_id,diff --git a/jarvis/brain/turn_override.py b/jarvis/brain/turn_override.pyindex e2689ba282..788afccc1e 100644--- a/jarvis/brain/turn_override.py+++ b/jarvis/brain/turn_override.py@@ -20,12 +20,14 @@ from __future__ import annotationsfrom collections.abc import Callable, Mappingfrom dataclasses import dataclass, field-from typing import Any+from typing import Any, Literalfrom jarvis.core.protocols import ReasoningEffort, Toolfrom .loop_control import LoopControl+GuardFailureReason = Literal["mandated_tool_unfulfilled", "unbacked_action_claim"]+@dataclass(slots=True)class TurnReceipt:@@ -42,6 +44,15 @@ class TurnReceipt:tokens_out: int = 0cost_usd: float = 0.0finish_reason: str = ""+ # Provider completion is separate from a later honesty guard rejecting+ # its answer. Callers must not label a full fallback as completed work.+ guard_failure: bool = False+ failure_reason: GuardFailureReason | Literal[""] = ""++ def mark_guard_failure(self, reason: GuardFailureReason) -> None:+ if not self.guard_failure:+ self.guard_failure = True+ self.failure_reason = reasondef record(self,@@ -59,6 +70,8 @@ class TurnReceipt:self.tokens_out = int(tokens_out)self.cost_usd = float(cost_usd)self.finish_reason = finish_reason+ self.guard_failure = False+ self.failure_reason = ""def usage(self) -> dict[str, Any]:"""The ``usage`` dict an agent-chat ``turn_finished`` event carries."""@@ -127,4 +140,4 @@ class TurnOverride:receipt: TurnReceipt = field(default_factory=TurnReceipt)-__all__ = ["TurnOverride", "TurnReceipt"]+__all__ = ["GuardFailureReason", "TurnOverride", "TurnReceipt"]diff --git a/jarvis/browser_voice/route.py b/jarvis/browser_voice/route.pyindex 9c5829f609..0136e32766 100644--- a/jarvis/browser_voice/route.py+++ b/jarvis/browser_voice/route.py@@ -43,9 +43,9 @@ _UNSAFE_FALLBACK_DETAIL = ("duplicate actions.")_USAGE_FALLBACK_DISABLED_DETAIL = (- "Selected realtime access failed. Automatic usage-billed API fallback is "- "disabled for this provider; configure an explicit realtime fallback or "- "restore its subscription access."+ "The selected voice connection could not start. Check its connection and "+ "model settings. Automatic usage-billed API fallback is disabled; "+ "Jarvis did not switch to another provider.")# BCP-47 from the canonical per-turn resolver (de/en/es).diff --git a/jarvis/cli_ctl/__main__.py b/jarvis/cli_ctl/__main__.pyindex 21478abf33..86e1e46fb3 100644--- a/jarvis/cli_ctl/__main__.py+++ b/jarvis/cli_ctl/__main__.py@@ -1,12 +1,15 @@"""jarvisctl entry point. Real commands are wired in here."""+from __future__ import annotationsimport loggingimport osimport sys+from typing import Anyimport clickimport typer+from typer.core import TyperGroup# Windows defaults to cp1252; force UTF-8 so non-ASCII help/output is intact.try: # reconfigure exists on TextIO in 3.7+; guard for exotic stdio wrappers@@ -47,8 +50,38 @@ from jarvis.cli_ctl.commands import telephony as telephony_cmdfrom jarvis.cli_ctl.commands import wiki as wiki_cmdfrom jarvis.cli_ctl.commands import workflows as workflows_cmd++class _CompatibleRootGroup(TyperGroup):+ """Honor external Click command exits under Typer's vendored Click root.++ Dynamic commands use the declared Click dependency. Newer Typer versions+ vendor a separate exception family, so nested help/errors otherwise escape+ the root handler as tracebacks. Older shared-Click Typer versions simply+ finish inside the parent handler and never reach this compatibility boundary.+ """++ def main(self, *args: Any, **kwargs: Any) -> Any:+ try:+ return super().main(*args, **kwargs)+ except click.exceptions.Exit as exc:+ if not kwargs.get("standalone_mode", True):+ return exc.exit_code+ raise SystemExit(exc.exit_code) from None+ except click.ClickException as exc:+ if not kwargs.get("standalone_mode", True):+ raise+ exc.show()+ raise SystemExit(exc.exit_code) from None+ except click.Abort:+ if not kwargs.get("standalone_mode", True):+ raise+ click.echo("Aborted!", err=True)+ raise SystemExit(1) from None++app = typer.Typer(name="jarvisctl",+ cls=_CompatibleRootGroup,no_args_is_help=True,add_completion=True,help="Control a running Personal Jarvis instance from the terminal.",@@ -67,7 +100,9 @@ def _root(None, "--url", help="Override the Jarvis base URL (e.g. http://host:port)."),key: str | None = typer.Option(- None, "--key", hide_input=True,+ None,+ "--key",+ hide_input=True,help="Override the control API key (Bearer token) for this call only.",),) -> None:@@ -174,6 +209,18 @@ def _first_subcommand(argv: list[str]) -> str | None:return None+def _root_options(root: click.Group, argv: list[str]) -> tuple[dict[str, object], str | None]:+ """Parse root options without running Click/Typer parameter or command callbacks.++ The root callback runs only after the dynamic command tree must exist.+ Click's option parser already handles split/equal values, ``--`` and root+ option boundaries; raw token scanning cannot safely supply credentials.+ """+ context = root.context_class(root)+ values, remaining, _ = root.make_parser(context).parse_args(list(argv))+ return values, remaining[0] if remaining else None++def build_root_command(argv: list[str] | None = None) -> click.Group:"""Return the Click root: the Typer app plus the grafted dynamic `api` group.@@ -186,14 +233,26 @@ def build_root_command(argv: list[str] | None = None) -> click.Group:if argv is None:argv = sys.argv[1:]root: click.Group = typer.main.get_command(app)- wants_api = not _in_completion() and _first_subcommand(argv) == "api"try:+ options, command = _root_options(root, argv)+ wants_api = not _in_completion() and not options.get("help") and command == "api"+ # Construction must not read STATE: it may still describe a previous+ # invocation in an embedded CLI or CliRunner process. The real root+ # callback will set STATE later for actual command execution.+ profile = _config.resolve_profile()+ url_option, key_option = options.get("url"), options.get("key")+ selected_url = (+ url_option if isinstance(url_option, str) and url_option else profile.base_url+ )+ selected_key = (+ key_option if isinstance(key_option, str) and key_option else profile.control_key+ )if wants_api:- with make_client() as client:+ with JarvisClient(base_url=selected_url, control_key=selected_key) as client:spec = openapi_cache.load_spec(client)else:- # cache-only: ttl effectively infinite, no fetch attempt- spec, _ = openapi_cache._read_cache()+ # Cache-only for this origin: TTL effectively infinite, no fetch attempt.+ spec, _ = openapi_cache._read_cache(base_url=selected_url)if spec:from jarvis.cli_ctl.dynamic import build_api_group@@ -206,13 +265,16 @@ def build_root_command(argv: list[str] | None = None) -> click.Group:click.echo("The dynamic `api` command group is unavailable (no cached "- "schema yet). " + doctor.unreachable_message(None),+ "schema yet). "+ + doctor.unreachable_message(openapi_cache.server_origin(selected_url)),err=True,)except Exception as exc: # noqa: S110 - static surface must work if dynamic build fails# The static surface must always work even if the dynamic build fails;# log at DEBUG so a missing `api` group stays diagnosable.- logging.getLogger(__name__).debug("dynamic api group unavailable: %s", exc)+ # Parser/client exceptions may contain option values or a credential-bearing+ # URL. Preserve the failure class, never credentials or remote response text.+ logging.getLogger(__name__).debug("dynamic api group unavailable (%s)", type(exc).__name__)return root@@ -221,4 +283,8 @@ def main() -> None:if __name__ == "__main__":- main()+ # Static commands import this canonical module for request/output state.+ # Executing a separate __main__ instance would lose explicit URL/key flags.+ from jarvis.cli_ctl.__main__ import main as canonical_main++ canonical_main()diff --git a/jarvis/cli_ctl/commands/auth.py b/jarvis/cli_ctl/commands/auth.pyindex bab7db6f08..715e141674 100644--- a/jarvis/cli_ctl/commands/auth.py+++ b/jarvis/cli_ctl/commands/auth.py@@ -1,4 +1,5 @@"""auth: store/verify the control key for a Jarvis target."""+from __future__ import annotationsimport typer@@ -27,11 +28,12 @@ def _probe(url: str, key: str) -> bool:def login(url: str = typer.Option(..., "--url", help="Base URL, e.g. http://127.0.0.1:47821"),key: str = typer.Option(- None, "--key",+ None,+ "--key",prompt="Control key (jctl_…)",hide_input=True,help="Control key. Omit to be prompted (hidden), or pass '-' to read it "- "from stdin. Avoid an inline value — it leaks into shell history.",+ "from stdin. Avoid an inline value — it leaks into shell history.",),) -> None:"""Verify the key against the server and persist it for future calls.@@ -60,15 +62,16 @@ def status(key: str = typer.Option(None, "--key"),) -> None:"""Report whether the configured (or given) target is reachable."""- from jarvis.cli_ctl.__main__ import as_json-- prof = config.resolve_profile()- target = url or prof.base_url- use_key = key or prof.control_key or ""- reachable = _probe(target, use_key)- render.emit(- {"base_url": target, "reachable": reachable}, as_json=as_json()- )+ from jarvis.cli_ctl.__main__ import as_json, make_client++ with make_client(url=url, key=key) as client:+ target = client.base_url+ try:+ client.request("GET", _PROBE)+ reachable = True+ except ApiError:+ reachable = False+ render.emit({"base_url": target, "reachable": reachable}, as_json=as_json())if not reachable:raise typer.Exit(code=1)diff --git a/jarvis/cli_ctl/openapi_cache.py b/jarvis/cli_ctl/openapi_cache.pyindex 642f7ab72a..4513414df7 100644--- a/jarvis/cli_ctl/openapi_cache.py+++ b/jarvis/cli_ctl/openapi_cache.py@@ -1,81 +1,162 @@-"""Fetch and cache the server's OpenAPI document, cross-platform & offline-safe.--The cache lives under platformdirs' user cache dir. Freshness is purely-TTL-based: within the TTL the cached spec is served from disk with no network-call; once it expires the next invocation re-fetches the full document. The-server exposes no cheap live-version probe (``/api/openapi.json`` carries no-ETag and there is no lightweight version endpoint), so we deliberately do NOT-attempt conditional/ETag revalidation -- comparing the cached spec's version-against the cached meta's version would be a no-op (they are written together),-and a real drift check would need a live probe we do not have. A newly added-endpoint becomes visible after the TTL lapses or immediately via ``clear_cache``-("jarvisctl refresh"). When the server is unreachable we degrade to the last-cached spec; with no cache at all we return None so the caller can skip the-dynamic command tree without crashing.+"""Fetch a server-scoped OpenAPI schema, with same-server offline fallback.++Within the TTL a matching cache is used without network access. Expired entries+are refreshed from the selected server; only a transport failure may fall back+to that server's previous schema. A different origin/base path or an unbound cache+can never supply its command tree. ``jarvisctl refresh`` clears all entries.++Each entry stores its spec and server metadata atomically in one file. URL+normalization drops userinfo, query strings and fragments; no control key or+credential-bearing URL is written to the cache or diagnostics."""+from __future__ import annotations+import hashlibimport json+import logging+import os+import tempfileimport time+from pathlib import Pathfrom typing import Any+from urllib.parse import urlsplit++import httpxfrom jarvis.cli_ctl import pathsfrom jarvis.cli_ctl.client import ApiError, JarvisClientOPENAPI_PATH = "/api/openapi.json"DEFAULT_TTL = 24 * 3600+log = logging.getLogger(__name__)-def _read_cache() -> tuple[dict[str, Any] | None, dict[str, Any]]:- spec_p, meta_p = paths.openapi_cache_file(), paths.openapi_meta_file()- spec = meta = None- if spec_p.exists():- try:- spec = json.loads(spec_p.read_text(encoding="utf-8"))- except (ValueError, OSError):- spec = None- if meta_p.exists():- try:- meta = json.loads(meta_p.read_text(encoding="utf-8"))- except (ValueError, OSError):- meta = None- return spec, (meta or {})+def server_origin(base_url: str) -> str:+ """Canonical HTTP origin without credentials or URL parameters."""+ try:+ parsed = urlsplit(base_url)+ scheme, hostname, port = parsed.scheme.lower(), parsed.hostname, parsed.port+ if scheme not in {"http", "https"} or not hostname:+ raise ValueError("unsupported server URL")+ except ValueError:+ # urllib errors may include user input; do not propagate their text.+ raise ValueError("invalid server origin") from None+ host = hostname.lower()+ if ":" in host:+ host = f"[{host}]"+ default_port = 80 if scheme == "http" else 443+ suffix = f":{port}" if port is not None and port != default_port else ""+ return f"{scheme}://{host}{suffix}"-def _write_cache(spec: dict[str, Any]) -> None:- paths.openapi_cache_file().write_text(- json.dumps(spec, ensure_ascii=False), encoding="utf-8"- )- paths.openapi_meta_file().write_text(- json.dumps({"fetched_at": time.time()}, ensure_ascii=False),- encoding="utf-8",+def _cache_path(base_url: str) -> Path:+ identity = server_origin(base_url) + _base_path(base_url)+ fingerprint = hashlib.sha256(identity.encode("utf-8")).hexdigest()+ return paths.cache_dir() / f"openapi-{fingerprint}.json"+++def _base_path(base_url: str) -> str:+ """Match httpx's normalized, slash-terminated request prefix exactly."""+ try:+ raw_path = httpx.URL(base_url).copy_with(query=None, fragment=None).raw_path+ except (ValueError, httpx.InvalidURL):+ raise ValueError("invalid server base path") from None+ # Do not strip multiple trailing slashes or unquote escaped path separators:+ # httpx preserves both in actual requests, so different mounts stay isolated.+ if not raw_path.endswith(b"/"):+ raw_path += b"/"+ return raw_path.decode("ascii")+++def _valid_spec(value: Any) -> bool:+ """Reject login/error payloads before they become a dynamic command tree."""+ return (+ isinstance(value, dict)+ and isinstance(value.get("openapi"), str)+ and value["openapi"].startswith("3.")+ and isinstance(value.get("info"), dict)+ and isinstance(value.get("paths"), dict))+def _read_cache(*, base_url: str) -> tuple[dict[str, Any] | None, dict[str, Any]]:+ try:+ entry = json.loads(_cache_path(base_url).read_text(encoding="utf-8"))+ except (ValueError, OSError):+ return None, {}+ if (+ not isinstance(entry, dict)+ or entry.get("origin") != server_origin(base_url)+ or entry.get("base_path") != _base_path(base_url)+ ):+ return None, {}+ spec = entry.get("spec")+ if not _valid_spec(spec):+ return None, {}+ return spec, {"origin": entry["origin"], "fetched_at": entry.get("fetched_at")}+++def _write_cache(spec: dict[str, Any], *, base_url: str) -> None:+ if not _valid_spec(spec):+ raise ValueError("invalid OpenAPI schema")+ path = _cache_path(base_url)+ entry = {+ "origin": server_origin(base_url),+ "base_path": _base_path(base_url),+ "fetched_at": time.time(),+ "spec": spec,+ }+ temporary: Path | None = None+ try:+ with tempfile.NamedTemporaryFile(+ mode="w",+ encoding="utf-8",+ prefix="openapi-",+ suffix=".tmp",+ dir=path.parent,+ delete=False,+ ) as stream:+ temporary = Path(stream.name)+ json.dump(entry, stream, ensure_ascii=False)+ os.replace(temporary, path)+ temporary = None+ finally:+ if temporary is not None:+ temporary.unlink(missing_ok=True)++def clear_cache() -> None:- for p in (paths.openapi_cache_file(), paths.openapi_meta_file()):- if p.exists():- p.unlink()---def load_spec(- client: JarvisClient, *, ttl_seconds: int = DEFAULT_TTL-) -> dict[str, Any] | None:- spec, meta = _read_cache()- # Freshness is TTL-only -- see the module docstring for why there is no- # version/ETag-based revalidation. A negative age means the wall clock- # moved backwards (VM restore, container clock drift); treat that as- # stale rather than "fresh forever".- age = time.time() - float(meta.get("fetched_at", 0)) if meta else None+ # Legacy unbound entries are never loaded, but refresh still removes them.+ entries = [paths.openapi_cache_file(), paths.openapi_meta_file()]+ entries.extend(paths.cache_dir().glob("openapi-*.json"))+ for path in entries:+ path.unlink(missing_ok=True)+++def load_spec(client: JarvisClient, *, ttl_seconds: int = DEFAULT_TTL) -> dict[str, Any] | None:+ spec, meta = _read_cache(base_url=client.base_url)+ try:+ age = time.time() - float(meta.get("fetched_at", 0)) if meta else None+ except (TypeError, ValueError):+ age = None+ # A backward wall-clock jump must not keep an entry fresh forever.fresh = spec is not None and age is not None and 0 <= age < ttl_secondsif fresh:return spec# Stale or missing: try to (re)fetch the full document.try:fetched = client.request("GET", OPENAPI_PATH)- except ApiError:- return spec # unreachable -> stale cache (may be None)- if isinstance(fetched, dict):- _write_cache(fetched)+ except ApiError as exc:+ # An authentication refusal is not offline access to private metadata.+ return spec if exc.status_code is None else None+ if _valid_spec(fetched):+ try:+ _write_cache(fetched, base_url=client.base_url)+ except OSError as exc:+ # A read-only cache directory must not hide a successfully fetched API.+ log.debug("OpenAPI cache write unavailable (%s)", type(exc).__name__)return fetched- return spec+ # A reachable login page, redirect body or malformed schema is not an+ # offline condition. Never hide it behind stale commands from an old build.+ return Nonediff --git a/jarvis/commands/registry.py b/jarvis/commands/registry.pyindex d1e9e7316a..7dc772a6e2 100644--- a/jarvis/commands/registry.py+++ b/jarvis/commands/registry.py@@ -193,9 +193,13 @@ def _build_registry() -> tuple[AppCommand, ...]:description=("Create an agent in the user's existing Agents team, only when requested. ""This creates a roster profile and starts no work. Responsibilities derive "- "capabilities through the same service as the Agents UI. Read the returned "- "agent and created flag: an existing name is adopted, never duplicated. "- "Use society-switch-agent-model only if a specific provider is requested."+ "capabilities through the same service as the Agents UI. When a team agent "+ "creates a teammate, the new agent inherits that creator's model seat "+ "(provider, model, effort, subscription account) and permission setup "+ "(ceiling, grant mode, grants, denies) and cannot exceed them. Read the "+ "returned agent and created flag: an existing name is adopted, never "+ "duplicated. Use society-switch-agent-model only if a different provider "+ "is requested."),method="POST", path="/api/society/agents", ui_section="agents",params={"type": "object", "properties": {diff --git a/jarvis/core/events.py b/jarvis/core/events.pyindex 3a091843e6..5ec2ded59b 100644--- a/jarvis/core/events.py+++ b/jarvis/core/events.py@@ -116,6 +116,28 @@ class TranscriptionUpdate(Event):is_final: bool = False+@dataclass(frozen=True, slots=True)+class VoiceTranscriptUpdated(Event):+ """Idempotent caption snapshot for one continuous-voice speech segment."""++ session_id: str = ""+ segment_id: str = ""+ role: Literal["user", "assistant"] = "user"+ text: str = ""+ start_ms: int = 0+ end_ms: int = 0+ revision: int = 1+++@dataclass(frozen=True, slots=True)+class ReasoningSummaryUpdated(Event):+ """Provider-exposed reasoning summary, never private reasoning or audio."""++ response_id: str = ""+ text: str = ""+ done: bool = False++@dataclass(frozen=True, slots=True)class TranscriptPolished(Event):"""A finished voice turn, re-read and written out as prose.@@ -1558,7 +1580,7 @@ class BrainTTFT(Event):@dataclass(frozen=True, slots=True)class AudioOutFirst(Event):- """The WASAPI player sent the first sample to the output device.+ """The native player or browser playback began audible output.Last stage event of a voice turn; marks TTFW = audio audible to the user."""diff --git a/jarvis/core/model_selection.py b/jarvis/core/model_selection.pyindex 0af902126a..e5b1e7642c 100644--- a/jarvis/core/model_selection.py+++ b/jarvis/core/model_selection.py@@ -35,7 +35,7 @@ def worker_selection(config: Any) -> ModelSelection | None:@contextmanager-def use_operation_model(selection: ModelSelection):+def use_operation_model(selection: ModelSelection | None):token = operation_model.set(selection)try:yielddiff --git a/jarvis/core/protocols.py b/jarvis/core/protocols.pyindex d6e7192e74..1724a50951 100644--- a/jarvis/core/protocols.py+++ b/jarvis/core/protocols.py@@ -752,3 +752,29 @@ class CodingSessionGateway(Protocol):async def run(self, args: dict[str, Any]) -> dict[str, Any]:"""Discover, open, send, or read using explicit persistent IDE identities."""...+++class MarsStationExecutor(Protocol):+ """Trusted task boundary; world movement and animation grant no authority."""++ async def authorize(self, *, agent_id: str, capability_id: str) -> None:+ """Validate the actual agent and supported capability before accepting work."""+ ...++ async def dispatch(+ self, *, agent_id: str, command_id: str, trace_id: str, draft: str+ ) -> dict[str, Any]:+ """Dispatch once through existing authorized execution, returning durable references."""+ ...++ async def inspect(+ self, *, agent_id: str, command_id: str, trace_id: str, task_ref: str | None+ ) -> dict[str, Any]:+ """Reconcile authoritative task state without repeating an external effect."""+ ...++ async def cancel(+ self, *, agent_id: str, command_id: str, trace_id: str, task_ref: str | None+ ) -> dict[str, Any]:+ """Request cancellation through the owning task service, then report its state."""+ ...diff --git a/jarvis/live/config.py b/jarvis/live/config.pyindex 7dbeb685dc..37be55ecb6 100644--- a/jarvis/live/config.py+++ b/jarvis/live/config.py@@ -31,6 +31,8 @@ class LiveConfig(BaseModel):"not completion. Use discover_tools and call_tool for additional capabilities. ""A superseded result describes earlier work, not the latest request; reconcile ""the actual outcome with the latest correction without blindly repeating actions. "+ "Discover only the tools needed for the current task using a few English "+ "keywords; reuse their schemas and still-current results from this conversation. ""Read tool schemas before calling. Do not bypass denied actions. ""Computer-use tasks use the selected thinking model and the same credential. "+ self.backend_instructions@@ -39,7 +41,7 @@ class LiveConfig(BaseModel):"parallel_tool_calls": False,}if self.reasoning_effort:- backend["reasoning"] = {"effort": self.reasoning_effort}+ backend["reasoning"] = {"effort": self.reasoning_effort, "summary": "auto"}language_rule = ("Use the user's language and follow explicit language changes. "if language == "auto"diff --git a/jarvis/live/cost.py b/jarvis/live/cost.pynew file mode 100644index 0000000000..d68f497e5f--- /dev/null+++ b/jarvis/live/cost.py@@ -0,0 +1,21 @@+"""Price Live's delegated usage, including explicit cache-write tokens."""++from jarvis.brain.cost import calculate_cost_usd+++def backend_cost_usd(model: str, usage: dict) -> float:+ """Input totals include both cache reads and writes; charge each exactly once.++ Cache writes reported by Responses cost 1.25 times the standard input rate.+ Older models without this usage field keep their existing input accounting.+ Source: https://developers.openai.com/api/docs/guides/prompt-caching+ """+ total = max(0, int(usage.get("input_tokens", 0)))+ details = usage.get("input_tokens_details") or {}+ cached = min(total, max(0, int(details.get("cached_tokens", 0))))+ uncached = total - cached+ writes = min(uncached, max(0, int(details.get("cache_write_tokens", 0))))+ output = max(0, int(usage.get("output_tokens", 0)))+ return calculate_cost_usd(model, uncached, output, cached) + (+ 0.25 * calculate_cost_usd(model, writes, 0)+ )diff --git a/jarvis/live/discovery.py b/jarvis/live/discovery.pynew file mode 100644index 0000000000..59eb7b2aea--- /dev/null+++ b/jarvis/live/discovery.py@@ -0,0 +1,80 @@+"""On-demand tool schemas for the Responses voice backend, without another model."""++from __future__ import annotations++import json+import math+import re+from collections import Counter+from collections.abc import Iterable++from jarvis.core.protocols import SupervisorToolDescriptor++_PAGE_SIZE = 5+_PAGE_BYTES = 12_000+_STOP_WORDS = frozenset("a an and are for in is it of on or the to with jarvis".split())+++def _words(text: str) -> set[str]:+ # Split canonical snake/kebab names and punctuation as well as ordinary prose.+ words = set(re.findall(r"[^\W_]+", text.casefold())) - _STOP_WORDS+ return {+ word[:-1]+ if len(word) > 3 and word.endswith("s") and not word.endswith(("ss", "us", "is"))+ else word+ for word in words+ }+++def discover(catalog: Iterable[SupervisorToolDescriptor], query: str, offset: int = 0) -> dict:+ """Rank keyword overlap; keep every matching tool and its complete schema reachable.++ Requiring every word of a natural-language query to occur in one descriptor+ returned no results even for available tools. Matching any meaningful word+ and ranking by coverage avoids repeated unsuccessful paid search turns.+ """+ terms = _words(query)+ indexed = [(d, _words(d.name), _words(d.description)) for d in catalog]+ frequencies = Counter(+ word for _, names, descriptions in indexed for word in names | descriptions+ )+ weights = {word: math.log(1 + len(indexed) / (1 + frequencies[word])) for word in terms}+ ranked: list[tuple[float, SupervisorToolDescriptor]] = []+ for descriptor, name_words, description_words in indexed:+ name = descriptor.name.casefold()+ if query.strip().casefold() == name:+ # An exact lookup must not bring along other tools mentioning this name.+ ranked = [(1, descriptor)]+ break+ name_hits = sum(weights[word] for word in terms & name_words)+ description_hits = sum(weights[word] for word in terms & description_words)+ # Rare capability words beat generic API prose. Normalize descriptions+ # so a long, unrelated declaration cannot win merely by being verbose.+ score = 3 * name_hits + description_hits / (1 + len(description_words) / 100)+ if score or not terms:+ ranked.append((score, descriptor))+ ranked.sort(key=lambda entry: (-entry[0], entry[1].name))+ offset = max(0, offset)+ page: list[dict] = []+ for _, descriptor in ranked[offset : offset + _PAGE_SIZE]:+ item = {+ "name": descriptor.name,+ "description": descriptor.description,+ "parameters": descriptor.input_schema,+ }+ # Never slice a schema. One large required schema is allowed to exceed+ # the page target; pagination must always advance without hiding tools.+ if page and len(json.dumps([*page, item]).encode("utf-8")) > _PAGE_BYTES:+ break+ page.append(item)+ next_offset = offset + len(page)+ result = {+ "tools": page,+ "total": len(ranked),+ "next_offset": next_offset if next_offset < len(ranked) else None,+ }+ if not ranked:+ result["hint"] = (+ "Try fewer English keywords, an exact tool name, or an empty query to browse."+ )+ return resultdiff --git a/jarvis/live/media.py b/jarvis/live/media.pynew file mode 100644index 0000000000..c6146743b0--- /dev/null+++ b/jarvis/live/media.py@@ -0,0 +1,27 @@+"""Ephemeral browser media measurements; never transcripts or stored usage."""++from typing import Annotated, Literal++from pydantic import BaseModel, ConfigDict, Field, StrictBool++Level = Annotated[float, Field(strict=True, ge=0, le=1, allow_inf_nan=False)]+++class MediaLevels(BaseModel):+ """One normalized snapshot from the client that owns this voice session."""++ model_config = ConfigDict(frozen=True, extra="forbid")+ type: Literal["media_levels"]+ input_level: Level+ output_level: Level+ input_active: StrictBool+ playback_active: StrictBool+++class InputPrefix(BaseModel):+ """One PCM16 wake prefix before browser audio, never stored in a ledger."""++ model_config = ConfigDict(frozen=True, extra="forbid")+ type: Literal["input_prefix"] = "input_prefix"+ sample_rate: Annotated[int, Field(strict=True, ge=8_000, le=192_000)]+ audio: Annotated[str, Field(max_length=15_360_000)]diff --git a/jarvis/live/native.py b/jarvis/live/native.pyindex d443492fbb..4374fa59ac 100644--- a/jarvis/live/native.py+++ b/jarvis/live/native.py@@ -109,6 +109,7 @@ class NativeLiveVoiceSession(LiveVoiceSession):self._resampler = StreamingPcm16Resampler(int(message.get("sample_rate", 48000)), rate)register(self)self._pump_task = asyncio.create_task(self._pump(), name="native-live-events")+ await self._take_startup_input(message)await self._send_json({"type": "audio_ready",@@ -216,9 +217,16 @@ class NativeLiveVoiceSession(LiveVoiceSession):self._tools.user_text = event.text or ""if event.is_final:self._tools.revision += 1+ if self._bus is not None:+ from jarvis.core.events import BrainTurnStarted++ await self._bus.publish(BrainTurnStarted(+ source_layer="live.native", trace_id=self._indicator_trace_id,+ provider=self.active_provider, model=self._active_model,+ ))if not self._closing and not self._recovering:self._resume_needs_input = False- self._tools.accepting = True+ self._tools.accept_new_input()self._reconnect_attempts = 0from jarvis.core.turn_language import resolve_output_language@@ -254,15 +262,27 @@ class NativeLiveVoiceSession(LiveVoiceSession):"is_final": event.is_final,})+ stamp = time.monotonic_ns() // 1_000_000+ caption = self._transcript.feed(+ session_id=self.session_id, trace_id=self._indicator_trace_id,+ event_id=str(uuid4()), role=role, text=event.text or "",+ start_ms=stamp, end_ms=stamp, snapshot=role == "user",+ )+ if self._bus is not None:+ await self._bus.publish(caption)+ if role == "user" and event.is_final:+ self._transcript.finish("user")elif event.type == "tool_call":+ await self._note_thinking()task = asyncio.create_task(self._call(event, self._tools.revision))self._jobs.add(task)task.add_done_callback(self._jobs.discard)elif event.type in {"interrupted", "speech_started"}:self._speaking = Falseself._thinking = False- await self._send_json({"type": "tts_cancel"})+ await self._emit_indicator({"type": "tts_cancel"})elif event.type == "turn_complete":+ self._transcript.finish("assistant")await self._note_turn_end()elif event.type == "usage":usage = event.usage or {}@@ -338,7 +358,8 @@ class NativeLiveVoiceSession(LiveVoiceSession):self._tools.revision += 1if not self._recovering:self._resume_needs_input = False- self._tools.accepting = True+ self._tools.accept_new_input()+ self._reconnect_attempts = 0await self._connection.send_text(str(message.get("text", "")))else:await super().handle_control(message)@@ -353,7 +374,9 @@ class NativeLiveVoiceSession(LiveVoiceSession):if self._ended:returnself._ended = True+ self._clear_media_levels()self._closing = True+ await self._publish_phase("idle")self._hangup_reason = reasonunregister(self.session_id)if self._tools is not None:diff --git a/jarvis/live/runtime.py b/jarvis/live/runtime.pyindex 98c567ea5c..a3804c74a0 100644--- a/jarvis/live/runtime.py+++ b/jarvis/live/runtime.py@@ -53,13 +53,26 @@ def active() -> tuple[Any, ...]:return tuple(_active.values())+def owns_microphone(*, except_session_id: str | None = None) -> bool:+ """A pending or active browser call must not be replaced by a wake start."""+ return any(sid != except_session_id for sid in (*_opening, *_active))++async def close_all(reason: str = "hotkey") -> None:await asyncio.gather(*(session.end(reason=reason) for session in active()))-async def run_browser_call(bus: Any, hangup: asyncio.Event, *, timeout_s: float = 45.0) -> str:+async def run_browser_call(+ bus: Any,+ hangup: asyncio.Event,+ *,+ timeout_s: float = 45.0,+ input_buffer: Any = None,+ session_id: str = "",+) -> str:"""Wake hands media to the WebView; the desktop never feeds speaker echo back."""from jarvis.core.events import BrowserVoiceRequested+ from jarvis.live import startupchanged = asyncio.Event()watcher = (asyncio.get_running_loop(), changed)@@ -75,19 +88,26 @@ async def run_browser_call(bus: Any, hangup: asyncio.Event, *, timeout_s: floatawait asyncio.gather(*tasks, return_exceptions=True)changed.clear()- await bus.publish(BrowserVoiceRequested(action="start"))- # UI permission and device setup can take time. No background billed connection.try:+ if hangup.is_set():+ return "hotkey"+ if input_buffer is not None and session_id:+ startup.offer(session_id, input_buffer)+ await bus.publish(BrowserVoiceRequested(action="start"))+ # UI permission and device setup can take time. No idle billed connection.async with asyncio.timeout(timeout_s):while not active() and not hangup.is_set():await wait_change()while active() and not hangup.is_set():await wait_change()except TimeoutError:+ # The caller receives an explicit error outcome for this bounded wait.return "error"finally:+ startup.discard(session_id)_watchers.discard(watcher)- if hangup.is_set():- await bus.publish(BrowserVoiceRequested(action="stop"))- await close_all()+ # Retract pending browser starts on timeout/cancellation too. Otherwise+ # focusing a hidden window later starts a call whose owner already left.+ await bus.publish(BrowserVoiceRequested(action="stop"))+ await close_all()return "hotkey" if hangup.is_set() else "client_stop"diff --git a/jarvis/live/session.py b/jarvis/live/session.pyindex 74c855f9a2..7c7a82480a 100644--- a/jarvis/live/session.py+++ b/jarvis/live/session.py@@ -68,6 +68,9 @@ class LiveVoiceSession:self._tools: LiveTools | None = Noneself._resampler = StreamingPcm16Resampler(48000, 24000)self._captions = {"user": "", "assistant": ""}+ from jarvis.live.transcript import LiveTranscript++ self._transcript = LiveTranscript()self._last_role = ""self._last_end = {"user": -1, "assistant": -1}self._delegation_responses: dict[str, str] = {}@@ -75,6 +78,13 @@ class LiveVoiceSession:self.playback_active = Falseself._speaking = Falseself._thinking = False+ self._indicator_phase = "idle"+ self._indicator_trace_id = uuid4()+ self._media_received = False+ self._mic_feedback_owned = False+ self._mic_feedback_warning = False+ self._input_active = False+ self._media_timeout: asyncio.TimerHandle | None = Noneself._active_model = ""self._archive_turn_id = str(uuid4())self._parent_owned = False@@ -120,9 +130,11 @@ class LiveVoiceSession:@propertydef phase(self) -> str:"""The surface indicator state: speaking, thinking or listening."""- if self._speaking or self.playback_active:+ if self.playback_active or (self._speaking and not self._media_received):return "speaking"- if self._thinking:+ if self._input_active:+ return "listening"+ if self._thinking or (self._media_received and self._speaking):return "thinking"return "listening"@@ -134,13 +146,38 @@ class LiveVoiceSession:"""if self._closing:return+ if self._media_received and message.get("type") in {+ "thinking", "speaking", "listening", "tts_start", "tts_end", "turn_complete",+ }:+ message = {"type": self.phase}+ await self._publish_phase()try:await self._send_json(message)except Exception: # noqa: BLE001 — indicators must not kill voicelog.debug("Live indicator frame could not be sent", exc_info=True)+ async def _publish_phase(self, phase: str | None = None) -> None:+ """Mirror the media state to native and remote surfaces on the same bus."""+ current = phase or self.phase+ if self._closing and current != "idle":+ return+ if current == self._indicator_phase:+ return+ previous, self._indicator_phase = self._indicator_phase, current+ if self._bus is not None:+ from jarvis.core.events import SystemStateChanged++ await self._bus.publish(+ SystemStateChanged(+ source_layer="live.session",+ trace_id=self._indicator_trace_id,+ new_state=current.upper(),+ previous=previous.upper(),+ )+ )+async def _note_thinking(self) -> None:- if self._thinking or self._speaking or self._closing:+ if self._thinking or self._closing:returnself._thinking = Trueawait self._emit_indicator({"type": "thinking"})@@ -160,7 +197,7 @@ class LiveVoiceSession:returnended_speech = self._speakingself._speaking = False- self._thinking = False+ self._thinking = self._has_pending_work()if ended_speech:await self._emit_indicator({"type": "tts_end"})await self._emit_indicator({"type": "turn_complete"})@@ -172,10 +209,112 @@ class LiveVoiceSession:# Playback is owned by the browser; it is not a model turn boundary.return None+ def _has_pending_work(self) -> bool:+ return bool(self._response_revisions) or any(not job.done() for job in self._jobs)++ async def _playback_changed(self, active: bool) -> None:+ first = active and not self.playback_active+ ended = self.playback_active and not active+ self.playback_active = active+ self._speaking = active+ if not active:+ self._thinking = self._has_pending_work()+ await self._emit_indicator({"type": self.phase})+ if ended and self._media_received:+ from jarvis.audio import level_tap++ level_tap.reset_playing()+ if first and self._bus is not None and not self._closing:+ from jarvis.core.events import AudioOutFirst++ # The native bar deliberately waits for audible output AFTER the+ # SPEAKING state. RTP bypasses AudioPlayer, so media owns this edge.+ await self._bus.publish(+ AudioOutFirst(source_layer="live.media", trace_id=self._indicator_trace_id)+ )++ def _clear_media_levels(self) -> None:+ if self._media_timeout is not None:+ self._media_timeout.cancel()+ self._media_timeout = None+ if self._media_received:+ from jarvis.audio import level_tap, mic_level++ level_tap.reset_playing()+ if self._mic_feedback_owned:+ mic_level.publish(0.0, owner=self.session_id)+ mic_level.release_external(self.session_id)+ self._mic_feedback_owned = False+ self._input_active = False+ self.playback_active = False+ self._speaking = False++ def _expire_media_levels(self) -> None:+ self._clear_media_levels()+ if not self._closing and not self._recovering:+ task = asyncio.create_task(+ self._emit_indicator({"type": self.phase}), name="live-media-expired"+ )+ self._control_tasks.add(task)+ task.add_done_callback(self._control_tasks.discard)++ async def _receive_media_levels(self, message: dict) -> None:+ from pydantic import ValidationError++ from jarvis.audio import level_tap, mic_level+ from jarvis.live.media import MediaLevels++ if not self.is_active:+ return+ try:+ levels = MediaLevels.model_validate(message)+ except ValidationError:+ log.debug("Ignoring invalid browser media measurements")+ return+ previous_phase = self.phase+ previous_playback = self.playback_active+ # A frontend rebuild can reach an already-running process whose eager+ # audio module predates the lazily imported Live session. Optional+ # meters must degrade instead of terminating a paid voice connection.+ microphone_ready = all(+ callable(getattr(mic_level, name, None))+ for name in ("claim_external", "release_external", "publish")+ )+ if microphone_ready:+ mic_level.claim_external(self.session_id)+ self._mic_feedback_owned = True+ elif not self._mic_feedback_warning:+ self._mic_feedback_warning = True+ log.warning("Browser microphone meter needs an app restart; voice remains connected")+ self._media_received = True+ self._input_active = levels.input_active+ if levels.playback_active != previous_playback:+ await self._playback_changed(levels.playback_active)+ elif self.phase != previous_phase or self._indicator_phase != self.phase:+ await self._emit_indicator({"type": self.phase})+ if self._closing:+ return+ if levels.playback_active:+ level_tap.publish(levels.output_level)+ level_tap.note_playing(0.3)+ elif previous_playback:+ level_tap.reset_playing()+ if microphone_ready:+ mic_level.publish(levels.input_level, owner=self.session_id)+ if self._media_timeout is not None:+ self._media_timeout.cancel()+ self._media_timeout = asyncio.get_running_loop().call_later(1.5, self._expire_media_levels)+async def handle_control(self, message: dict) -> None:if self._closing:returnkind = message.get("type")+ if kind == "media_levels":+ try:+ await self._receive_media_levels(message)+ except Exception: # noqa: BLE001 — optional UI feedback must not end speech+ log.warning("Browser media feedback failed; voice remains connected", exc_info=True)+ returnif kind == "reconnect_offer" and self._offer_future is not None:if message.get("request_id") == self._offer_request and not self._offer_future.done():from jarvis.realtime.offer_broker import validate_webrtc_offer_sdp@@ -183,7 +322,8 @@ class LiveVoiceSession:self._offer_future.set_result(validate_webrtc_offer_sdp(message.get("sdp")))returnif kind == "playback_state":- self.playback_active = bool(message.get("active", False))+ if type(message.get("active")) is bool:+ await self._playback_changed(message["active"])returnif kind == "audio_start" and self._connection is None:await self._start(message)@@ -226,6 +366,7 @@ class LiveVoiceSession:# GPT-Live hears interruptions in the continuous input stream.self._speaking = Falseself._thinking = False+ self.playback_active = Falseawait self._send_json({"type": "audio_clear"})await self._emit_indicator({"type": "tts_cancel"})@@ -254,6 +395,7 @@ class LiveVoiceSession:# opening them concurrently keeps the permit's quarter-second budget# off the wake path instead of stacked after a cold-disk sqlite open.self._ledger, _ = await asyncio.gather(_open_ledger(), _take_permit())+ assert self._ledger is not Nonesetup_ms = (time.monotonic() - started_at) * 1000.0self._tools = LiveTools(gateway,@@ -263,7 +405,9 @@ class LiveVoiceSession:backend_model=profile.backend_model,)prompt_language = getattr(self._config.brain, "reply_language", "auto")- config = profile.session_config(language=prompt_language, tools=self._tools.declarations())+ config = profile.session_config(+ language=prompt_language, tools=self._tools.declarations(defer_catalog=True)+ )self._base_session_config = configoffer = str(message.get("webrtc_offer_sdp", ""))self._using_webrtc = bool(offer)@@ -273,6 +417,7 @@ class LiveVoiceSession:from jarvis.live.runtime import claimclaim(self.session_id)+ await self._publish_phase("connecting")from jarvis.live.recovery import seed_messagesself._initial_seed = self._take_initial_context()@@ -335,6 +480,10 @@ class LiveVoiceSession:language=self._language,))+ await self._publish_phase()+ if self._closing:+ return+ await self._take_startup_input(message)await self._send_json({"type": "audio_ready",@@ -374,6 +523,14 @@ class LiveVoiceSession:self.session_id = str(parent_id)self._parent_owned = True+ async def _take_startup_input(self, message: dict) -> None:+ from jarvis.live.startup import take++ if self._parent_owned:+ prefix = await take(self.session_id, message.get("capture_started_at_ms"))+ if prefix is not None:+ await self._send_json(prefix)+async def handle_audio_frame(self, pcm: bytes) -> None:if (self._connection is None@@ -439,9 +596,14 @@ class LiveVoiceSession:)if not await asyncio.to_thread(self._ledger.append, fragment):return- if fragment.start_ms - self._last_end[role] > 1500:- self._captions[role] = ""- self._captions[role] = (self._captions[role] + delta)[-32000:]+ caption = self._transcript.feed(+ session_id=self.session_id, trace_id=self._indicator_trace_id,+ event_id=fragment.event_id, role=role, text=delta,+ start_ms=fragment.start_ms, end_ms=fragment.end_ms,+ )+ self._captions[role] = caption.text+ if self._bus is not None:+ await self._bus.publish(caption)current = fragment.end_ms >= self._last_end[role]self._last_end[role] = max(self._last_end[role], fragment.end_ms)if role == "user" and current:@@ -466,13 +628,10 @@ class LiveVoiceSession:if role == "assistant" and current:await self._note_thinking()elif kind == "session.output_audio.delta":- # The sideband carries this event on every transport, including- # WebRTC where the media itself travels over RTP. The binary- # forwarding below stays PCM-only, but the speaking signal must- # reach the surfaces on both paths — otherwise the Jarvis bar- # never leaves listening while GPT-Live talks.- await self._note_speaking()+ # With WebRTC, only measured RTP playback owns the speaking+ # state. Sideband generation can lead playback or include silence.if not self._connection.answer_sdp:+ await self._note_speaking()await self._send_binary(base64.b64decode(event["delta"]))elif kind in {"session.usage.updated", "session.closed"}:self._wire_seconds = max(@@ -534,9 +693,40 @@ class LiveVoiceSession:self._response_revisions[self._response_id] = self._tools.revisionself._delegation_responses[delegation] = self._response_idself._responses.setdefault(self._response_id, [])+ if self._bus is not None:+ from jarvis.core.events import BrainTurnStarted++ await self._bus.publish(BrainTurnStarted(+ source_layer="live.delegation", trace_id=self._indicator_trace_id,+ provider=self.active_provider, model=self._tools.backend_model,+ ))await self._note_thinking()+ elif kind == "response.reasoning_summary_text.done":+ if self._bus is not None and event.get("text"):+ from jarvis.core.events import ReasoningSummaryUpdated+ from jarvis.core.redact import safe_preview++ await self._bus.publish(ReasoningSummaryUpdated(+ source_layer="live.delegation", trace_id=self._indicator_trace_id,+ response_id=str(event.get("item_id") or event.get("response_id") or delegation),+ text=safe_preview(event["text"], max_chars=4000), done=True,+ ))elif kind == "response.output_item.done":item = event.get("item", {})+ if item.get("type") == "reasoning":+ summary = "\n\n".join(+ str(part.get("text", "")) for part in item.get("summary", [])+ if part.get("type") == "summary_text"+ )+ if summary and self._bus is not None:+ from jarvis.core.events import ReasoningSummaryUpdated+ from jarvis.core.redact import safe_preview++ await self._bus.publish(ReasoningSummaryUpdated(+ source_layer="live.delegation", trace_id=self._indicator_trace_id,+ response_id=str(item.get("id") or delegation),+ text=safe_preview(summary, max_chars=4000), done=True,+ ))if item.get("type") == "function_call":rid = str(event.get("response_id")@@ -551,15 +741,26 @@ class LiveVoiceSession:if rid in self._completed:returnself._completed.add(rid)- await self._note_turn_end()+ calls = self._responses.pop(rid, [])+ revision = self._response_revisions.pop(rid, self._tools.revision)+ # A backend response completing is not a speech boundary. Its+ # tool calls still need running and RTP can still be playing.+ self._thinking = bool(+ (kind == "response.completed" and calls) or self._has_pending_work()+ )+ if self._thinking or self.playback_active:+ self._speaking = self.playback_active+ await self._emit_indicator({"type": self.phase})+ else:+ await self._note_turn_end()usage = response.get("usage") or {}backend_model = self._tools.backend_modelawait asyncio.to_thread(self._ledger.backend_usage, self.session_id, rid, backend_model, usage)if self._bus is not None:- from jarvis.brain.cost import calculate_cost_usdfrom jarvis.core.events import BrainTurnCompleted+ from jarvis.live.cost import backend_cost_usdcached = int((usage.get("input_tokens_details") or {}).get("cached_tokens", 0))tokens_in = max(0, int(usage.get("input_tokens", 0)) - cached)@@ -571,7 +772,7 @@ class LiveVoiceSession:tokens_in=tokens_in,tokens_out=tokens_out,tokens_cached=cached,- cost_usd=calculate_cost_usd(backend_model, tokens_in, tokens_out, cached),+ cost_usd=backend_cost_usd(backend_model, usage),finish_reason="live_delegation",))@@ -582,8 +783,6 @@ class LiveVoiceSession:"usage": response.get("usage", {}),})- calls = self._responses.pop(rid, [])- revision = self._response_revisions.pop(rid, self._tools.revision)if calls and kind == "response.completed" and not self._closing:task = asyncio.create_task(self._run_calls(calls, revision), name="live-tools")self._jobs.add(task)@@ -612,7 +811,9 @@ class LiveVoiceSession:"item": {"type": "function_call_output","call_id": item["call_id"],- "output": json.dumps(result, default=str),+ "output": json.dumps(+ result, ensure_ascii=False, separators=(",", ":"), default=str+ ),},})@@ -740,10 +941,12 @@ class LiveVoiceSession:if self._ended:returnself._ended = True+ self._clear_media_levels()from jarvis.live.runtime import unregisterunregister(self.session_id)self._closing = True+ await self._publish_phase("idle")self._hangup_reason = reasonif self._connection is not None:try:diff --git a/jarvis/live/startup.py b/jarvis/live/startup.pynew file mode 100644index 0000000000..c04ad1756c--- /dev/null+++ b/jarvis/live/startup.py@@ -0,0 +1,79 @@+"""One-use, memory-only handoff from the wake microphone to browser capture."""++from __future__ import annotations++import asyncio+import base64+import math+import threading+import time+from typing import Any++from jarvis.live.media import InputPrefix++_lock = threading.Lock()+_pending: dict[str, tuple[asyncio.AbstractEventLoop, Any]] = {}+++def offer(session_id: str, source: Any) -> None:+ """Keep the existing wake capture alive until the browser actually captures."""+ with _lock:+ _pending[session_id] = (asyncio.get_running_loop(), source)+++def discard(session_id: str) -> None:+ with _lock:+ _pending.pop(session_id, None)+++async def take(session_id: str, capture_started_at_ms: Any) -> dict | None:+ """Trim at the browser's first sample, close native capture, and consume once.++ Both clocks are wall clocks on the same desktop. Only the owning desktop+ session can have a source here; a headless/browser-only call has none.+ AudioChunk timestamps mark the END of their frame. Trimming overlapping+ samples prevents the user's opening words from being sent twice.+ """+ with _lock:+ entry = _pending.pop(session_id, None)+ if entry is None:+ return None+ loop, source = entry++ async def collect() -> dict | None:+ await source.close()+ # Old clients cannot consume a prefix. Release their native lease too.+ if capture_started_at_ms is None:+ return None+ if (+ isinstance(capture_started_at_ms, bool)+ or not isinstance(capture_started_at_ms, (int, float))+ or not math.isfinite(capture_started_at_ms)+ or abs(time.time() * 1000 - capture_started_at_ms) > 60_000+ ):+ raise ValueError("Invalid browser capture timestamp")+ cutoff_ns = round(capture_started_at_ms * 1_000_000)+ audio = bytearray()+ rate = 0+ async for chunk in source.stream():+ if chunk.channels != 1 or chunk.sample_rate <= 0 or len(chunk.pcm) % 2:+ raise ValueError("Invalid wake microphone format")+ if rate and rate != chunk.sample_rate:+ raise ValueError("Wake microphone format changed during startup")+ rate = chunk.sample_rate+ samples = len(chunk.pcm) // 2+ end_ns = chunk.timestamp_ns+ start_ns = end_ns - samples * 1_000_000_000 // rate+ keep = max(0, min(samples, (cutoff_ns - start_ns) * rate // 1_000_000_000))+ audio.extend(chunk.pcm[: keep * 2])+ if len(audio) > rate * 2 * 30:+ raise ValueError("Wake microphone exceeded the startup buffer")+ if not audio:+ return None+ return InputPrefix(+ sample_rate=rate, audio=base64.b64encode(audio).decode("ascii")+ ).model_dump()++ if asyncio.get_running_loop() is loop:+ return await collect()+ return await asyncio.wrap_future(asyncio.run_coroutine_threadsafe(collect(), loop))diff --git a/jarvis/live/tools.py b/jarvis/live/tools.pyindex 61320ff727..6f703e5a30 100644--- a/jarvis/live/tools.py+++ b/jarvis/live/tools.py@@ -17,6 +17,15 @@ from jarvis.safety.tool_executor import VOICE_CONFIRM_SENTINELlog = logging.getLogger(__name__)+# A session.started event includes its declarations. Keep room for prompts and+# history inside the 64 KiB message limit of smaller WebRTC clients.+_CATALOG_BYTE_BUDGET = 24_000+_DISCOVERY_PAGE_SIZE = 8+++def _wire_size(value: Any) -> int:+ return len(json.dumps(value).encode("utf-8"))+def take_images(result: dict) -> list[dict]:"""Separate actual image inputs from text function outputs and stored receipts."""@@ -71,6 +80,7 @@ class LiveTools:self._lock = asyncio.Lock()self._pending: dict[str, tuple[UUID, str, dict, int]] = {}self._names: dict[str, str] = {}+ self._defer_catalog = Falseself.end_requested = Falseself.accepting = True@@ -78,7 +88,20 @@ class LiveTools:read = getattr(self.gateway, "voice_catalog", self.gateway.catalog)return read()- def declarations(self) -> list[dict]:+ def accept_new_input(self) -> None:+ """New requests get a fresh token; running work keeps its cancelled token."""+ if self.cancel_token.is_cancelled():+ self.cancel_token = CancelToken()+ self.accepting = True++ async def cancel_work(self) -> None:+ self.cancel_token.cancel("user_cancelled")+ self.accepting = False+ self.revision += 1+ await self._cancel_confirmations()++ def declarations(self, *, defer_catalog: bool = False) -> list[dict]:+ self._defer_catalog = defer_catalogdefinitions = [function("end_call",@@ -88,8 +111,9 @@ class LiveTools:),function("discover_tools",- "Find Jarvis tools and their complete input schemas. Empty query lists all tools.",- {"query": {"type": "string"}},+ "Find Jarvis tools and their complete input schemas. Empty query browses all "+ "tools. Pass next_offset as offset to read the next page.",+ {"query": {"type": "string"}, "offset": {"type": "integer", "minimum": 0}},["query"],),function(@@ -105,18 +129,36 @@ class LiveTools:["approval_id"],),]- # Stable ordering helps cache reuse. Discovery keeps the rest reachable.- for descriptor in sorted(self.catalog(), key=lambda d: d.name)[:48]:+ if defer_catalog:+ definitions[1]["description"] = (+ "Find tools by intent using a few English keywords, or an exact canonical name. "+ "Returns relevant complete input schemas. Reuse schemas already read; do not "+ "inventory unrelated tools. Empty query browses all tools. Pass next_offset as "+ "offset with the same query to read another page only if needed."+ )+ # A names-only index lets the same model choose an exact capability+ # without asking lexical search to infer the user's intent.+ definitions[1]["description"] += " Available tool names: " + ", ".join(+ sorted(descriptor.name for descriptor in self.catalog())+ )+ definitions[1]["parameters"]["properties"]["offset"] = {"type": "integer", "minimum": 0}+ return definitions+ # Count alone is insufficient: an imported tool may carry a large schema.+ used_bytes = _wire_size(definitions)+ for descriptor in sorted(self.catalog(), key=lambda d: d.name):alias = "jarvis_" + hashlib.sha256(descriptor.name.encode()).hexdigest()[:20]+ definition = {+ "type": "function",+ "name": alias,+ "description": f"{descriptor.name}: {descriptor.description}",+ "parameters": descriptor.input_schema,+ }+ size = _wire_size(definition) + 2+ if len(definitions) >= 52 or used_bytes + size > _CATALOG_BYTE_BUDGET:+ continue+ used_bytes += sizeself._names[alias] = descriptor.name- definitions.append(- {- "type": "function",- "name": alias,- "description": f"{descriptor.name}: {descriptor.description}",- "parameters": descriptor.input_schema,- }- )+ definitions.append(definition)return definitionsasync def execute(self, call_id: str, name: str, args: dict, revision: int) -> dict:@@ -159,6 +201,15 @@ class LiveTools:return resultasync def _execute(self, name: str, args: dict, revision: int) -> dict:+ operation_token = self.cancel_token+ if operation_token.is_cancelled():+ return {"success": False, "status": "cancelled"}+ if revision != self.revision:+ return {+ "success": False,+ "status": "superseded",+ "error": "The request changed before execution. Re-evaluate the latest user input.",+ }if ":" in name:prefix, suffix = name.split(":", 1)if prefix.isidentifier() and (@@ -175,16 +226,35 @@ class LiveTools:if name == "end_call":self.end_requested = Truereturn {"success": True, "status": "closing_voice"}- if self.cancel_token.is_cancelled():- return {"success": False, "status": "cancelled"}if name == "discover_tools":+ if self._defer_catalog:+ from jarvis.live.discovery import discover++ return discover(+ self.catalog(), str(args.get("query", "")), int(args.get("offset", 0))+ )query = str(args.get("query", "")).casefold().split()+ matches = [+ d+ for d in sorted(self.catalog(), key=lambda d: d.name)+ if all(word in (d.name + " " + d.description).casefold() for word in query)+ ]+ offset = max(0, int(args.get("offset", 0)))+ page: list[dict] = []+ for descriptor in matches[offset : offset + _DISCOVERY_PAGE_SIZE]:+ item = {+ "name": descriptor.name,+ "description": descriptor.description,+ "parameters": descriptor.input_schema,+ }+ if page and _wire_size([*page, item]) > _CATALOG_BYTE_BUDGET:+ break+ page.append(item)+ next_offset = offset + len(page)return {- "tools": [- {"name": d.name, "description": d.description, "parameters": d.input_schema}- for d in self.catalog()- if all(word in (d.name + " " + d.description).casefold() for word in query)- ]+ "tools": page,+ "total": len(matches),+ "next_offset": next_offset if next_offset < len(matches) else None,}if name == "confirm_action":from jarvis.voice.echo_confirmation import classify_response@@ -238,12 +308,6 @@ class LiveTools:import jsonschema # type: ignore[import-untyped]jsonschema.validate(args, descriptor.input_schema)- if revision != self.revision:- return {- "success": False,- "status": "superseded",- "error": "The request changed before execution. Re-evaluate the latest user input.",- }trace = uuid4()from jarvis.core.model_selection import ModelSelection, use_operation_model@@ -264,6 +328,9 @@ class LiveTools:}result = await self.gateway.execute(canonical, args, self._request(trace))if result.error == VOICE_CONFIRM_SENTINEL:+ if operation_token.is_cancelled() or revision != self.revision:+ await self.gateway.cancel_pending(trace)+ return {"success": False, "status": "superseded"}if not self.accepting:await self.gateway.cancel_pending(trace)return {"success": False, "status": "voice_closed_before_confirmation"}@@ -314,6 +381,10 @@ class LiveTools:async def close(self) -> None:self.accepting = False- for trace, _, _, _ in self._pending.values():- await self.gateway.cancel_pending(trace)+ await self._cancel_confirmations()++ async def _cancel_confirmations(self) -> None:+ pending = tuple(self._pending.values())self._pending.clear()+ for trace, _, _, _ in pending:+ await self.gateway.cancel_pending(trace)diff --git a/jarvis/live/transcript.py b/jarvis/live/transcript.pynew file mode 100644index 0000000000..7808c3da91--- /dev/null+++ b/jarvis/live/transcript.py@@ -0,0 +1,124 @@+"""Continuous caption projection; display boundaries never control model turns."""++import logging+import sqlite3+import time+from contextlib import closing+from dataclasses import replace+from pathlib import Path+from typing import Literal+from uuid import UUID++from jarvis.core.events import VoiceTranscriptUpdated+from jarvis.core.redact import redact_secrets+++class LiveTranscript:+ """Retain each speaker's segment independently, including overlapping speech."""++ def __init__(self) -> None:+ self._current: dict[str, VoiceTranscriptUpdated] = {}+ self._recent: dict[str, list[VoiceTranscriptUpdated]] = {"user": [], "assistant": []}+ self._finished: set[str] = set()++ def finish(self, role: str) -> None:+ self._finished.add(role)++ def feed(+ self,+ *,+ session_id: str,+ trace_id: UUID,+ event_id: str,+ role: Literal["user", "assistant"],+ text: str,+ start_ms: int,+ end_ms: int,+ snapshot: bool = False,+ ) -> VoiceTranscriptUpdated:+ old = self._current.get(role)+ late = old is not None and start_ms < old.start_ms+ if late:+ old = next(+ (+ item+ for item in reversed(self._recent[role])+ if item.start_ms <= start_ms <= item.end_ms + 1500+ ),+ None,+ )+ other = self._current.get("assistant" if role == "user" else "user")+ crossed = old is not None and other is not None and old.end_ms <= other.start_ms <= start_ms+ new = (+ old is None+ or (not late and role in self._finished)+ or crossed+ or start_ms - old.end_ms > 1500+ or (not snapshot and len(old.text) + len(text) > 32000)+ )+ if not late:+ self._finished.discard(role)+ if new:+ result = VoiceTranscriptUpdated(+ session_id=session_id,+ segment_id=event_id,+ role=role,+ text=redact_secrets(text),+ start_ms=start_ms,+ end_ms=end_ms,+ trace_id=trace_id,+ source_layer="live.transcript",+ )+ else:+ assert old is not None+ result = replace(+ old,+ text=redact_secrets(text if snapshot else old.text + text),+ end_ms=max(old.end_ms, end_ms),+ revision=old.revision + 1,+ timestamp_ns=time.time_ns(),+ )+ recent = self._recent[role]+ if old is not None and not new:+ recent[recent.index(old)] = result+ else:+ recent.append(result)+ del recent[:-64]+ if not late:+ self._current[role] = result+ return result+++def read_legacy_transcript(path: Path, session_id: str) -> list[VoiceTranscriptUpdated]:+ """Recover pre-fix conversations from existing fragments without rewriting data."""+ if not path.is_file():+ return []+ try:+ with closing(sqlite3.connect(path.resolve().as_uri() + "?mode=ro", uri=True)) as db:+ rows = db.execute(+ "SELECT event_id,role,delta,start_ms,end_ms FROM live_transcripts "+ "WHERE session_id=? ORDER BY start_ms,rowid",+ (session_id,),+ ).fetchall()+ except sqlite3.Error:+ logging.getLogger(__name__).debug("Legacy Live captions unavailable", exc_info=True)+ return []+ projector = LiveTranscript()+ segments = {}+ from uuid import uuid4++ trace = uuid4()+ for event_id, role, text, start, end in rows:+ if role not in {"user", "assistant"}:+ continue+ caption = projector.feed(+ session_id=session_id,+ trace_id=trace,+ event_id=event_id,+ role=role,+ text=text,+ start_ms=start,+ end_ms=end,+ )+ segments[caption.segment_id] = caption+ return sorted(segments.values(), key=lambda item: item.start_ms)diff --git a/jarvis/plugins/brain/_openai_base.py b/jarvis/plugins/brain/_openai_base.pyindex 08d943ab69..761d472956 100644--- a/jarvis/plugins/brain/_openai_base.py+++ b/jarvis/plugins/brain/_openai_base.py@@ -55,6 +55,29 @@ if not _STREAM_OPTIONS_SUPPORTED:)+def _tool_output_text(message: BrainMessage) -> str:+ """Translate one internal result envelope without billing it as nested JSON.++ The call ID already has its own wire field. Unwrap only the exact envelope+ emitted by ToolUseLoop; preserve unfamiliar blocks and metadata in full.+ Strings are opaque tool evidence, including whitespace and repetitions.+ """+ content = message.content+ if isinstance(content, list) and len(content) == 1:+ block = content[0]+ if (+ isinstance(block, dict)+ and set(block) == {"type", "tool_use_id", "content"}+ and block["type"] == "tool_result"+ and message.tool_call_id+ and block["tool_use_id"] == message.tool_call_id+ ):+ content = block["content"]+ if isinstance(content, str):+ return content+ return json.dumps(content, ensure_ascii=False, separators=(",", ":"), default=str)++def _to_openai_messages(messages: tuple[BrainMessage, ...],system_extra: str | None,@@ -89,11 +112,7 @@ def _to_openai_messages(if m.role == "tool":out.append({"role": "tool",- "content": (- m.content- if isinstance(m.content, str)- else json.dumps(m.content, default=str)- ),+ "content": _tool_output_text(m),"tool_call_id": m.tool_call_id or "",})continue@@ -117,7 +136,9 @@ def _to_openai_messages(original_name,original_name,),- "arguments": json.dumps(block.get("input", {}), ensure_ascii=False),+ "arguments": json.dumps(+ block.get("input", {}), ensure_ascii=False, separators=(",", ":")+ ),},})if tool_calls and assistant_tool_call_extra_content:diff --git a/jarvis/plugins/tool/app_command.py b/jarvis/plugins/tool/app_command.pyindex 8d2a2c729b..1e9a0e2085 100644--- a/jarvis/plugins/tool/app_command.py+++ b/jarvis/plugins/tool/app_command.py@@ -319,6 +319,13 @@ class RegistryCommandTool:key = self._runtime.control_key()if key:headers["Authorization"] = f"Bearer {key}"+ from jarvis.society.inherit import caller_session_id++ session_id = caller_session_id()+ if session_id:+ from jarvis.agent_chat.jarvis_harness import HEADER_NAME++ headers[HEADER_NAME] = session_idtry:async with httpx.AsyncClient(# The request stays in-process through ASGITransport. Use adiff --git a/jarvis/plugins/tool/create_artifact.py b/jarvis/plugins/tool/create_artifact.pyindex 52102e0ef0..3964498fdf 100644--- a/jarvis/plugins/tool/create_artifact.py+++ b/jarvis/plugins/tool/create_artifact.py@@ -104,18 +104,20 @@ class CreateArtifactTool:name: str = "create_artifact"risk_tier: str = "monitor"description: str = (- "Build an ARTIFACT: one self-contained HTML page the user can look at — "- "a dashboard, report, infographic, diagram, comparison, timeline, chart, "- "landing page or small interactive tool. A strong background agent "- "writes the page; it appears in the Artifacts section when done (about "- "a minute). Use this when the user explicitly asks to SEE something as "- "a page, picture, diagram or artifact ('visualisier mir das', 'mach mir "- "ein Dashboard draus', 'build me an artifact', 'show me that as a "- "timeline'). Never call it to decorate an ordinary answer. To change "- "an existing artifact ('make the bars red'), pass 'revise' with its "- "title (or 'latest'). This does NOT open the Artifacts section — that "- "is 'navigate'. Prefer this over spawn_worker whenever the deliverable "- "is a page to look at."+ "Build an ARTIFACT: one self-contained HTML page the user can look at "+ "and keep — a dashboard, report, infographic, diagram, comparison, "+ "timeline, chart, landing page or small interactive tool. A strong "+ "background agent writes the page; it appears in the Artifacts "+ "section when done (about a minute). Use this ONLY when the user "+ "literally says the word artifact ('mach mir ein Artefakt draus', "+ "'build me an artifact', 'hazme un artefacto') or pinned this "+ "capability via the Add menu. Never call it for 'visualisier', "+ "'Dashboard', 'Diagramm', 'Seite' or 'Bericht' alone, and never to "+ "decorate an ordinary answer. To change an existing artifact, the "+ "user names the artifact again and you pass 'revise' with its title "+ "(or 'latest'). This does NOT open the Artifacts section — that "+ "is 'navigate'. Prefer this over spawn_worker whenever the "+ "deliverable is a page to look at.")schema: dict[str, Any] = {"type": "object",diff --git a/jarvis/plugins/tool/delegate_to_agent.py b/jarvis/plugins/tool/delegate_to_agent.pyindex bf2977f256..42073537ac 100644--- a/jarvis/plugins/tool/delegate_to_agent.py+++ b/jarvis/plugins/tool/delegate_to_agent.py@@ -24,6 +24,7 @@ from collections.abc import Callablefrom typing import Any, Finalfrom jarvis.core.protocols import ExecutionContext, ToolResult+from jarvis.society.communication import REPLY_POLICY_SCHEMA, select_reply_policylog = logging.getLogger(__name__)@@ -34,6 +35,16 @@ _ACK: Final[dict[str, str]] = {"en": "{name} is on it, I will let you know.","es": "{name} se encarga, te aviso.",}+_QUIET_ACK: Final[dict[str, str]] = {+ "de": "{name} ist dran.", # i18n-allow: spoken ack+ "en": "{name} is on it.",+ "es": "{name} se encarga.",+}+_ERROR_ACK: Final[dict[str, str]] = {+ "de": "{name} ist dran; ich melde mich bei Hindernissen.", # i18n-allow: spoken ack+ "en": "{name} is on it; I will report any blockers.",+ "es": "{name} se encarga; te avisare si hay impedimentos.",+}_QUEUED: Final[dict[str, str]] = {"de": "Aufgabe für {name} erfasst; Start noch nicht bestätigt.", # i18n-allow: spoken ack"en": "The task for {name} is recorded; its start is not confirmed yet.",@@ -121,10 +132,14 @@ class DelegateToAgentTool:"team card): 'let Scout research X', 'Mailbox, answer the invoice mail', 'give that ""to the team'. Use when a background task fits the persistent team; leave `agent` ""empty to let the lead pick the agent whose hands fit the task. The agent works in "- "the background; you acknowledge now and its result is announced when it lands. "+ "the background; you acknowledge now and its result follows reply_policy. ""Never for inventory/status questions or tasks the user wants done right here. "- "Include relevant conversation context and completion criteria so the agent "- "can act independently. Report the acknowledgement and state exactly. Keep the "+ "Turn the user's intent into an actionable brief: objective, known target, relevant "+ "context, scope, constraints and completion evidence. Do not merely paraphrase or "+ "invent facts. Include context and completion_criteria so the agent can act independently. "+ "Select reply_policy=always for requested findings, on_error for work without a "+ "requested success report, none only for explicit silence. Report the acknowledgement "+ "and state exactly. Keep the ""returned assignment_id and trace_id for society_status; never speak those ids.")schema: dict[str, Any] = {@@ -137,7 +152,14 @@ class DelegateToAgentTool:"name one (the best-fitting agent is picked from the task)."),},- "task": {"type": "string", "description": "The task, in full, in the user's words."},+ "task": {+ "type": "string",+ "description": (+ "An actionable objective and scope faithful to the user's intent, "+ "not just a paraphrase."+ ),+ },+ "reply_policy": REPLY_POLICY_SCHEMA,"context": {"type": "string","description": "Relevant prior decisions, constraints and facts; omit secrets.",@@ -181,6 +203,10 @@ class DelegateToAgentTool:return ToolResult(success=False, output=_NO_FIT[lang], error="no_agent_fits")from jarvis.society.events import MsgType+ try:+ policy = select_reply_policy(args.get("reply_policy"), MsgType.ASSIGN)+ except (TypeError, ValueError) as exc:+ return ToolResult(success=False, output=None, error=str(exc))context = str(args.get("context") or "").strip()criteria = str(args.get("completion_criteria") or "").strip()brief = task@@ -199,7 +225,7 @@ class DelegateToAgentTool:text=brief,trace_id=f"voice:{ctx.trace_id.hex[:12]}",msg_type=MsgType.ASSIGN,- payload={"text": brief, "lang": lang, "refs": refs},+ payload={"text": brief, "lang": lang, "refs": refs, "reply_policy": policy},)# The scheduler answered synchronously on the same trace: a CLAIM# means the agent took it, a VETO says why not — say so, no waiting.@@ -216,6 +242,7 @@ class DelegateToAgentTool:"agent_name": target.name,"assignment_id": env.event_id,"trace_id": env.trace_id,+ "reply_policy": policy,}if outcome is not None and outcome.msg_type is MsgType.VETO:reason = str(outcome.payload.get("text") or outcome.payload.get("reason") or "")@@ -228,12 +255,13 @@ class DelegateToAgentTool:},error=str(outcome.payload.get("reason") or "vetoed"),)+ ack = _ACK if policy == "always" else _ERROR_ACK if policy == "on_error" else _QUIET_ACKreturn ToolResult(success=True,output={**tracking,"state": "running" if outcome is not None else "recorded",- "acknowledgement": (_ACK if outcome is not None else _QUEUED)[lang].format(+ "acknowledgement": (ack if outcome is not None else _QUEUED)[lang].format(name=target.name,),},diff --git a/jarvis/plugins/tool/message_agent.py b/jarvis/plugins/tool/message_agent.pyindex 66bc81c5da..15f34db1b9 100644--- a/jarvis/plugins/tool/message_agent.py+++ b/jarvis/plugins/tool/message_agent.py@@ -21,7 +21,10 @@ class LeadMessageAgentTool:"Send an INTERNAL chat message to one of the user's Jarvis agents by name or id. ""Use for 'send the Gmail agent a test message': this does NOT send email. ""No extra confirmation is needed for internal messages. For assigning work use "- "delegate_to_agent. Report queued, delivered or failed exactly as returned."+ "delegate_to_agent, including 'tell X to test Y'. For 'ask X about Y', use kind "+ "'query' and reply_policy='always'. Include relevant context and the precise "+ "question; use kind 'say' and reply_policy='none' for information. "+ "Report queued, delivered or failed exactly as returned; delivery is not completion.")def __init__(self, *, runtime_resolver: RuntimeResolver) -> None:diff --git a/jarvis/pointer/intent.py b/jarvis/pointer/intent.pyindex 68cd7825be..88ff6c735b 100644--- a/jarvis/pointer/intent.py+++ b/jarvis/pointer/intent.py@@ -60,11 +60,24 @@ DEFAULT_STRONG_PHRASES: tuple[str, ...] = (# Vision/read verbs + a LOCATIVE anchor (hier/da/dort/here/there). The# demonstratives das/this/that are intentionally NOT anchors — a verb + bare# demonstrative ("zeig mir das wetter") is a normal object, not deictic.+# Active writing verbs need an observational question (below), not a composition+# command. A locative cannot come from an unrelated sentence or instruction.+# Direct line wraps ("written\nhere") and short embedded questions+# ("see,\nwhat is here") still describe one visual reference.+_VISUAL_LOCATION_TAIL = (+ r"(?:[^.!?;\r\n]*?|\s*(?:,\s*)?(?:(?:was|what(?:\s+(?:is|was))?)\s+)?)"+ r"\b(?:hier|da|dort|drueben|drüben|here|there)\b"+)_VISION_VERB_RE = re.compile(r"\b(?:siehst|sehe|seh|sehen|siehe|liest|lies|lese|lesen|vorlesen|vorliest|"r"steht|stehen|stehst|zeigst|zeig|zeige|"- r"read|reads|reading|see|sees|write|writes|written|wrote)\b"- r".*?\b(?:hier|da|dort|drueben|drüben|here|there)\b"+ r"read|reads|reading|see|sees|written)\b"+ + _VISUAL_LOCATION_TAIL+)+_WRITING_QUESTION_RE = re.compile(+ r"\b(?:what\s+(?:did|do|does)\s+(?:i|you|we|they|he|she)|who)"+ r"\s+(?:write|writes|wrote)\b"+ + _VISUAL_LOCATION_TAIL)# Bare deictic command ("lies das" / "show me that") — fires only when NOT@@ -102,11 +115,13 @@ class PointingGate:def matches(self, text: str) -> bool:if not text or not text.strip():return False- t = _WS_RE.sub(" ", text.strip().lower())+ lowered = text.strip().lower()+ t = _WS_RE.sub(" ", lowered)# Locative deictic signals win over everything (incl. the für-ein veto).if self._strong_re.search(t):return True- if _VISION_VERB_RE.search(t):+ # Do not fold line boundaries into spaces for the weak locative match.+ if _VISION_VERB_RE.search(lowered) or _WRITING_QUESTION_RE.search(lowered):return True# "das für ein <noun>" → category question, not deictic.if _VETO_RE.search(t):diff --git a/jarvis/realtime/offer_broker.py b/jarvis/realtime/offer_broker.pyindex 3ffa3b6692..2ba5cd56c8 100644--- a/jarvis/realtime/offer_broker.py+++ b/jarvis/realtime/offer_broker.py@@ -29,15 +29,16 @@ _DEFAULT_MAX_OFFERS_PER_OWNER = 2def validate_webrtc_offer_sdp(offer_sdp: object) -> str:- """Validate one browser WebRTC offer at every ingress boundary."""+ """Validate an offer without changing SDP line endings or media attributes."""if not isinstance(offer_sdp, str):raise ValueError("WebRTC offer SDP must be text")normalized = offer_sdp.strip()- if not normalized or len(normalized) > _MAX_SDP_CHARS:+ if not normalized or len(offer_sdp) > _MAX_SDP_CHARS:raise ValueError("WebRTC offer SDP is empty or too large")if not normalized.startswith("v=0"):raise ValueError("WebRTC offer SDP must be generated by RTCPeerConnection")- return normalized+ # SDP is a wire format. Removing the final CRLF makes Live reject the offer.+ return offer_sdp@dataclass(frozen=True, slots=True)@@ -216,8 +217,8 @@ class RealtimeTransportOfferBroker:return Noneasync def answer(self, offer_id: str, answer_sdp: str) -> bool:- normalized_sdp = str(answer_sdp or "").strip()- if not normalized_sdp or len(normalized_sdp) > _MAX_SDP_CHARS:+ normalized_sdp = str(answer_sdp or "")+ if not normalized_sdp.strip() or len(normalized_sdp) > _MAX_SDP_CHARS:raise ValueError("WebRTC answer SDP is empty or too large")async with self._lock:entry = self._entries.get(str(offer_id))diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.pyindex a80b733a45..34921cf764 100644--- a/jarvis/realtime/session.py+++ b/jarvis/realtime/session.py@@ -3164,7 +3164,12 @@ class RealtimeVoiceSession:"ask jarvis_action to use message_agent if it is not directly available. ""This is an internal chat message, not an email: never use gmail or ""another external messaging connector for it. Internal messages need "- "no extra confirmation. Use delegate_to_agent only for assigning work. "+ "no extra confirmation. Use delegate_to_agent for assigning work, including "+ "'tell X to test Y'; compose an actionable brief with known context, scope "+ "and completion evidence. For 'ask X about Y', send a query requiring an answer. "+ "Choose reply_policy: always for requested findings, on_error for blockers only, "+ "none for information or explicit silence. Do not merely paraphrase the user "+ "or invent missing facts. Delivery does not mean completion. ""Those are the user's OWN AGENTS from the Agents section (each with ""its own chat, tools and instructions) — not people you know, not ""coding terminals, and not the retired sub-agent system. When the "diff --git a/jarvis/sessions/recorder.py b/jarvis/sessions/recorder.pyindex 8385c34dbd..a1c5ccfb27 100644--- a/jarvis/sessions/recorder.py+++ b/jarvis/sessions/recorder.py@@ -84,6 +84,8 @@ _RAW_EVENT_KINDS: frozenset[str] = frozenset("ListeningStarted","TranscriptFinal","TranscriptionUpdate",+ "VoiceTranscriptUpdated",+ "ReasoningSummaryUpdated","BrainTurnStarted","BrainTurnCompleted","BrainTTFT",@@ -1004,6 +1006,8 @@ class SessionRecorder:def _maybe_append_raw(self, event: Event, kind: str) -> None:if self._state is None:return+ if kind == "VoiceTranscriptUpdated" and getattr(event, "session_id", "") != self._state.session_id:+ returnif kind not in _RAW_EVENT_KINDS:returnturn_id = (@@ -1188,6 +1192,13 @@ def _payload_for(event: Event) -> dict[str, Any]:"new_state","previous","session_id",+ "segment_id",+ "role",+ "start_ms",+ "end_ms",+ "revision",+ "response_id",+ "done","turn_id","turn_index","surface",diff --git a/jarvis/society/agent_tools.py b/jarvis/society/agent_tools.pyindex bfff42522e..ba3aa56d58 100644--- a/jarvis/society/agent_tools.py+++ b/jarvis/society/agent_tools.py@@ -27,6 +27,7 @@ from typing import Any, Finalfrom jarvis.core.protocols import ToolResult+from .communication import REPLY_POLICY_SCHEMA, reply_policy, select_reply_policyfrom .delivery import incoming_contextfrom .events import MsgTypefrom .failure_reasons import FailureReason, retry_action@@ -83,7 +84,10 @@ class MessageAgentTool:"you need an answer, 'propose' to suggest a plan, 'answer' when replying to a ""query, else 'say'. The teammate reads it in their own chat and may reply ""later; this call returns at once. It never assigns work — ask Jarvis or an "- "orchestrator to assign."+ "orchestrator to assign. Include the objective, relevant known context, scope "+ "and expected evidence, not just a paraphrase. Select reply_policy from the "+ "intent: none for information, on_error for blockers only, always for findings. "+ "An answer ends the exchange; never send courtesy acknowledgements.")schema: dict[str, Any] = {"type": "object",@@ -92,7 +96,25 @@ class MessageAgentTool:"type": "string","description": "The teammate's name or id, exactly as listed under Teammates.",},- "text": {"type": "string", "description": "Your message, in your own words."},+ "text": {+ "type": "string",+ "description": (+ "Self-contained question or brief with known context and expected output."+ ),+ },+ "reply_policy": REPLY_POLICY_SCHEMA,+ "reply_status": {+ "type": "string",+ "enum": ["done", "blocked"],+ "description": "For answers: done (default) or blocked with the concrete obstacle.",+ },+ "in_reply_to": {+ "type": "string",+ "description": (+ "Original message id for a delayed answer; "+ "otherwise inferred from the incoming turn."+ ),+ },"kind": {"type": "string","enum": sorted(_KINDS),@@ -130,7 +152,9 @@ class MessageAgentTool:):return _failure(FailureReason.BLOCKED_BY_POLICY, "internal messaging is disabled")target_key = str(args.get("target", "")).strip()- text = str(args.get("text", "")).strip()[:_MAX_TEXT]+ text = str(args.get("text", "")).strip()+ if len(text) > _MAX_TEXT:+ return _failure(FailureReason.BLOCKED_BY_POLICY, "message exceeds 8000 characters")if not target_key or not text:return _failure(FailureReason.BLOCKED_BY_POLICY, "target and text are required")target = await rt.roster.resolve(target_key)@@ -145,11 +169,56 @@ class MessageAgentTool:if msg_type is None:return _failure(FailureReason.BLOCKED_BY_POLICY, f"unknown kind {kind!r}")refs = args.get("refs")- payload: dict[str, Any] = {}+ try:+ policy = select_reply_policy(args.get("reply_policy"), msg_type)+ except (TypeError, ValueError) as exc:+ return _failure(FailureReason.BLOCKED_BY_POLICY, str(exc))+ reply_status = args.get("reply_status", "done")+ if reply_status not in ("done", "blocked"):+ return _failure(FailureReason.BLOCKED_BY_POLICY, "reply_status must be done or blocked")+ payload: dict[str, Any] = {"reply_policy": policy}+ if msg_type is MsgType.ANSWER:+ payload["reply_status"] = reply_statusif isinstance(refs, list) and refs:payload["refs"] = [str(r) for r in refs][:20]incoming = incoming_context.get()- trace_id = incoming.trace_id if incoming is not None else None+ parent_id = args.get("in_reply_to")+ if parent_id is not None and (not isinstance(parent_id, str) or not parent_id.strip()):+ return _failure(FailureReason.BLOCKED_BY_POLICY, "in_reply_to must be a message id")+ if parent_id is None and incoming is not None:+ parent_id = incoming.message_id+ parent = await rt.store.get_event(parent_id) if parent_id else None+ if args.get("in_reply_to") is not None and (+ parent is None+ or parent.to_agent != caller.agent_id+ or parent.from_agent != target.agent_id+ ):+ return _failure(+ FailureReason.BLOCKED_BY_POLICY,+ "in_reply_to is not a request from this target to you",+ )+ if msg_type is MsgType.ANSWER:+ if (+ parent is None+ or parent.to_agent != caller.agent_id+ or parent.from_agent != target.agent_id+ ):+ return _failure(+ FailureReason.BLOCKED_BY_POLICY,+ "an answer needs the original request from this target",+ )+ if parent.msg_type in (MsgType.ANSWER, MsgType.RESULT):+ return _failure(+ FailureReason.BLOCKED_BY_POLICY,+ "this exchange is already closed; do not acknowledge an answer",+ )+ if parent.msg_type is not MsgType.ASSIGN:+ expected = reply_policy(parent)+ if expected == "none" or (expected == "on_error" and reply_status == "done"):+ return _failure(+ FailureReason.BLOCKED_BY_POLICY, "no success reply was requested"+ )+ trace_id = parent.trace_id if parent is not None else Noneenv = await rt.say(from_agent=caller.agent_id,to_agent=target.agent_id,@@ -157,7 +226,7 @@ class MessageAgentTool:trace_id=trace_id,msg_type=msg_type,payload=payload,- parent_event_id=incoming.message_id if incoming is not None else None,+ parent_event_id=parent.event_id if parent is not None else None,)status = await rt.store.delivery_status(env.event_id)return ToolResult(@@ -169,6 +238,9 @@ class MessageAgentTool:"target": target.name,**({"delivered_to": target.name} if status == "delivered" else {}),"kind": kind,+ "reply_policy": policy,+ "in_reply_to": parent.event_id if parent is not None else None,+ "receipt_scope": "delivery only; not task completion or an answer","seq": env.seq,"trace_id": env.trace_id,},diff --git a/jarvis/society/browser/live.py b/jarvis/society/browser/live.pyindex 3a92fd6396..6c6a4218b5 100644--- a/jarvis/society/browser/live.py+++ b/jarvis/society/browser/live.py@@ -21,6 +21,7 @@ from . import installlog = logging.getLogger(__name__)RPC = Callable[[dict[str, Any]], Awaitable[dict[str, Any]]]MAX_LINE = 8 * 1024 * 1024+_FORCED_CLOSE_TIMEOUT_S = 2.0_BUSY = "This browser is busy or under manual control"_PAUSED = ("This browser is paused until you allow the action in the browser panel. "@@ -206,29 +207,50 @@ class LiveSession:self.tree.close()async def close(self) -> None:- if not self.closed:- try:- await self.command("shutdown", timeout=2)- except Exception:- log.debug("Browser graceful shutdown unavailable", exc_info=True)- if self.proc.stdin:- self.proc.stdin.close()- for task in list(self.tasks):- task.cancel()- await asyncio.gather(*self.tasks, return_exceptions=True)try:+ if not self.closed:+ try:+ await self.command("shutdown", timeout=2)+ except Exception:+ log.debug("Browser graceful shutdown unavailable", exc_info=True)+ if self.proc.stdin:+ self.proc.stdin.close()+ for task in list(self.tasks):+ task.cancel()await asyncio.wait_for(self.proc.wait(), timeout=5)except TimeoutError:log.debug("Browser graceful shutdown timed out; closing its process tree")- self.tree.close()- if self.proc.returncode is None:- self.proc.kill()- await self.proc.wait()- self.tree.close()- for task in self.readers:- task.cancel()- await asyncio.gather(*self.readers, return_exceptions=True)- self.closed = True+ finally:+ # Cancellation can arrive during either graceful wait. Release the+ # containment handle and terminate the owned worker before awaiting+ # anything else, then bound the process/task joins independently.+ self.closed = True+ try:+ self.tree.close()+ finally:+ if self.proc.returncode is None:+ try:+ self.proc.kill()+ except ProcessLookupError:+ pass # The containment close already reaped this worker.+ except OSError as exc:+ log.warning("Browser worker termination failed: %s", type(exc).__name__)+ if self.proc.stdin:+ self.proc.stdin.close()+ tasks = set(self.tasks) | set(self.readers)+ for task in tasks:+ task.cancel()+ reaping = asyncio.create_task(self.proc.wait())+ done, pending = await asyncio.wait(+ tasks | {reaping}, timeout=_FORCED_CLOSE_TIMEOUT_S+ )+ for task in done:+ if not task.cancelled() and (error := task.exception()) is not None:+ log.warning("Browser cleanup task failed: %s", type(error).__name__)+ if pending:+ # Keep reader/RPC handles available for a later close retry.+ reaping.cancel()+ raise TimeoutError("browser process cleanup incomplete")async def claim_browser(session: LiveSession, chat_session_id: str) -> None:@@ -285,6 +307,7 @@ class LiveSessions:self.executor: Any = Noneself.cdp_url = "http://127.0.0.1:9222"self.idle_tasks: dict[str, asyncio.Task] = {}+ self._closing_tasks: dict[str, asyncio.Task[None]] = {}self.stopped_turns: dict[tuple[str, str], None] = {}def stop_turn(self, agent_id: str, trace_id: str) -> None:@@ -518,9 +541,48 @@ class LiveSessions:self.release_when_idle(session)async def close(self) -> None:- for task in self.idle_tasks.values():+ idle = list(self.idle_tasks.values())+ for task in idle:task.cancel()- await asyncio.gather(*self.idle_tasks.values(), return_exceptions=True)- self.idle_tasks.clear()- await asyncio.gather(*(s.close() for s in self.sessions.values()), return_exceptions=True)- self.sessions.clear()+ sessions = list(self.sessions.items())+ closing = []+ for key, session in sessions:+ task = self._closing_tasks.get(key)+ if task is None or task.done():+ task = asyncio.create_task(session.close())+ self._closing_tasks[key] = task+ closing.append(task)+ owned = set(idle) | set(closing)+ try:+ if owned:+ # Unlike gather, wait returns immediately on caller cancellation,+ # so a reluctant idle/RPC task cannot defeat the server deadline.+ _done, pending = await asyncio.wait(owned, timeout=9)+ if pending:+ raise TimeoutError("browser sessions shutdown incomplete")+ for task in closing:+ task.result()+ finally:+ pending = {task for task in owned if not task.done()}+ for task in pending:+ task.cancel()+ if pending:+ _done, pending = await asyncio.wait(pending, timeout=3)+ for task in owned:+ if task.done() and not task.cancelled() and task.exception() is not None:+ log.warning("Browser owner cleanup failed: %s", type(task.exception()).__name__)+ for key, task in list(self.idle_tasks.items()):+ if task.done():+ self.idle_tasks.pop(key, None)+ for (key, session), task in zip(sessions, closing, strict=True):+ if task.done():+ self._closing_tasks.pop(key, None)+ if (+ task.done()+ and (task.cancelled() or task.exception() is None)+ and session.proc.returncode is not None+ and all(job.done() for job in (*session.tasks, *session.readers))+ ):+ self.sessions.pop(key, None)+ if pending:+ raise TimeoutError("browser sessions cleanup incomplete")diff --git a/jarvis/society/browser/live_runner.py b/jarvis/society/browser/live_runner.pyindex 67d95b748e..57f2d639b5 100644--- a/jarvis/society/browser/live_runner.py+++ b/jarvis/society/browser/live_runner.py@@ -106,6 +106,8 @@ class Worker:self.branding: asyncio.Task | None = Noneself.pointer: Any = Noneself.visual_action = False+ self.cursor_on = False+ self.cursor_jobs: set[asyncio.Task] = set()async def rpc(self, kind: str, payload: dict) -> dict:key = uuid.uuid4().hex@@ -194,6 +196,12 @@ class Worker:await asyncio.sleep(0.05)cdp_url = f"http://127.0.0.1:{port}"self.browser_args = {"cdp_url": cdp_url, "allowed_domains": args.get("allowed_domains")}+ try:+ from page_cursor import install_cursor # type: ignore[import-not-found]++ await install_cursor(self.context)+ except Exception:+ logging.getLogger(__name__).debug("Agent cursor could not be prepared", exc_info=True)self.context.on("page", self.page_opened)for page in self.context.pages:self.page_opened(page)@@ -285,6 +293,33 @@ class Worker:def page_opened(self, page: Any) -> None:page.on("dialog", self.on_dialog)+ page.on("framenavigated", self.cursor_navigated)++ def cursor_navigated(self, frame: Any) -> None:+ if not self.cursor_on or self.manual:+ return+ task = asyncio.create_task(self._arm_frame(frame))+ self.cursor_jobs.add(task)+ task.add_done_callback(self.cursor_jobs.discard)++ async def _arm_frame(self, frame: Any) -> None:+ from page_cursor import ARM_SOURCE, CURSOR_SCRIPT # type: ignore[import-not-found]++ try:+ await frame.evaluate(CURSOR_SCRIPT)+ await frame.evaluate(ARM_SOURCE, True)+ except Exception:+ logging.getLogger(__name__).debug(+ "Agent cursor could not follow a navigation", exc_info=True+ )++ async def show_page_cursor(self, armed: bool) -> None:+ from page_cursor import arm_cursor # type: ignore[import-not-found]++ try:+ await arm_cursor(self.context, armed)+ except Exception:+ logging.getLogger(__name__).debug("Agent cursor could not be updated", exc_info=True)def on_dialog(self, dialog: Any) -> None:self.dialog = dialog@@ -552,6 +587,10 @@ class Worker:await self.agent_gate.wait()self.step_idle.clear()+ visible = bool(self.native) or not self.owns_context+ if visible:+ self.cursor_on = True+ await self.show_page_cursor(True)try:history = await self.agent.run(max_steps=args.get("max_steps", 25), on_step_start=before_step, on_step_end=step@@ -570,6 +609,9 @@ class Worker:}finally:self.agent = None+ self.cursor_on = False+ if visible:+ await self.show_page_cursor(False)if self.pointer:self.pointer.clear()self.step_idle.set()@@ -615,6 +657,7 @@ class Worker:self.manual = Trueif self.pointer:self.pointer.clear()+ await self.show_page_cursor(False)else:if self.native and self.manual:await self.ensure_browser()@@ -628,6 +671,8 @@ class Worker:)self.manual = Falseself.agent_gate.set()+ if self.cursor_on:+ await self.show_page_cursor(True)return {"manual": self.manual}if op == "run":if self.manual:diff --git a/jarvis/society/browser/page_cursor.py b/jarvis/society/browser/page_cursor.pynew file mode 100644index 0000000000..ba6c79bcc1--- /dev/null+++ b/jarvis/society/browser/page_cursor.py@@ -0,0 +1,198 @@+"""The arrow drawn inside the real Chrome window.++Browser clicks are sent straight to the page. They never move the mouse the+person sees, so the window itself has to draw the arrow and glide it to the+click.+"""++from __future__ import annotations++import logging+from typing import Any++log = logging.getLogger(__name__)++# The page listens for the clicks it actually receives. The dataset is the+# switch: on while the agent is driving, off while the person has the window.+CURSOR_SCRIPT = """+(() => {+ if (globalThis.__jarvisCursorInstalled) return;+ globalThis.__jarvisCursorInstalled = true;+ const root = document.documentElement;+ if (!root) return;+ const host = document.createElement("div");+ host.id = "jarvis-agent-cursor";+ host.setAttribute("aria-hidden", "true");+ const paint = (name, value) => host.style.setProperty(name, value, "important");+ paint("position", "fixed");+ paint("margin", "0");+ paint("padding", "0");+ paint("border", "0");+ paint("background", "transparent");+ paint("width", "0");+ paint("height", "0");+ paint("overflow", "visible");+ paint("pointer-events", "none");+ paint("z-index", "2147483647");+ paint("inset", "auto");+ paint("left", "0");+ paint("top", "0");+ root.appendChild(host);+ try {+ host.setAttribute("popover", "manual");+ host.showPopover();+ paint("left", "0");+ paint("top", "0");+ } catch (error) {+ /* A document without popovers keeps the fixed layer. */+ }+ const shadow = host.attachShadow({ mode: "closed" });+ shadow.innerHTML = [+ "<style>",+ ":host{all:initial}",+ ".arrow{position:fixed;left:0;top:0;width:0;height:0;opacity:0;",+ "transform-origin:7.2px 2.4px;filter:drop-shadow(0 1px 1px rgba(0,0,0,.45))}",+ ".shift{transform:translate(-7.2px,-2.4px)}",+ ".ring{position:fixed;left:0;top:0;width:26px;height:26px;margin:-13px 0 0 -13px;",+ "border:2.5px solid #0a0a0a;border-radius:50%;box-shadow:0 0 0 1.5px #fff;",+ "opacity:0;pointer-events:none}",+ "</style>",+ '<div class="arrow"><div class="shift">',+ '<svg width="52" height="64" viewBox="0 0 34 42" fill="none">',+ '<path d="M7.2 2.4 L4.6 28.8 L11.2 24.2 L15.4 39.2 L20.2 36.6 L16.2 22.2 L31.2 21.2 Z"',+ ' fill="#fff" stroke="#0a0a0a" stroke-width="1.9" stroke-linejoin="round"',+ ' stroke-linecap="round"/></svg></div></div><div class="ring"></div>',+ ].join("");+ const arrow = shadow.querySelector(".arrow");+ const ring = shadow.querySelector(".ring");+ const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;+ let x = null;+ let y = null;+ let fromX = 0;+ let fromY = 0;+ let toX = 0;+ let toY = 0;+ let started = 0;+ let duration = 0;+ let pending = null;+ let handle = 0;+ const armed = () => root.dataset.jarvisCursor === "1";+ const ease = (t) => {+ const left = 1 - t;+ return 1 - left * left * left;+ };+ const travel = (distance) => (+ distance < 1 ? 0 : Math.min(340, Math.max(130, 110 + distance * 0.28))+ );+ const show = (px, py) => {+ arrow.style.transform = "translate3d(" + px + "px," + py + "px,0)";+ arrow.style.opacity = "1";+ };+ const press = (px, py) => {+ const at = "translate3d(" + px + "px," + py + "px,0)";+ ring.style.opacity = "1";+ ring.animate(+ [+ { transform: at + " scale(0.4)", opacity: 0.95 },+ { transform: at + " scale(1.8)", opacity: 0 },+ ],+ { duration: reduce ? 1 : 420, easing: "cubic-bezier(0.16, 1, 0.3, 1)", fill: "forwards" },+ );+ arrow.animate(+ [+ { transform: at + " scale(1)" },+ { transform: at + " scale(0.9)", offset: 0.45 },+ { transform: at + " scale(1)" },+ ],+ { duration: reduce ? 1 : 110, easing: "ease-out" },+ );+ };+ const arrived = (px, py) => {+ if (!pending) return;+ const dx = px - pending.x;+ const dy = py - pending.y;+ if (dx * dx + dy * dy > 6.25) return;+ const point = pending;+ pending = null;+ press(point.x, point.y);+ };+ const step = (now) => {+ const t = duration <= 0 ? 1 : Math.min(1, Math.max(0, (now - started) / duration));+ const eased = ease(t);+ x = fromX + (toX - fromX) * eased;+ y = fromY + (toY - fromY) * eased;+ show(x, y);+ arrived(x, y);+ handle = t < 1 ? requestAnimationFrame(step) : 0;+ };+ const aim = (nx, ny, down) => {+ if (!armed()) {+ arrow.style.opacity = "0";+ pending = null;+ return;+ }+ if (!host.isConnected) root.appendChild(host);+ if (x === null) {+ x = nx;+ y = ny;+ fromX = nx;+ fromY = ny;+ toX = nx;+ toY = ny;+ duration = 0;+ show(nx, ny);+ } else if (Math.abs(toX - nx) > 0.5 || Math.abs(toY - ny) > 0.5) {+ fromX = x;+ fromY = y;+ toX = nx;+ toY = ny;+ started = performance.now();+ duration = reduce ? 0 : travel(Math.hypot(nx - x, ny - y));+ if (duration === 0) {+ x = nx;+ y = ny;+ show(nx, ny);+ } else if (!handle) {+ handle = requestAnimationFrame(step);+ }+ }+ if (down) pending = { x: nx, y: ny };+ if (x !== null) arrived(x, y);+ };+ window.addEventListener("mousemove", (event) => aim(event.clientX, event.clientY, false), true);+ window.addEventListener("mousedown", (event) => aim(event.clientX, event.clientY, true), true);+ new MutationObserver(() => {+ if (!armed()) {+ arrow.style.opacity = "0";+ pending = null;+ }+ }).observe(root, { attributes: true, attributeFilter: ["data-jarvis-cursor"] });+})();+"""++ARM_SOURCE = (+ "(on) => { const root = document.documentElement;"+ " if (root) root.dataset.jarvisCursor = on ? '1' : ''; }"+)+++async def install_cursor(context: Any) -> None:+ """Put the arrow on every later document in this browser."""+ await context.add_init_script(CURSOR_SCRIPT)+++async def arm_cursor(context: Any, armed: bool) -> None:+ """Show or hide the arrow on documents that are already open."""+ if context is None:+ return+ for page in list(getattr(context, "pages", ()) or ()):+ closed = getattr(page, "is_closed", None)+ if callable(closed) and closed():+ continue+ frames = list(getattr(page, "frames", ()) or ()) or [page]+ for frame in frames:+ try:+ await frame.evaluate(CURSOR_SCRIPT)+ await frame.evaluate(ARM_SOURCE, armed)+ except Exception:+ log.debug("Agent cursor could not attach to this frame", exc_info=True)diff --git a/jarvis/society/browser/session.py b/jarvis/society/browser/session.pyindex da6fcf7337..6cf1340e94 100644--- a/jarvis/society/browser/session.py+++ b/jarvis/society/browser/session.py@@ -180,18 +180,28 @@ class BrowserJobs:}async def close(self) -> None:- await self.live.close()- for agent_id in list(self._procs):- await self.kill(agent_id)+ try:+ await self.live.close()+ finally:+ # A cancelled live-browser shutdown still owns the one-shot jobs.+ results = await asyncio.gather(+ *(self.kill(agent_id) for agent_id in list(self._procs)), return_exceptions=True+ )+ for result in results:+ if isinstance(result, BaseException):+ raise resultasync def kill(self, agent_id: str) -> bool:- proc = self._procs.pop(agent_id, None)- if proc is None or proc.returncode is not None:+ proc = self._procs.get(agent_id)+ if proc is None:+ return False+ if proc.returncode is not None:+ self._procs.pop(agent_id, None)return Falsewith contextlib.suppress(ProcessLookupError, OSError):proc.kill()- with contextlib.suppress(ProcessLookupError, OSError):- await proc.wait()+ await asyncio.wait_for(proc.wait(), timeout=2)+ self._procs.pop(agent_id, None)return True# -------------------------------------------------------------- jobsdiff --git a/jarvis/society/chat_binding.py b/jarvis/society/chat_binding.pyindex 7f238b14a7..15cfaa7089 100644--- a/jarvis/society/chat_binding.py+++ b/jarvis/society/chat_binding.py@@ -22,6 +22,7 @@ from collections.abc import Callablefrom pathlib import Pathfrom typing import Any, Final+from .communication import response_instructionfrom .delivery import DeliveryBusy, IncomingMessage, incoming_contextfrom .events import MsgType, SocietyEnvelopefrom .roster import LEAD_AGENT_ID, AgentRecord, PermissionCeiling@@ -131,11 +132,8 @@ def frame_incoming(env: SocietyEnvelope, sender_name: str) -> str:refs = env.payload.get("refs")if isinstance(refs, list) and refs:lines.append("Refs: " + ", ".join(str(r) for r in refs))- if env.msg_type is MsgType.QUERY:- lines.append(- "Reply to the sender using society_message_agent with kind 'answer'. "- "This is internal communication; do not use an external messaging connector."- )+ lines.append(f"Message id: {env.event_id}; sender id: {env.from_agent}")+ lines.append(response_instruction(env))return "\n".join(lines)@@ -151,6 +149,8 @@ def frame_assignment(env: SocietyEnvelope) -> str:"When you are done, end with a handoff: what is done, where the output is, ""what evidence you used, what remains open, who should own the next step.")+ lines.append(f"Message id: {env.event_id}; sender id: {env.from_agent}")+ lines.append(response_instruction(env))return "\n".join(lines)@@ -179,7 +179,13 @@ def make_deliver_hook(message_id=env.event_id,sender_id=env.from_agent,sender_name=sender,- sender_kind=("jarvis" if env.from_agent == LEAD_AGENT_ID else "user" if env.from_agent == "user" else "agent"),+ sender_kind=(+ "jarvis"+ if env.from_agent == LEAD_AGENT_ID+ else "user"+ if env.from_agent == "user"+ else "agent"+ ),text=env.text,prompt=frame_incoming(env, sender),trace_id=env.trace_id,diff --git a/jarvis/society/communication.py b/jarvis/society/communication.pynew file mode 100644index 0000000000..f3e0345634--- /dev/null+++ b/jarvis/society/communication.py@@ -0,0 +1,103 @@+"""Portable reply expectations shared by lead and teammate communication.++Policies live in the existing envelope JSON, not in delivery status. Old+assignments still report completion; information and answers close quietly.+"""++from __future__ import annotations++from typing import Any++from .events import MsgType, SocietyEnvelope++REPLY_POLICIES = ("none", "on_error", "always")+REPLY_POLICY_SCHEMA: dict[str, Any] = {+ "type": "string",+ "enum": list(REPLY_POLICIES),+ "description": (+ "Expected reply: none for information or an explicitly silent task; "+ "on_error for work needing only blockers reported; always for a question, "+ "requested result or decision. Choose from the user's intent and context."+ ),+}++COMMUNICATION_GUIDANCE = """## Communicating with teammates+Compose an independently actionable brief, not a lightly reworded user sentence.+Use the relevant conversation: explain the objective, known target and context,+concrete scope, constraints, and what evidence or output establishes completion.+Keep simple requests short; include detail only when it helps the recipient act.+Never invent URLs, paths, credentials, prior decisions or additional authorization.+Resolve references such as "that page" from known context; identify missing facts.+For "tell X to do Y", delegate the actual work with delegate_to_agent when available.+For "ask X about Y", send a query with the precise question and relevant context.+Use say for information, propose for a decision, answer for a substantive reply.+Choose reply_policy explicitly: always for requested findings or an answer,+on_error for work with no requested success report, none for information or an+explicit request for silence. A query always needs an answer. Answers normally+end the exchange; do not send acknowledgements, thanks, or acknowledgement loops.+Use reply_status=blocked for an inability to finish or a missing prerequisite.+Necessary clarification uses a concrete query, not a generic "shall I proceed?".+Delivery is not task completion, and a promise to act is not evidence of success.+Reply to the requesting agent; the lead conveys requested findings to the user.+Example: "test your browser" becomes a check of opening a public test page,+reading its content and following a link with the granted browser tool; record+observations and distinguish browser-access failures from page failures. Use a+known target when provided. Do not turn this into an unrelated full product audit.+"""+++def select_reply_policy(value: Any, kind: MsgType) -> str:+ """Validate tool input, preserving compatible defaults for older callers."""+ default = "always" if kind in (MsgType.ASSIGN, MsgType.QUERY, MsgType.PROPOSE) else "none"+ policy = default if value is None else value+ if policy not in REPLY_POLICIES:+ raise ValueError("reply_policy must be none, on_error or always")+ if kind is MsgType.QUERY and policy != "always":+ raise ValueError("a query requires reply_policy=always")+ if kind is MsgType.ANSWER and policy != "none":+ raise ValueError("an answer closes the exchange; use a query for a new question")+ return policy+++def reply_policy(env: SocietyEnvelope) -> str:+ """Read older envelopes without failing the receiver on malformed metadata."""+ try:+ return select_reply_policy(env.payload.get("reply_policy"), env.msg_type)+ except (TypeError, ValueError):+ # Invalid old metadata must not hide a requested result.+ return "always" if env.msg_type in (MsgType.ASSIGN, MsgType.QUERY) else "none"+++def should_report(env: SocietyEnvelope, status: str) -> bool:+ policy = reply_policy(env)+ return policy == "always" or (policy == "on_error" and status != "done")+++def response_instruction(env: SocietyEnvelope) -> str:+ policy = reply_policy(env)+ if env.msg_type is MsgType.ASSIGN:+ return (+ f"Reply expectation: {policy}. Record the actual outcome and evidence in your "+ "final response. The runtime routes the completion; do not send a second "+ "success message. If blocked or unable to finish, send an answer to the "+ "requesting agent with reply_status=blocked and the specific obstacle. "+ "A finished chat turn alone does not prove the task succeeded."+ )+ if policy == "always":+ return (+ "Reply to the sender using society_message_agent with kind 'answer'. "+ "Include the actual findings or decision; use reply_status=blocked if you "+ "cannot answer. This is internal communication; do not use an external "+ "messaging connector. No preliminary acknowledgement is needed."+ )+ if policy == "on_error":+ return (+ "Reply only for a blocker or missing prerequisite, using society_message_agent "+ "with kind 'answer' and reply_status=blocked. Keep successful completion in "+ "your own chat; do not send a success acknowledgement."+ )+ return (+ "No reply is requested. Use this information and finish in your own chat. "+ "Do not send an acknowledgement or reply to an answer. A genuinely new question "+ "or material blocker may start a separate, substantive exchange."+ )diff --git a/jarvis/society/companion.py b/jarvis/society/companion.pynew file mode 100644index 0000000000..06522d0a5a--- /dev/null+++ b/jarvis/society/companion.py@@ -0,0 +1,26 @@+"""Validated visual companion settings inside the existing avatar JSON envelope."""++from typing import Any, Literal++from pydantic import BaseModel, ConfigDict, Field+++class CompanionAppearance(BaseModel):+ """One identity for the profile and its presentation-only world follower."""++ model_config = ConfigDict(extra="forbid", strict=True)++ shape: Literal["circle", "squircle", "pill", "triangle", "hexagon", "cloud", "drop"]+ color: str = Field(pattern=r"^#[0-9a-fA-F]{6}$")+ eyes: Literal["dots", "lines"] = "dots"+ enabled: bool = True+ sizeM: float = Field(default=0.5, ge=0.25, le=0.8)+ followDistanceM: float = Field(default=1.0, ge=0.5, le=2.0)+++def validate_avatar_companion(avatar: dict[str, Any]) -> dict[str, Any]:+ """Preserve character/import fields verbatim; validate only our namespace."""+ if "companion" not in avatar:+ return avatar+ companion = CompanionAppearance.model_validate(avatar["companion"])+ return {**avatar, "companion": companion.model_dump()}diff --git a/jarvis/society/inherit.py b/jarvis/society/inherit.pynew file mode 100644index 0000000000..602b1153f3--- /dev/null+++ b/jarvis/society/inherit.py@@ -0,0 +1,133 @@+"""Copy a creating agent's seat and permission setup onto a new roster row.++When a society agent creates a teammate — typed chat or a subscription CLI+calling ``society-create-agent`` — the new row starts on the creator's model+seat (provider, model, effort, subscription account) and may not exceed the+creator's permission ceiling, grant mode, grants or denies. The Agents UI+sends those fields itself, so an explicit choice still wins, and a blank+create from the UI (no society session) keeps the usual defaults.+"""++from __future__ import annotations++from typing import Any++from .events import GrantMode, PermissionCeiling+from .roster import AgentRecord+from .surface import agent_id_of++__all__ = [+ "caller_session_id",+ "inherit_creator_fields",+ "session_agent_id",+]++_CEILING_RANK: dict[str, int] = {+ str(PermissionCeiling.SAFE): 0,+ str(PermissionCeiling.MONITOR): 1,+ str(PermissionCeiling.ASK): 2,+}++_SEAT_FIELDS: tuple[str, ...] = ("provider", "model", "effort", "account_id")+++def session_agent_id(session_id: str | None) -> str | None:+ """The roster id behind a society chat session, else ``None``."""+ if not session_id:+ return None+ return agent_id_of(str(session_id).strip())+++def caller_session_id() -> str | None:+ """The chat session of the in-flight tool call, if one is running.++ MCP seats stamp ``CHAT_SESSION_REF`` from ``X-Jarvis-Chat-Session``.+ Brain-runner seats stamp ``current_chat_turn``. Either is enough to+ know which agent is creating a teammate.+ """+ try:+ from jarvis.mcp.jarvis_tools_server import CHAT_SESSION_REF++ stamped = CHAT_SESSION_REF.get()+ if stamped:+ return str(stamped)+ except Exception: # noqa: BLE001 — optional; a missing MCP server is not a create failure+ pass+ try:+ from jarvis.core.chat_turn import current_chat_turn++ turn = current_chat_turn.get()+ if turn is not None and turn.session_id:+ return str(turn.session_id)+ except Exception: # noqa: BLE001 — optional; a missing turn is not a create failure+ pass+ return None+++def _blank(value: Any) -> bool:+ if value is None:+ return True+ if isinstance(value, str):+ return not value.strip()+ return False+++def _capped_ceiling(requested: str, creator: str) -> str:+ """Never raise a child above the creator's unattended ceiling."""+ want = _CEILING_RANK.get(requested, _CEILING_RANK[str(PermissionCeiling.MONITOR)])+ cap = _CEILING_RANK.get(creator, _CEILING_RANK[str(PermissionCeiling.MONITOR)])+ rank = min(want, cap)+ for name, value in _CEILING_RANK.items():+ if value == rank:+ return name+ return creator+++def inherit_creator_fields(fields: dict[str, Any], creator: AgentRecord) -> dict[str, Any]:+ """Fill unset create fields from ``creator`` and cap any explicit raise.++ Mutates and returns ``fields``. Role-specific fields (name, title,+ description, focus, skills, budget, avatar) stay with the request.+ """+ if _blank(fields.get("parent_agent_id")):+ fields["parent_agent_id"] = creator.agent_id+ for key in _SEAT_FIELDS:+ if _blank(fields.get(key)):+ value = str(getattr(creator, key) or "")+ if value:+ fields[key] = value++ requested_ceiling = str(fields.get("permission_ceiling") or "").strip()+ creator_ceiling = str(creator.permission_ceiling)+ fields["permission_ceiling"] = (+ _capped_ceiling(requested_ceiling, creator_ceiling)+ if requested_ceiling+ else creator_ceiling+ )++ creator_mode = str(creator.grant_mode)+ requested_mode = str(fields.get("grant_mode") or "").strip()+ if creator_mode == str(GrantMode.ALLOWLIST):+ allowed = set(creator.grants)+ fields["grant_mode"] = str(GrantMode.ALLOWLIST)+ if "grants" in fields and isinstance(fields["grants"], list):+ fields["grants"] = [str(item) for item in fields["grants"] if str(item) in allowed]+ else:+ fields["grants"] = list(creator.grants)+ elif not requested_mode:+ fields["grant_mode"] = creator_mode+ if "grants" not in fields and creator.grants:+ fields["grants"] = list(creator.grants)++ creator_denies = [str(item) for item in creator.denies]+ if "denies" not in fields:+ if creator_denies:+ fields["denies"] = creator_denies+ else:+ existing = [str(item) for item in (fields.get("denies") or [])]+ merged: list[str] = []+ for item in (*creator_denies, *existing):+ if item and item not in merged:+ merged.append(item)+ fields["denies"] = merged+ return fieldsdiff --git a/jarvis/society/lead_card.py b/jarvis/society/lead_card.pyindex 32a44ffd63..fdb5181d3b 100644--- a/jarvis/society/lead_card.py+++ b/jarvis/society/lead_card.py@@ -31,6 +31,7 @@ from collections.abc import Callable, Sequencefrom typing import Finalfrom .capabilities import CapabilityRow+from .communication import COMMUNICATION_GUIDANCEfrom .roster import LEAD_AGENT_ID, AgentRecordfrom .runtime import current_runtime@@ -56,8 +57,8 @@ def _rule_block(lead_name: str) -> str:return (f"You are {lead_name}, the lead of the user's agent society: the named agents ""listed below live in the Agents section, each with its own chat, its own tools "- "and its own standing instructions. When the user says \"agent\", \"my agents\" "- "or \"the team\", they mean THESE agents.\n"+ 'and its own standing instructions. When the user says "agent", "my agents" '+ 'or "the team", they mean THESE agents.\n'"- Send internal messages with message_agent (target, text). A message TO an email ""specialist is not email: never call gmail for this. Internal messages need no extra ""confirmation. Report the actual queued/delivered/failed receipt.\n"@@ -65,8 +66,8 @@ def _rule_block(lead_name: str) -> str:"full, relevant conversation context, completion_criteria and refs). Report ""the actual assignment receipt, keep its assignment and trace identifiers, ""and use society_status to follow results.\n"- "- Answer \"which agents do you have\", \"who is on the team\", \"what is X "- "doing\", \"is X done\" with society_status — never from the "+ '- Answer "which agents do you have", "who is on the team", "what is X '+ 'doing", "is X done" with society_status — never from the '"retired sub-agent or mission-worker system. These are read-only questions: ""never assign work or announce a spawn for them. Use details=true for actual ""roles, capabilities and measured event history; never invent performance scores.\n"@@ -77,6 +78,8 @@ def _rule_block(lead_name: str) -> str:"work the user explicitly asked to run in the background that no agent covers.\n""- Create or reconfigure an agent only when requested: use society-create-agent, ""society-update-agent or society-switch-agent-model through the app commands. "+ "A teammate that creates another agent copies its own model seat and permission "+ "setup onto the new agent unless a different model is requested. ""Inspect society-capability-catalog for capabilities and society-agent-catalog ""for models. These commands share the ""Agents section's validation. Verify the returned state before claiming success.\n"@@ -144,7 +147,7 @@ def render_lead_card(key=lambda a: a.name.casefold(),)by_id = {row.id: row for row in catalog if row.connected}- parts: list[str] = [CARD_TITLE, _rule_block(lead_name)]+ parts: list[str] = [CARD_TITLE, _rule_block(lead_name), COMMUNICATION_GUIDANCE]if team:lines = ["Agents (name — title · tier · state · hands):"]for agent in team:diff --git a/jarvis/society/mars/__init__.py b/jarvis/society/mars/__init__.pynew file mode 100644index 0000000000..453fde0913--- /dev/null+++ b/jarvis/society/mars/__init__.py@@ -0,0 +1 @@+"""Renderer-independent Mars station contracts; no startup side effects."""diff --git a/jarvis/society/mars/definition.json b/jarvis/society/mars/definition.jsonnew file mode 100644index 0000000000..ea5b6d6a9e--- /dev/null+++ b/jarvis/society/mars/definition.json@@ -0,0 +1,3370 @@+{+ "schema_version": 1,+ "world_id": "mars:ordinary",+ "layout_version": 1,+ "seed": 6901,+ "units": "metres",+ "axes": {+ "up": "+Y",+ "east": "+X",+ "north": "-Z"+ },+ "reference_id": "ref-layout",+ "status": "blockout",+ "bounds": {+ "min": [+ -430,+ -12,+ -400+ ],+ "max": [+ 435,+ 180,+ 410+ ]+ },+ "districts": [+ {+ "id": "central",+ "name": "Central district",+ "center": [+ 0,+ 48,+ 0+ ],+ "size": [+ 250,+ 210+ ],+ "landmark_height": 35,+ "stage": "blockout",+ "terrain": "plateau",+ "access": "exterior",+ "asset": null+ },+ {+ "id": "foundry",+ "name": "Agent Foundry",+ "center": [+ -30,+ 92,+ -290+ ],+ "size": [+ 145,+ 135+ ],+ "landmark_height": 82,+ "stage": "blockout",+ "terrain": "plateau",+ "access": "exterior",+ "asset": null+ },+ {+ "id": "mine",+ "name": "The Mine",+ "center": [+ 150,+ 80,+ -260+ ],+ "size": [+ 155,+ 155+ ],+ "landmark_height": 20,+ "stage": "blockout",+ "terrain": "plateau",+ "access": "exterior",+ "asset": null+ },+ {+ "id": "workshop",+ "name": "Workshop",+ "center": [+ -230,+ 66,+ -170+ ],+ "size": [+ 130,+ 115+ ],+ "landmark_height": 24,+ "stage": "blockout",+ "terrain": "plateau",+ "access": "exterior",+ "asset": null+ },+ {+ "id": "water-extraction",+ "name": "Water Extraction",+ "center": [+ -320,+ 42,+ -10+ ],+ "size": [+ 130,+ 150+ ],+ "landmark_height": 22,+ "stage": "blockout",+ "terrain": "plateau",+ "access": "exterior",+ "asset": null+ },+ {+ "id": "memory-house",+ "name": "Memory House",+ "center": [+ 240,+ 70,+ -160+ ],+ "size": [+ 105,+ 100+ ],+ "landmark_height": 23,+ "stage": "blockout",+ "terrain": "plateau",+ "access": "exterior",+ "asset": null+ },+ {+ "id": "harbor-gate",+ "name": "Harbor Gate",+ "center": [+ -230,+ 25,+ 240+ ],+ "size": [+ 180,+ 145+ ],+ "landmark_height": 65,+ "stage": "blockout",+ "terrain": "plateau",+ "access": "exterior",+ "asset": null+ },+ {+ "id": "gardens",+ "name": "Gardens",+ "center": [+ 80,+ 36,+ 300+ ],+ "size": [+ 210,+ 125+ ],+ "landmark_height": 20,+ "stage": "blockout",+ "terrain": "plateau",+ "access": "exterior",+ "asset": null+ },+ {+ "id": "solar-field",+ "name": "Solar Field",+ "center": [+ -25,+ 58,+ -175+ ],+ "size": [+ 170,+ 85+ ],+ "landmark_height": 5,+ "stage": "blockout",+ "terrain": "plateau",+ "access": "exterior",+ "asset": null+ },+ {+ "id": "communications-outpost",+ "name": "Communications Outpost",+ "center": [+ 320,+ 58,+ 50+ ],+ "size": [+ 120,+ 95+ ],+ "landmark_height": 62,+ "stage": "blockout",+ "terrain": "plateau",+ "access": "exterior",+ "asset": null+ }+ ],+ "buildings": [+ {+ "id": "jarvis-hub",+ "name": "Jarvis Hub",+ "district_id": "central",+ "position": [+ 0,+ 48,+ 0+ ],+ "size": [+ 36,+ 30,+ 36+ ],+ "checkpoint": "meeting",+ "stage": "blockout",+ "access": "planned-exterior",+ "asset": null+ },+ {+ "id": "terminal",+ "name": "Terminal",+ "district_id": "central",+ "position": [+ -64,+ 48,+ -34+ ],+ "size": [+ 36,+ 12,+ 18+ ],+ "checkpoint": "hub:cli",+ "stage": "blockout",+ "access": "planned-exterior",+ "asset": null+ },+ {+ "id": "plugin-docks",+ "name": "Plugin Docks",+ "district_id": "central",+ "position": [+ 64,+ 48,+ -34+ ],+ "size": [+ 36,+ 12,+ 18+ ],+ "checkpoint": "hub:plugins",+ "stage": "blockout",+ "access": "planned-exterior",+ "asset": null+ },+ {+ "id": "control-room",+ "name": "Control Room",+ "district_id": "central",+ "position": [+ -72,+ 48,+ 10+ ],+ "size": [+ 24,+ 10,+ 18+ ],+ "checkpoint": "hub:desktop",+ "stage": "blockout",+ "access": "planned-exterior",+ "asset": null+ },+ {+ "id": "skill-forge",+ "name": "Skill Forge",+ "district_id": "central",+ "position": [+ 72,+ 48,+ 10+ ],+ "size": [+ 24,+ 10,+ 18+ ],+ "checkpoint": "hub:skills",+ "stage": "blockout",+ "access": "planned-exterior",+ "asset": null+ },+ {+ "id": "signal-office",+ "name": "Signal Office",+ "district_id": "central",+ "position": [+ -45,+ 48,+ 61+ ],+ "size": [+ 24,+ 10,+ 18+ ],+ "checkpoint": "hub:comms",+ "stage": "blockout",+ "access": "planned-exterior",+ "asset": null+ },+ {+ "id": "gallery",+ "name": "Gallery",+ "district_id": "central",+ "position": [+ 45,+ 48,+ 61+ ],+ "size": [+ 24,+ 10,+ 18+ ],+ "checkpoint": "gallery",+ "stage": "blockout",+ "access": "planned-exterior",+ "asset": null+ },+ {+ "id": "boiler-house",+ "name": "Boiler House",+ "district_id": "central",+ "position": [+ 0,+ 48,+ -76+ ],+ "size": [+ 36,+ 18,+ 24+ ],+ "checkpoint": "hub:models",+ "stage": "blockout",+ "access": "planned-exterior",+ "asset": null+ },+ {+ "id": "lookout",+ "name": "The Lookout",+ "district_id": "central",+ "position": [+ 0,+ 48,+ 85+ ],+ "size": [+ 24,+ 14,+ 24+ ],+ "checkpoint": "idle",+ "stage": "blockout",+ "access": "planned-exterior",+ "asset": null+ },+ {+ "id": "communications-mast",+ "name": "Communications mast",+ "district_id": "communications-outpost",+ "position": [+ 320,+ 58,+ 46+ ],+ "size": [+ 14,+ 62,+ 14+ ],+ "checkpoint": null,+ "stage": "blockout",+ "access": "exterior-only",+ "asset": null+ },+ {+ "id": "operations",+ "name": "Outpost operations",+ "district_id": "communications-outpost",+ "position": [+ 294,+ 58,+ 64+ ],+ "size": [+ 20,+ 8,+ 14+ ],+ "checkpoint": "hub:comms",+ "stage": "blockout",+ "access": "required-interior",+ "asset": null+ },+ {+ "id": "radome-north",+ "name": "North radome",+ "district_id": "communications-outpost",+ "position": [+ 298,+ 58,+ 21+ ],+ "size": [+ 18,+ 17,+ 18+ ],+ "checkpoint": null,+ "stage": "blockout",+ "access": "exterior-only",+ "asset": null+ },+ {+ "id": "radome-south",+ "name": "South radome",+ "district_id": "communications-outpost",+ "position": [+ 351,+ 58,+ 69+ ],+ "size": [+ 22,+ 18,+ 22+ ],+ "checkpoint": null,+ "stage": "blockout",+ "access": "exterior-only",+ "asset": null+ },+ {+ "id": "dish-west",+ "name": "Western dish",+ "district_id": "communications-outpost",+ "position": [+ 278,+ 58,+ 46+ ],+ "size": [+ 21,+ 24,+ 21+ ],+ "checkpoint": null,+ "stage": "blockout",+ "access": "exterior-only",+ "asset": null+ },+ {+ "id": "dish-east",+ "name": "Eastern dish",+ "district_id": "communications-outpost",+ "position": [+ 351,+ 58,+ 21+ ],+ "size": [+ 25,+ 29,+ 25+ ],+ "checkpoint": null,+ "stage": "blockout",+ "access": "exterior-only",+ "asset": null+ },+ {+ "id": "service-east",+ "name": "Outpost service building",+ "district_id": "communications-outpost",+ "position": [+ 363,+ 58,+ 45+ ],+ "size": [+ 12,+ 12,+ 12+ ],+ "checkpoint": null,+ "stage": "blockout",+ "access": "planned-exterior",+ "asset": null+ }+ ],+ "navigation": {+ "version": 1,+ "nodes": [+ {+ "id": "hub-east",+ "position": [+ 125,+ 48,+ 40+ ]+ },+ {+ "id": "outpost-west",+ "position": [+ 256,+ 58,+ 50+ ]+ },+ {+ "id": "outpost-arrival",+ "position": [+ 268,+ 58,+ 68+ ],+ "resource_ids": [+ "corridor:route05-lead"+ ]+ },+ {+ "id": "console-approach",+ "position": [+ 294,+ 58,+ 75+ ]+ },+ {+ "id": "console",+ "position": [+ 294,+ 58,+ 64+ ]+ },+ {+ "id": "outpost-south",+ "position": [+ 325,+ 58,+ 96+ ],+ "resource_ids": [+ "corridor:route05-tail"+ ]+ },+ {+ "id": "gardens-east",+ "position": [+ 185,+ 36,+ 300+ ]+ },+ {+ "id": "hub-south",+ "position": [+ 0,+ 48,+ 109+ ]+ },+ {+ "id": "gardens-north",+ "position": [+ 80,+ 36,+ 234+ ]+ },+ {+ "id": "harbor-east",+ "position": [+ -137,+ 25,+ 240+ ]+ },+ {+ "id": "hub-west",+ "position": [+ -128,+ 48,+ 20+ ]+ },+ {+ "id": "water-east",+ "position": [+ -251,+ 42,+ -10+ ]+ },+ {+ "id": "workshop-south",+ "position": [+ -230,+ 66,+ -111+ ]+ },+ {+ "id": "hub-north",+ "position": [+ 0,+ 48,+ -110+ ]+ },+ {+ "id": "solar-south",+ "position": [+ -25,+ 58,+ -129+ ]+ },+ {+ "id": "foundry-south",+ "position": [+ -30,+ 92,+ -220+ ]+ },+ {+ "id": "mine-south",+ "position": [+ 150,+ 80,+ -180+ ]+ },+ {+ "id": "memory-west",+ "position": [+ 185,+ 70,+ -160+ ]+ },+ {+ "id": "central-northwest",+ "position": [+ -128,+ 48,+ -110+ ]+ },+ {+ "id": "central-northeast",+ "position": [+ 125,+ 48,+ -110+ ]+ },+ {+ "id": "central-southeast",+ "position": [+ 125,+ 48,+ 109+ ]+ },+ {+ "id": "central-southwest",+ "position": [+ -128,+ 48,+ 109+ ]+ },+ {+ "id": "rover-a-dock",+ "position": [+ 285.1,+ 58,+ 76.4+ ],+ "resource_ids": [+ "clearance:rover-a"+ ]+ },+ {+ "id": "rover-a-board",+ "position": [+ 283.05767024317663,+ 58,+ 78.51633862233665+ ]+ },+ {+ "id": "rover-a-exit",+ "position": [+ 284.673268030764,+ 58,+ 79.30996560571289+ ]+ },+ {+ "id": "rover-a-alternate",+ "position": [+ 286.3345308630297,+ 58,+ 73.88684788597524+ ],+ "resource_ids": [+ "corridor:route05-lead"+ ]+ },+ {+ "id": "rover-a-shoulder",+ "position": [+ 279.37769750478327,+ 58,+ 76.70863271575743+ ]+ },+ {+ "id": "rover-a-alternate-shoulder",+ "position": [+ 281.8467592308427,+ 58,+ 71.6823284877079+ ],+ "resource_ids": [+ "corridor:route05-lead"+ ]+ },+ {+ "id": "rover-b-dock",+ "position": [+ 313.6,+ 58,+ 90.4+ ],+ "resource_ids": [+ "clearance:rover-b"+ ]+ },+ {+ "id": "rover-b-board",+ "position": [+ 311.55767024317663,+ 58,+ 92.51633862233665+ ]+ },+ {+ "id": "rover-b-exit",+ "position": [+ 313.173268030764,+ 58,+ 93.30996560571289+ ]+ },+ {+ "id": "rover-b-alternate",+ "position": [+ 314.8345308630297,+ 58,+ 87.88684788597524+ ]+ },+ {+ "id": "rover-b-shoulder",+ "position": [+ 316.85324076915737,+ 58,+ 95.1176715122921+ ]+ },+ {+ "id": "rover-b-alternate-shoulder",+ "position": [+ 319.3223024952168,+ 58,+ 90.09136728424258+ ]+ }+ ],+ "edges": [+ {+ "id": "route-01",+ "from": "hub-east",+ "to": "outpost-west",+ "width": 10,+ "kind": "bridge",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-02",+ "from": "outpost-west",+ "to": "outpost-arrival",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-03",+ "from": "outpost-arrival",+ "to": "console-approach",+ "width": 4,+ "kind": "footpath",+ "modes": [+ "pedestrian"+ ],+ "stage": "blockout",+ "resource_ids": [+ "corridor:route05-lead"+ ]+ },+ {+ "id": "route-04",+ "from": "console-approach",+ "to": "console",+ "width": 2.4,+ "kind": "interior",+ "modes": [+ "pedestrian"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-06",+ "from": "outpost-south",+ "to": "gardens-east",+ "width": 10,+ "kind": "bridge",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-07",+ "from": "hub-south",+ "to": "gardens-north",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-08",+ "from": "gardens-north",+ "to": "gardens-east",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-09",+ "from": "harbor-east",+ "to": "gardens-north",+ "width": 10,+ "kind": "bridge",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-10",+ "from": "hub-west",+ "to": "water-east",+ "width": 10,+ "kind": "bridge",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-11",+ "from": "hub-west",+ "to": "workshop-south",+ "width": 10,+ "kind": "bridge",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-12",+ "from": "hub-north",+ "to": "solar-south",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-13",+ "from": "solar-south",+ "to": "foundry-south",+ "width": 10,+ "kind": "bridge",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-14",+ "from": "foundry-south",+ "to": "mine-south",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-15",+ "from": "hub-east",+ "to": "memory-west",+ "width": 10,+ "kind": "bridge",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-16",+ "from": "memory-west",+ "to": "mine-south",+ "width": 10,+ "kind": "bridge",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-17",+ "from": "hub-west",+ "to": "harbor-east",+ "width": 10,+ "kind": "bridge",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-18",+ "from": "hub-west",+ "to": "central-northwest",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-19",+ "from": "hub-north",+ "to": "central-northeast",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-20",+ "from": "hub-east",+ "to": "central-southeast",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-21",+ "from": "hub-south",+ "to": "central-southwest",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-22",+ "from": "central-northwest",+ "to": "hub-north",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-23",+ "from": "central-northeast",+ "to": "hub-east",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-24",+ "from": "central-southeast",+ "to": "hub-south",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-25",+ "from": "central-southwest",+ "to": "hub-west",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "rover-a-access-1",+ "from": "outpost-arrival",+ "to": "rover-a-shoulder",+ "width": 1.2,+ "kind": "footpath",+ "modes": [+ "pedestrian"+ ],+ "stage": "blockout",+ "surface_id": "route-05",+ "render": false,+ "resource_ids": [+ "corridor:route05-lead"+ ]+ },+ {+ "id": "rover-a-access-2",+ "from": "rover-a-shoulder",+ "to": "rover-a-board",+ "width": 1.2,+ "kind": "footpath",+ "modes": [+ "pedestrian"+ ],+ "stage": "blockout",+ "surface_id": "route-05",+ "render": false+ },+ {+ "id": "rover-a-access-3",+ "from": "rover-a-board",+ "to": "rover-a-exit",+ "width": 1.2,+ "kind": "footpath",+ "modes": [+ "pedestrian"+ ],+ "stage": "blockout",+ "surface_id": "route-05",+ "render": false+ },+ {+ "id": "rover-a-access-4",+ "from": "outpost-arrival",+ "to": "rover-a-alternate-shoulder",+ "width": 1.2,+ "kind": "footpath",+ "modes": [+ "pedestrian"+ ],+ "stage": "blockout",+ "surface_id": "route-05",+ "render": false,+ "resource_ids": [+ "corridor:route05-lead"+ ]+ },+ {+ "id": "rover-a-access-5",+ "from": "rover-a-alternate-shoulder",+ "to": "rover-a-alternate",+ "width": 1.2,+ "kind": "footpath",+ "modes": [+ "pedestrian"+ ],+ "stage": "blockout",+ "surface_id": "route-05",+ "render": false,+ "resource_ids": [+ "corridor:route05-lead"+ ]+ },+ {+ "id": "rover-b-access-1",+ "from": "outpost-south",+ "to": "rover-b-shoulder",+ "width": 1.2,+ "kind": "footpath",+ "modes": [+ "pedestrian"+ ],+ "stage": "blockout",+ "surface_id": "route-05",+ "render": false,+ "resource_ids": [+ "corridor:route05-tail"+ ]+ },+ {+ "id": "rover-b-access-2",+ "from": "rover-b-shoulder",+ "to": "rover-b-exit",+ "width": 1.2,+ "kind": "footpath",+ "modes": [+ "pedestrian"+ ],+ "stage": "blockout",+ "surface_id": "route-05",+ "render": false+ },+ {+ "id": "rover-b-access-3",+ "from": "rover-b-board",+ "to": "rover-b-exit",+ "width": 1.2,+ "kind": "footpath",+ "modes": [+ "pedestrian"+ ],+ "stage": "blockout",+ "surface_id": "route-05",+ "render": false+ },+ {+ "id": "rover-b-access-4",+ "from": "outpost-south",+ "to": "rover-b-alternate-shoulder",+ "width": 1.2,+ "kind": "footpath",+ "modes": [+ "pedestrian"+ ],+ "stage": "blockout",+ "surface_id": "route-05",+ "render": false,+ "resource_ids": [+ "corridor:route05-tail"+ ]+ },+ {+ "id": "rover-b-access-5",+ "from": "rover-b-alternate-shoulder",+ "to": "rover-b-alternate",+ "width": 1.2,+ "kind": "footpath",+ "modes": [+ "pedestrian"+ ],+ "stage": "blockout",+ "surface_id": "route-05",+ "render": false+ },+ {+ "id": "route-05-lead",+ "from": "outpost-arrival",+ "to": "rover-a-dock",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout",+ "surface_id": "route-05",+ "resource_ids": [+ "corridor:route05-lead",+ "clearance:rover-a"+ ]+ },+ {+ "id": "route-05-ride",+ "from": "rover-a-dock",+ "to": "rover-b-dock",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout",+ "surface_id": "route-05",+ "resource_ids": [+ "clearance:rover-a",+ "clearance:rover-b"+ ]+ },+ {+ "id": "route-05-tail",+ "from": "rover-b-dock",+ "to": "outpost-south",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout",+ "surface_id": "route-05",+ "resource_ids": [+ "corridor:route05-tail",+ "clearance:rover-b"+ ]+ }+ ],+ "destinations": [+ {+ "id": "outpost-approach",+ "name": "Outpost approach",+ "anchor": "console-approach",+ "capacity": 1+ },+ {+ "id": "outpost-bridge-staging",+ "name": "Outpost bridge staging",+ "anchor": "outpost-west",+ "capacity": 1+ },+ {+ "id": "rover-a-board",+ "name": "Rover A board",+ "anchor": "rover-a-board",+ "capacity": 1+ },+ {+ "id": "rover-a-exit",+ "name": "Rover A exit",+ "anchor": "rover-a-exit",+ "capacity": 1+ },+ {+ "id": "rover-a-alternate",+ "name": "Rover A alternate",+ "anchor": "rover-a-alternate",+ "capacity": 1+ },+ {+ "id": "rover-b-board",+ "name": "Rover B board",+ "anchor": "rover-b-board",+ "capacity": 1+ },+ {+ "id": "rover-b-exit",+ "name": "Rover B exit",+ "anchor": "rover-b-exit",+ "capacity": 1+ },+ {+ "id": "rover-b-alternate",+ "name": "Rover B alternate",+ "anchor": "rover-b-alternate",+ "capacity": 1+ }+ ],+ "surface_edges": [+ {+ "id": "route-01",+ "from": "hub-east",+ "to": "outpost-west",+ "width": 10,+ "kind": "bridge",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-02",+ "from": "outpost-west",+ "to": "outpost-arrival",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-03",+ "from": "outpost-arrival",+ "to": "console-approach",+ "width": 4,+ "kind": "footpath",+ "modes": [+ "pedestrian"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-04",+ "from": "console-approach",+ "to": "console",+ "width": 2.4,+ "kind": "interior",+ "modes": [+ "pedestrian"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-05",+ "from": "outpost-arrival",+ "to": "outpost-south",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-06",+ "from": "outpost-south",+ "to": "gardens-east",+ "width": 10,+ "kind": "bridge",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-07",+ "from": "hub-south",+ "to": "gardens-north",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-08",+ "from": "gardens-north",+ "to": "gardens-east",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-09",+ "from": "harbor-east",+ "to": "gardens-north",+ "width": 10,+ "kind": "bridge",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-10",+ "from": "hub-west",+ "to": "water-east",+ "width": 10,+ "kind": "bridge",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-11",+ "from": "hub-west",+ "to": "workshop-south",+ "width": 10,+ "kind": "bridge",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-12",+ "from": "hub-north",+ "to": "solar-south",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-13",+ "from": "solar-south",+ "to": "foundry-south",+ "width": 10,+ "kind": "bridge",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-14",+ "from": "foundry-south",+ "to": "mine-south",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-15",+ "from": "hub-east",+ "to": "memory-west",+ "width": 10,+ "kind": "bridge",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-16",+ "from": "memory-west",+ "to": "mine-south",+ "width": 10,+ "kind": "bridge",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-17",+ "from": "hub-west",+ "to": "harbor-east",+ "width": 10,+ "kind": "bridge",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-18",+ "from": "hub-west",+ "to": "central-northwest",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-19",+ "from": "hub-north",+ "to": "central-northeast",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-20",+ "from": "hub-east",+ "to": "central-southeast",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-21",+ "from": "hub-south",+ "to": "central-southwest",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-22",+ "from": "central-northwest",+ "to": "hub-north",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-23",+ "from": "central-northeast",+ "to": "hub-east",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-24",+ "from": "central-southeast",+ "to": "hub-south",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-25",+ "from": "central-southwest",+ "to": "hub-west",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ }+ ],+ "graph_migrations": [+ {+ "source_signature": "9cfc77d4978d54f23b6d97d815fe5e1afcb309f328b78016f919a9ef66d186a5",+ "source_descriptor": {+ "navigation": {+ "version": 1,+ "nodes": [+ {+ "id": "hub-east",+ "position": [+ 125,+ 48,+ 40+ ]+ },+ {+ "id": "outpost-west",+ "position": [+ 256,+ 58,+ 50+ ]+ },+ {+ "id": "outpost-arrival",+ "position": [+ 268,+ 58,+ 68+ ]+ },+ {+ "id": "console-approach",+ "position": [+ 294,+ 58,+ 75+ ]+ },+ {+ "id": "console",+ "position": [+ 294,+ 58,+ 64+ ]+ },+ {+ "id": "outpost-south",+ "position": [+ 325,+ 58,+ 96+ ]+ },+ {+ "id": "gardens-east",+ "position": [+ 185,+ 36,+ 300+ ]+ },+ {+ "id": "hub-south",+ "position": [+ 0,+ 48,+ 109+ ]+ },+ {+ "id": "gardens-north",+ "position": [+ 80,+ 36,+ 234+ ]+ },+ {+ "id": "harbor-east",+ "position": [+ -137,+ 25,+ 240+ ]+ },+ {+ "id": "hub-west",+ "position": [+ -128,+ 48,+ 20+ ]+ },+ {+ "id": "water-east",+ "position": [+ -251,+ 42,+ -10+ ]+ },+ {+ "id": "workshop-south",+ "position": [+ -230,+ 66,+ -111+ ]+ },+ {+ "id": "hub-north",+ "position": [+ 0,+ 48,+ -110+ ]+ },+ {+ "id": "solar-south",+ "position": [+ -25,+ 58,+ -129+ ]+ },+ {+ "id": "foundry-south",+ "position": [+ -30,+ 92,+ -220+ ]+ },+ {+ "id": "mine-south",+ "position": [+ 150,+ 80,+ -180+ ]+ },+ {+ "id": "memory-west",+ "position": [+ 185,+ 70,+ -160+ ]+ },+ {+ "id": "central-northwest",+ "position": [+ -128,+ 48,+ -110+ ]+ },+ {+ "id": "central-northeast",+ "position": [+ 125,+ 48,+ -110+ ]+ },+ {+ "id": "central-southeast",+ "position": [+ 125,+ 48,+ 109+ ]+ },+ {+ "id": "central-southwest",+ "position": [+ -128,+ 48,+ 109+ ]+ }+ ],+ "edges": [+ {+ "id": "route-01",+ "from": "hub-east",+ "to": "outpost-west",+ "width": 10,+ "kind": "bridge",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-02",+ "from": "outpost-west",+ "to": "outpost-arrival",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-03",+ "from": "outpost-arrival",+ "to": "console-approach",+ "width": 4,+ "kind": "footpath",+ "modes": [+ "pedestrian"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-04",+ "from": "console-approach",+ "to": "console",+ "width": 2.4,+ "kind": "interior",+ "modes": [+ "pedestrian"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-05",+ "from": "outpost-arrival",+ "to": "outpost-south",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-06",+ "from": "outpost-south",+ "to": "gardens-east",+ "width": 10,+ "kind": "bridge",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-07",+ "from": "hub-south",+ "to": "gardens-north",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-08",+ "from": "gardens-north",+ "to": "gardens-east",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-09",+ "from": "harbor-east",+ "to": "gardens-north",+ "width": 10,+ "kind": "bridge",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-10",+ "from": "hub-west",+ "to": "water-east",+ "width": 10,+ "kind": "bridge",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-11",+ "from": "hub-west",+ "to": "workshop-south",+ "width": 10,+ "kind": "bridge",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-12",+ "from": "hub-north",+ "to": "solar-south",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-13",+ "from": "solar-south",+ "to": "foundry-south",+ "width": 10,+ "kind": "bridge",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-14",+ "from": "foundry-south",+ "to": "mine-south",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-15",+ "from": "hub-east",+ "to": "memory-west",+ "width": 10,+ "kind": "bridge",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-16",+ "from": "memory-west",+ "to": "mine-south",+ "width": 10,+ "kind": "bridge",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-17",+ "from": "hub-west",+ "to": "harbor-east",+ "width": 10,+ "kind": "bridge",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-18",+ "from": "hub-west",+ "to": "central-northwest",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-19",+ "from": "hub-north",+ "to": "central-northeast",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-20",+ "from": "hub-east",+ "to": "central-southeast",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-21",+ "from": "hub-south",+ "to": "central-southwest",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-22",+ "from": "central-northwest",+ "to": "hub-north",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-23",+ "from": "central-northeast",+ "to": "hub-east",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-24",+ "from": "central-southeast",+ "to": "hub-south",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-25",+ "from": "central-southwest",+ "to": "hub-west",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ }+ ],+ "destinations": [+ {+ "id": "outpost-approach",+ "name": "Outpost approach",+ "anchor": "console-approach",+ "capacity": 1+ },+ {+ "id": "outpost-bridge-staging",+ "name": "Outpost bridge staging",+ "anchor": "outpost-west",+ "capacity": 1+ }+ ]+ },+ "stations": [+ {+ "id": "communications-console",+ "district_id": "communications-outpost",+ "building_id": "operations",+ "checkpoint": "hub:comms",+ "capability": "communication-draft",+ "capacity": 1,+ "anchor": "console"+ }+ ],+ "spawn": {+ "position": [+ 268,+ 58,+ 68+ ],+ "yaw": 1.5707963267948966+ }+ },+ "edge_splits": {+ "route-05": [+ "route-05-lead",+ "route-05-ride",+ "route-05-tail"+ ]+ }+ }+ ],+ "rover_docks": [+ {+ "id": "outpost-a",+ "name": "Operations approach",+ "node_id": "rover-a-dock",+ "boarding_station_id": "rover-a-board",+ "exit_station_ids": [+ "rover-a-exit",+ "rover-a-alternate"+ ],+ "yaw": 1.1141908549024027+ },+ {+ "id": "outpost-b",+ "name": "South overlook",+ "node_id": "rover-b-dock",+ "boarding_station_id": "rover-b-board",+ "exit_station_ids": [+ "rover-b-exit",+ "rover-b-alternate"+ ],+ "yaw": 1.1141908549024027+ }+ ],+ "rovers": [+ {+ "id": "outpost-rover",+ "home_dock_id": "outpost-a",+ "seat_capacity": 1,+ "width_m": 3.4,+ "length_m": 4.8,+ "height_m": 2.6,+ "speed_m_s": 4+ }+ ],+ "collision": {+ "version": 1,+ "source_sha256": "ce64fbcbf1815245e9352f35b0cd6c2b3148acc747bca2e9d53808130e2a0ace",+ "solid_boxes": [+ {+ "id": "outpost:communications-mast",+ "min": [+ 313.0,+ 58.0,+ 39.0+ ],+ "max": [+ 327.0,+ 120.0,+ 53.0+ ]+ },+ {+ "id": "outpost:dish-west base",+ "min": [+ 271.435,+ 58.0,+ 39.435+ ],+ "max": [+ 284.565,+ 67.0,+ 52.565+ ]+ },+ {+ "id": "outpost:dish-east base",+ "min": [+ 343.2,+ 58.0,+ 13.2+ ],+ "max": [+ 358.8,+ 67.0,+ 28.8+ ]+ },+ {+ "id": "outpost:radome-north",+ "min": [+ 289.5,+ 58.0,+ 12.5+ ],+ "max": [+ 306.5,+ 75.0,+ 29.5+ ]+ },+ {+ "id": "outpost:radome-south",+ "min": [+ 340.8,+ 58.0,+ 58.8+ ],+ "max": [+ 361.2,+ 76.0,+ 79.2+ ]+ },+ {+ "id": "outpost:operations-west",+ "min": [+ 284.0,+ 58.0,+ 57.0+ ],+ "max": [+ 284.38,+ 66.0,+ 71.0+ ]+ },+ {+ "id": "outpost:operations-east",+ "min": [+ 303.62,+ 58.0,+ 57.0+ ],+ "max": [+ 304.0,+ 66.0,+ 71.0+ ]+ },+ {+ "id": "outpost:operations-north",+ "min": [+ 284.0,+ 58.0,+ 57.0+ ],+ "max": [+ 304.0,+ 66.0,+ 57.379999999999995+ ]+ },+ {+ "id": "outpost:operations-south-west",+ "min": [+ 284.0,+ 58.0,+ 70.62+ ],+ "max": [+ 292.5,+ 66.0,+ 71.0+ ]+ },+ {+ "id": "outpost:operations-south-east",+ "min": [+ 295.5,+ 58.0,+ 70.62+ ],+ "max": [+ 304.0,+ 66.0,+ 71.0+ ]+ },+ {+ "id": "outpost:operations-lintel",+ "min": [+ 292.5,+ 61.0,+ 70.62+ ],+ "max": [+ 295.5,+ 66.0,+ 71.0+ ]+ },+ {+ "id": "outpost:operations-jamb-west",+ "min": [+ 292.5,+ 58.0,+ 70.7+ ],+ "max": [+ 292.79999999999995,+ 61.0,+ 71.3+ ]+ },+ {+ "id": "outpost:operations-jamb-east",+ "min": [+ 295.20000000000005,+ 58.0,+ 70.7+ ],+ "max": [+ 295.5,+ 61.0,+ 71.3+ ]+ },+ {+ "id": "outpost:operations-roof",+ "min": [+ 284.0,+ 65.6,+ 57.0+ ],+ "max": [+ 304.0,+ 66.0,+ 71.0+ ]+ },+ {+ "id": "outpost:console-desk",+ "min": [+ 291.3,+ 58.0,+ 60.35+ ],+ "max": [+ 296.7,+ 59.7,+ 61.85+ ]+ },+ {+ "id": "outpost:equipment-rack--7.3",+ "min": [+ 285.8,+ 58.0,+ 58.550000000000004+ ],+ "max": [+ 287.59999999999997,+ 60.7,+ 59.85+ ]+ },+ {+ "id": "outpost:equipment-rack-7.3",+ "min": [+ 300.40000000000003,+ 58.0,+ 58.550000000000004+ ],+ "max": [+ 302.2,+ 60.7,+ 59.85+ ]+ },+ {+ "id": "outpost:service-east",+ "min": [+ 357.0,+ 58.0,+ 39.0+ ],+ "max": [+ 369.0,+ 70.0,+ 51.0+ ]+ },+ {+ "id": "outpost:service-module-0",+ "min": [+ 319.0,+ 58.0,+ 22.5+ ],+ "max": [+ 327.0,+ 63.0,+ 29.5+ ]+ },+ {+ "id": "outpost:service-module-1",+ "min": [+ 330.0,+ 58.0,+ 22.5+ ],+ "max": [+ 338.0,+ 63.0,+ 29.5+ ]+ },+ {+ "id": "outpost:service-module-2",+ "min": [+ 329.0,+ 58.0,+ 66.5+ ],+ "max": [+ 337.0,+ 63.0,+ 73.5+ ]+ },+ {+ "id": "outpost:district-sign",+ "min": [+ 334.5,+ 58.25,+ 84.75+ ],+ "max": [+ 359.5,+ 61.75,+ 85.25+ ]+ }+ ],+ "support_surfaces": [+ {+ "id": "outpost:plateau",+ "polygon": [+ [+ 379.19163409438966,+ 50.0+ ],+ [+ 381.7492419347785,+ 58.514104199157146+ ],+ [+ 381.03500148354226,+ 62.59773149092457+ ],+ [+ 379.67266156242977,+ 65.61855150291954+ ],+ [+ 379.7138129811923,+ 68.5285314444432+ ],+ [+ 379.30010118534335,+ 71.03260979086602+ ],+ [+ 378.1277633525924,+ 73.03831634746953+ ],+ [+ 378.03849366748466,+ 75.3147658224957+ ],+ [+ 375.7582675104747,+ 76.47535138798723+ ],+ [+ 376.5920862573003,+ 79.02009076235758+ ],+ [+ 376.0353986202004,+ 80.84748377192284+ ],+ [+ 375.3453245155374,+ 82.56036857604752+ ],+ [+ 372.84886548328643,+ 83.11431138481073+ ],+ [+ 374.619411079832,+ 86.35841802338464+ ],+ [+ 371.8664668879266,+ 86.61419465719865+ ],+ [+ 371.8477631042101,+ 88.77066420610154+ ],+ [+ 369.0427710204593,+ 88.82552705786364+ ],+ [+ 368.5391304378219,+ 90.68211219407127+ ],+ [+ 366.4757798300741,+ 91.26183928516427+ ],+ [+ 364.305907776994,+ 91.71462965746207+ ],+ [+ 362.1056707359226,+ 92.1158188329598+ ],+ [+ 359.15382820533574,+ 91.71099744219333+ ],+ [+ 357.44787241673714,+ 92.63385347604682+ ],+ [+ 357.24984033273296,+ 95.52668955958615+ ],+ [+ 355.0163627172807,+ 96.21929204878478+ ],+ [+ 351.8229780248019,+ 95.72647836343249+ ],+ [+ 350.03576699714756,+ 97.49592171667565+ ],+ [+ 347.24440458962243,+ 98.14202004449209+ ],+ [+ 344.0354146019505,+ 98.54786562306265+ ],+ [+ 340.18614863807016,+ 98.33623732169764+ ],+ [+ 335.6906457592861,+ 97.64443136971514+ ],+ [+ 330.14088995768566,+ 96.09496164452219+ ],+ [+ 320.0000000235387,+ 97.19276845121112+ ],+ [+ 309.92320260553623,+ 95.8036317656123+ ],+ [+ 304.3860817789598,+ 97.41144924863454+ ],+ [+ 300.6171020382319,+ 96.4128335058094+ ],+ [+ 296.8428624194162,+ 96.7738802136463+ ],+ [+ 293.5014243136735,+ 96.82410869524162+ ],+ [+ 290.7775180055971,+ 96.20986430294711+ ],+ [+ 287.26739559252616,+ 97.03352169148432+ ],+ [+ 284.624027589598,+ 96.69395315405563+ ],+ [+ 283.84745624424954,+ 94.1855756066445+ ],+ [+ 282.342651256897,+ 92.87233920109944+ ],+ [+ 280.41092477246457,+ 92.1746708111034+ ],+ [+ 278.78852878478403,+ 91.22140379678106+ ],+ [+ 275.63221416488017,+ 91.77288871157364+ ],+ [+ 274.9874496692863,+ 89.96276392460727+ ],+ [+ 272.81910058089176,+ 89.54373772814304+ ],+ [+ 271.2700169517463,+ 88.57790324653419+ ],+ [+ 268.8458597107479,+ 88.25198768788074+ ],+ [+ 268.25172461805664,+ 86.53075950021659+ ],+ [+ 266.2331971354765,+ 85.79086364501453+ ],+ [+ 267.0127497612887,+ 83.20102120989677+ ],+ [+ 266.65856938990567,+ 81.38145193368136+ ],+ [+ 265.43898673473666,+ 80.03583471739847+ ],+ [+ 265.4497731571428,+ 77.97303719974983+ ],+ [+ 262.8192600737334,+ 77.15077511848128+ ],+ [+ 262.0322551730263,+ 75.28390715927802+ ],+ [+ 262.9883953175588,+ 72.59593881470717+ ],+ [+ 259.223786114948,+ 71.55615868538268+ ],+ [+ 260.0695071914646,+ 68.59576478282621+ ],+ [+ 258.60779132628915,+ 66.06862083812328+ ],+ [+ 258.00916191438665,+ 62.79501784415481+ ],+ [+ 259.32424234087335,+ 58.36609012331292+ ],+ [+ 259.3495762567311,+ 50.000000028341475+ ],+ [+ 260.5964479323404,+ 41.809324029624264+ ],+ [+ 260.1438254971525,+ 37.64558046805121+ ],+ [+ 262.5032946937482,+ 34.95097705446951+ ],+ [+ 261.7596479107917,+ 31.928667068032997+ ],+ [+ 261.5948166400917,+ 29.284800416553985+ ],+ [+ 262.4710933812729,+ 27.199034104119573+ ],+ [+ 260.6006289453545,+ 24.091657566669426+ ],+ [+ 262.9462386735701,+ 22.909517340368904+ ],+ [+ 262.5646990164183,+ 20.547513658910997+ ],+ [+ 264.03700001067955,+ 19.19237167028285+ ],+ [+ 263.85775316965555,+ 16.97079174284609+ ],+ [+ 265.78417245795464,+ 16.029170564120022+ ],+ [+ 267.93078701319394,+ 15.33916835617471+ ],+ [+ 270.02807886435204,+ 14.723225667011768+ ],+ [+ 271.195626916927,+ 13.505118691620538+ ],+ [+ 270.8154598788249,+ 11.062239070736403+ ],+ [+ 271.77760065367204,+ 9.583349706116927+ ],+ [+ 273.49216678942435,+ 8.709703280885485+ ],+ [+ 274.5029255957228,+ 7.1638703618232+ ],+ [+ 276.18553705139044,+ 6.174977109846587+ ],+ [+ 279.0339182950227,+ 6.358389267792468+ ],+ [+ 280.4545394761706,+ 4.978073230611699+ ],+ [+ 284.11531714728227,+ 6.141803519509949+ ],+ [+ 286.6072020861511,+ 5.923706537784902+ ],+ [+ 288.9206790224664,+ 5.342083411497079+ ],+ [+ 290.8615363029251,+ 3.9229948470469864+ ],+ [+ 294.2540217761467,+ 4.505762985551868+ ],+ [+ 296.998541863548,+ 3.5405684804641524+ ],+ [+ 299.9962777661018,+ 2.1005872615302934+ ],+ [+ 304.3640355418862,+ 2.521607653845521+ ],+ [+ 309.4140918179079,+ 1.8822279245663438+ ],+ [+ 319.99999995347287,+ 0.674740860932836+ ],+ [+ 330.42279299555577,+ 2.623660707922049+ ],+ [+ 336.1069664978563,+ 1.091416398381888+ ],+ [+ 339.3572787372233,+ 3.648512367531737+ ],+ [+ 342.7642959204728,+ 4.019599925642176+ ],+ [+ 345.5890146967183,+ 4.7831242046135+ ],+ [+ 348.82367794470844,+ 4.4207693654516405+ ],+ [+ 351.64372982649695,+ 4.531083605000639+ ],+ [+ 354.31818703595144,+ 4.70225385754631+ ],+ [+ 357.4039036178342,+ 4.285014563419921+ ],+ [+ 359.3380272047489,+ 5.214233021835845+ ],+ [+ 361.55706533165505,+ 5.728808006633024+ ],+ [+ 363.0557045872154,+ 6.933918343365669+ ],+ [+ 364.25556995259376,+ 8.332764105762173+ ],+ [+ 365.4836023944597,+ 9.619029546738517+ ],+ [+ 367.05382794706486,+ 10.562764712994756+ ],+ [+ 368.37220519760007,+ 11.705337551899916+ ],+ [+ 369.3847115416682,+ 13.071153826851791+ ],+ [+ 371.1026615972322,+ 13.924999879689885+ ],+ [+ 371.7240152171838,+ 15.568955616061515+ ],+ [+ 372.9811525519948,+ 16.80279950971211+ ],+ [+ 374.4680274538123,+ 17.955756605808368+ ],+ [+ 375.31635820191013,+ 19.548347937688114+ ],+ [+ 377.47521835954484,+ 20.52704426203846+ ],+ [+ 379.62332048963174,+ 21.68942954360917+ ],+ [+ 378.8969662617972,+ 24.310792469651567+ ],+ [+ 379.63839298941355,+ 26.362961777652128+ ],+ [+ 379.1311621599627,+ 29.027309644822214+ ],+ [+ 379.07198808562094,+ 31.67061967597117+ ],+ [+ 377.65811895381694,+ 34.90872910873081+ ],+ [+ 380.19804747358233,+ 37.57501728652195+ ],+ [+ 380.37226430933055,+ 41.67575612326357+ ]+ ],+ "plane": [+ 0,+ 0,+ 57.88+ ]+ },+ {+ "id": "outpost:terrace",+ "polygon": [+ [+ 375.0,+ 78.0+ ],+ [+ 374.88022805923333,+ 79.82736669108073+ ],+ [+ 374.522961568047,+ 81.62346663143529+ ],+ [+ 373.934313455158,+ 83.35756805311127+ ],+ [+ 373.12435565298216,+ 85.0+ ],+ [+ 372.1069467640773,+ 86.5226600061221+ ],+ [+ 370.8994949366117,+ 87.89949493661166+ ],+ [+ 369.52266000612207,+ 89.10694676407729+ ],+ [+ 368.0,+ 90.12435565298213+ ],+ [+ 366.35756805311127,+ 90.93431345515802+ ],+ [+ 364.6234666314353,+ 91.52296156804695+ ],+ [+ 362.8273666910807,+ 91.88022805923335+ ],+ [+ 361.0,+ 92.0+ ],+ [+ 279.0,+ 92.0+ ],+ [+ 277.1726333089193,+ 91.88022805923335+ ],+ [+ 275.3765333685647,+ 91.52296156804695+ ],+ [+ 273.64243194688873,+ 90.93431345515802+ ],+ [+ 272.0,+ 90.12435565298215+ ],+ [+ 270.47733999387793,+ 89.10694676407729+ ],+ [+ 269.10050506338837,+ 87.89949493661166+ ],+ [+ 267.8930532359227,+ 86.5226600061221+ ],+ [+ 266.87564434701784,+ 85.0+ ],+ [+ 266.065686544842,+ 83.35756805311127+ ],+ [+ 265.477038431953,+ 81.62346663143529+ ],+ [+ 265.11977194076667,+ 79.82736669108073+ ],+ [+ 265.0,+ 78.0+ ],+ [+ 265.0,+ 22.0+ ],+ [+ 265.11977194076667,+ 20.17263330891928+ ],+ [+ 265.477038431953,+ 18.376533368564708+ ],+ [+ 266.065686544842,+ 16.642431946888742+ ],+ [+ 266.87564434701784,+ 15.0+ ],+ [+ 267.8930532359227,+ 13.477339993877912+ ],+ [+ 269.1005050633883,+ 12.10050506338834+ ],+ [+ 270.4773399938779,+ 10.893053235922707+ ],+ [+ 272.0,+ 9.875644347017861+ ],+ [+ 273.64243194688873,+ 9.06568654484198+ ],+ [+ 275.3765333685647,+ 8.477038431953048+ ],+ [+ 277.1726333089193,+ 8.119771940766654+ ],+ [+ 279.0,+ 8.0+ ],+ [+ 361.0,+ 8.0+ ],+ [+ 362.8273666910807,+ 8.119771940766654+ ],+ [+ 364.6234666314353,+ 8.47703843195304+ ],+ [+ 366.35756805311127,+ 9.065686544841988+ ],+ [+ 368.0,+ 9.875644347017861+ ],+ [+ 369.52266000612207,+ 10.893053235922707+ ],+ [+ 370.89949493661163,+ 12.100505063388333+ ],+ [+ 372.1069467640773,+ 13.477339993877905+ ],+ [+ 373.12435565298216,+ 14.999999999999993+ ],+ [+ 373.934313455158,+ 16.64243194688875+ ],+ [+ 374.522961568047,+ 18.37653336856471+ ],+ [+ 374.88022805923333,+ 20.172633308919277+ ],+ [+ 375.0,+ 21.999999999999996+ ]+ ],+ "plane": [+ 0,+ 0,+ 57.97+ ]+ },+ {+ "id": "outpost:route-01",+ "polygon": [+ [+ 124.6194278287001,+ 44.985495444028814+ ],+ [+ 125.3805721712999,+ 35.014504555971186+ ],+ [+ 256.3805721712999,+ 45.014504555971186+ ],+ [+ 255.61942782870008,+ 54.985495444028814+ ]+ ],+ "plane": [+ 0.07589363304559411,+ 0.005793407102717108,+ 38.28155958519205+ ]+ },+ {+ "id": "outpost:route-02",+ "polygon": [+ [+ 251.8397485283108,+ 52.77350098112615+ ],+ [+ 260.1602514716892,+ 47.22649901887385+ ],+ [+ 272.1602514716892,+ 65.22649901887385+ ],+ [+ 263.8397485283108,+ 70.77350098112615+ ]+ ],+ "plane": [+ 0.0,+ 0.0,+ 58.006+ ]+ },+ {+ "id": "outpost:route-03",+ "polygon": [+ [+ 267.48005305310426,+ 69.93123151704134+ ],+ [+ 268.51994694689574,+ 66.06876848295866+ ],+ [+ 294.51994694689574,+ 73.06876848295866+ ],+ [+ 293.48005305310426,+ 76.93123151704134+ ]+ ],+ "plane": [+ 0.0,+ 0.0,+ 58.006+ ]+ },+ {+ "id": "outpost:route-05",+ "polygon": [+ [+ 265.79548060173266,+ 72.48777163218708+ ],+ [+ 270.20451939826734,+ 63.512228367812924+ ],+ [+ 327.20451939826734,+ 91.51222836781292+ ],+ [+ 322.79548060173266,+ 100.48777163218708+ ]+ ],+ "plane": [+ 0.0,+ 0.0,+ 58.006+ ]+ }+ ]+ }+ },+ "stations": [+ {+ "id": "communications-console",+ "district_id": "communications-outpost",+ "building_id": "operations",+ "checkpoint": "hub:comms",+ "capability": "communication-draft",+ "capacity": 1,+ "anchor": "console"+ }+ ],+ "spawn": {+ "position": [+ 268,+ 58,+ 68+ ],+ "yaw": 1.5707963267948966+ },+ "view": {+ "near_inspection_m": 0.75,+ "overview_padding": 1.15+ }+}diff --git a/jarvis/society/mars/definition.py b/jarvis/society/mars/definition.pynew file mode 100644index 0000000000..6d0704444d--- /dev/null+++ b/jarvis/society/mars/definition.py@@ -0,0 +1,214 @@+"""Packaged canonical Mars layout, independent of rendering and authoring tools."""++from __future__ import annotations++import json+import math+from importlib.resources import files+from typing import Any++from .mobility_geometry import MobilityGeometry+++def validate_definition(data: dict[str, Any]) -> None:+ """Reject inconsistent layout/route identities before either client uses them."""+ if data.get("schema_version") != 1 or data.get("layout_version") != 1:+ raise ValueError("unsupported Mars definition version")+ if data.get("world_id") != "mars:ordinary" or data.get("units") != "metres":+ raise ValueError("unsupported Mars world scope or units")+ bounds = data["bounds"]++ def vector(value: Any) -> None:+ if (+ not isinstance(value, list)+ or len(value) != 3+ or any(+ isinstance(v, bool) or not isinstance(v, (int, float)) or not math.isfinite(v)+ for v in value+ )+ ):+ raise ValueError("expected a finite three-dimensional position")++ vector(bounds["min"])+ vector(bounds["max"])+ if any(a >= b for a, b in zip(bounds["min"], bounds["max"], strict=True)):+ raise ValueError("invalid world bounds")++ def position(value: Any) -> None:+ vector(value)+ if any(+ v < lo or v > hi for v, lo, hi in zip(value, bounds["min"], bounds["max"], strict=True)+ ):+ raise ValueError("position lies outside world bounds")++ def index(rows: list[dict[str, Any]]) -> dict[str, dict[str, Any]]:+ result = {row["id"]: row for row in rows}+ if len(rows) != len(result) or any(not key for key in result):+ raise ValueError("duplicate or empty world identity")+ return result++ districts = index(data["districts"])+ for district in districts.values():+ position(district["center"])+ position(+ [+ district["center"][0],+ district["center"][1] + district["landmark_height"],+ district["center"][2],+ ]+ )+ buildings = index(data["buildings"])+ for building in buildings.values():+ if building["district_id"] not in districts:+ raise ValueError("building references an unknown district")+ position(building["position"])+ vector(building["size"])+ if min(building["size"]) <= 0:+ raise ValueError("building dimensions must be positive")+ for sign in (-1, 1):+ position(+ [+ building["position"][0] + sign * building["size"][0] / 2,+ building["position"][1] + (building["size"][1] if sign == 1 else 0),+ building["position"][2] + sign * building["size"][2] / 2,+ ]+ )+ navigation = data["navigation"]+ if navigation["version"] != data["layout_version"]:+ raise ValueError("navigation and layout versions differ")+ nodes = index(navigation["nodes"])+ edges = index(navigation["edges"])+ adjacent: dict[str, set[str]] = {key: set() for key in nodes}+ for node in nodes.values():+ position(node["position"])+ for edge in edges.values():+ start, end = edge["from"], edge["to"]+ if start not in nodes or end not in nodes or start == end:+ raise ValueError("route references an invalid endpoint")+ width = edge["width"]+ if not isinstance(width, (int, float)) or not math.isfinite(width) or width <= 0:+ raise ValueError("route width must be positive")+ if "pedestrian" not in edge["modes"]:+ raise ValueError("colony routes must retain pedestrian access")+ if "rover" in edge["modes"] and width < 7:+ raise ValueError("rover route lacks required clearance")+ adjacent[start].add(end)+ adjacent[end].add(start)+ if not nodes:+ raise ValueError("world requires navigation nodes")+ visited: set[str] = set()+ pending = [next(iter(nodes))]+ while pending:+ key = pending.pop()+ if key not in visited:+ visited.add(key)+ pending.extend(adjacent[key] - visited)+ if visited != set(nodes):+ raise ValueError("colony navigation contains a disconnected route")+ stations = index(data["stations"])+ for station in stations.values():+ building = buildings.get(station["building_id"])+ if (+ building is None+ or building["district_id"] != station["district_id"]+ or station["anchor"] not in visited+ or station["capacity"] != 1+ ):+ raise ValueError("invalid station location or capacity")+ destinations = index(navigation.get("destinations", []))+ if stations.keys() & destinations.keys() or len(stations) + len(destinations) > 64:+ raise ValueError("invalid bounded navigation destination identities")+ for destination in destinations.values():+ if (+ destination["anchor"] not in visited+ or type(destination["capacity"]) is not int+ or destination["capacity"] != 1+ or not isinstance(destination.get("name"), str)+ or not destination["name"].strip()+ or set(destination) != {"id", "name", "anchor", "capacity"}+ ):+ raise ValueError("invalid visit-only destination")+ for row in [*nodes.values(), *edges.values()]:+ resources = row.get("resource_ids", [])+ if (+ not isinstance(resources, list)+ or len(resources) > 16+ or len(set(resources)) != len(resources)+ or any(not isinstance(key, str) or not key or len(key) > 128 for key in resources)+ ):+ raise ValueError("invalid shared physical resource identities")+ rovers = index(navigation.get("rovers", []))+ docks = index(navigation.get("rover_docks", []))+ if bool(rovers) != bool(docks) or len(rovers) > 8 or len(docks) > 16:+ raise ValueError("invalid bounded rover catalog")+ if rovers:+ geometry = MobilityGeometry(data)+ visits = {**stations, **destinations}+ surface_edges = index(navigation["surface_edges"])+ for edge in surface_edges.values():+ if edge["from"] not in nodes or edge["to"] not in nodes:+ raise ValueError("unknown authored road endpoint")+ for dock in docks.values():+ if dock["node_id"] not in nodes or dock["boarding_station_id"] not in visits:+ raise ValueError("invalid rover dock location")+ yaw = dock["yaw"]+ if isinstance(yaw, bool) or not isinstance(yaw, (float, int)) or not math.isfinite(yaw):+ raise ValueError("invalid rover dock orientation")+ exits = dock["exit_station_ids"]+ if not 2 <= len(exits) <= 4 or len(set(exits)) != len(exits):+ raise ValueError("rover dock requires distinct alternative exits")+ anchors = [dock["boarding_station_id"], *exits]+ if len(set(anchors)) != len(anchors):+ raise ValueError("rover boarding and exit anchors must be distinct")+ center = nodes[dock["node_id"]]["position"]+ for station in anchors:+ if station not in destinations:+ raise ValueError("rover access must use visit-only destinations")+ point = nodes[visits[station]["anchor"]]["position"]+ if not 2.3 <= math.dist(center, point) <= 3 or not geometry.capsule_clear(point):+ raise ValueError("rover access lacks adjacent supported clearance")+ for rover in rovers.values():+ if (+ rover["home_dock_id"] not in docks+ or type(rover["seat_capacity"]) is not int+ or rover["seat_capacity"] != 1+ ):+ raise ValueError("invalid rover home or seat capacity")+ dimensions = [rover[key] for key in ("width_m", "length_m", "height_m", "speed_m_s")]+ if any(+ isinstance(value, bool)+ or not isinstance(value, (int, float))+ or not math.isfinite(value)+ or not 0 < value <= 10+ for value in dimensions+ ):+ raise ValueError("invalid rover physical dimensions")+ for dock in docks.values():+ if not geometry.vehicle_clear(+ nodes[dock["node_id"]]["position"], dock["yaw"], *dimensions[:3]+ ):+ raise ValueError("rover dock lacks complete supported clearance")+ center = nodes[dock["node_id"]]["position"]+ anchors = [dock["boarding_station_id"], *dock["exit_station_ids"]]+ points = [nodes[visits[anchor]["anchor"]]["position"] for anchor in anchors]+ sine, cosine = math.sin(dock["yaw"]), math.cos(dock["yaw"])+ for i, point in enumerate(points):+ dx, dz = point[0] - center[0], point[2] - center[2]+ across = abs(dx * cosine - dz * sine)+ along = abs(dx * sine + dz * cosine)+ clearance = math.hypot(+ max(0, across - dimensions[0] / 2),+ max(0, along - dimensions[1] / 2),+ )+ if clearance < 0.6:+ raise ValueError("rover access overlaps the vehicle body")+ if any(math.dist(point, previous) < 1.2 for previous in points[:i]):+ raise ValueError("rover access anchors overlap each other")+ position(data["spawn"]["position"])+++def load_definition() -> dict[str, Any]:+ """Read a fresh value so callers cannot mutate another world's definition."""+ data = json.loads(files(__package__).joinpath("definition.json").read_text(encoding="utf-8"))+ validate_definition(data)+ return datadiff --git a/jarvis/society/mars/mobility_geometry.py b/jarvis/society/mars/mobility_geometry.pynew file mode 100644index 0000000000..4264c680d3--- /dev/null+++ b/jarvis/society/mars/mobility_geometry.py@@ -0,0 +1,233 @@+"""Portable collision and support checks for the authored transport corridor.++These conservative checks consume packaged world coordinates. Renderer loading+and animation cannot grant support, clear a wall, or authorize an exit.+"""++from __future__ import annotations++import math+from typing import Any++Point = tuple[float, float]+_EPS = 1e-7+_GROUND_TOLERANCE = 0.18+++def _cross(a: Point, b: Point, c: Point) -> float:+ return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])+++def _segment_distance(point: Point, start: Point, end: Point) -> float:+ dx, dz = end[0] - start[0], end[1] - start[1]+ length2 = dx * dx + dz * dz+ t = (+ 0+ if length2 == 0+ else max(0, min(1, ((point[0] - start[0]) * dx + (point[1] - start[1]) * dz) / length2))+ )+ return math.hypot(point[0] - start[0] - t * dx, point[1] - start[1] - t * dz)+++def _inside(point: Point, polygon: list[Point]) -> bool:+ inside = False+ for start, end in zip(polygon, polygon[1:] + polygon[:1], strict=True):+ if _segment_distance(point, start, end) <= _EPS:+ return True+ if (start[1] > point[1]) != (end[1] > point[1]) and point[0] < (+ (end[0] - start[0]) * (point[1] - start[1]) / (end[1] - start[1]) + start[0]+ ):+ inside = not inside+ return inside+++def _rectangle(center: Point, yaw: float, width: float, length: float) -> list[Point]:+ forward = (math.sin(yaw), math.cos(yaw))+ right = (forward[1], -forward[0])+ return [+ (+ center[0] + side * width / 2 * right[0] + along * length / 2 * forward[0],+ center[1] + side * width / 2 * right[1] + along * length / 2 * forward[1],+ )+ for side, along in ((-1, -1), (1, -1), (1, 1), (-1, 1))+ ]+++def _overlap(a: list[Point], b: list[Point]) -> bool:+ """Separating-axis check for convex footprints, including touching edges."""+ for polygon in (a, b):+ for p, q in zip(polygon, polygon[1:] + polygon[:1], strict=True):+ axis = (q[1] - p[1], p[0] - q[0])+ av = [x * axis[0] + z * axis[1] for x, z in a]+ bv = [x * axis[0] + z * axis[1] for x, z in b]+ if max(av) < min(bv) - _EPS or max(bv) < min(av) - _EPS:+ return False+ return True+++def _contains_footprint(polygon: list[Point], footprint: list[Point]) -> bool:+ if not all(_inside(point, polygon) for point in footprint):+ return False+ # Clip each shoreline segment against the strict interior of the convex+ # footprint. Corner-to-corner notches have no proper edge intersections and+ # no strictly interior vertices, but still remove support under the body.+ for a, b in zip(polygon, polygon[1:] + polygon[:1], strict=True):+ lower, upper = 0.0, 1.0+ for c, d in zip(footprint, footprint[1:] + footprint[:1], strict=True):+ initial, change = _cross(c, d, a), _cross(c, d, b) - _cross(c, d, a)+ if abs(change) <= _EPS:+ if initial <= _EPS:+ upper = -1.0+ break+ elif change > 0:+ lower = max(lower, (_EPS - initial) / change)+ else:+ upper = min(upper, (_EPS - initial) / change)+ if upper - lower > _EPS:+ return False+ return True+++class MobilityGeometry:+ """Fail closed outside explicitly packaged support and solid geometry.++ A complete footprint must fit on one known patch. Overlapping patches may+ provide alternative support; unverified gaps between patches never do.+ """++ def __init__(self, definition: dict[str, Any]) -> None:+ collision = definition["navigation"].get("collision")+ if collision is None or collision.get("version") != 1:+ raise ValueError("transport requires validated collision data")+ signature = collision.get("source_sha256", "")+ if len(signature) != 64 or any(char not in "0123456789abcdef" for char in signature):+ raise ValueError("invalid collision source fingerprint")+ self.boxes: list[tuple[tuple[float, ...], tuple[float, ...]]] = []+ self.surfaces: list[tuple[list[Point], tuple[float, ...]]] = []++ def vector(value: Any, length: int) -> tuple[float, ...]:+ if (+ not isinstance(value, (list, tuple))+ or len(value) != length+ or any(+ isinstance(n, bool) or not isinstance(n, (int, float)) or not math.isfinite(n)+ for n in value+ )+ ):+ raise ValueError("invalid collision coordinates")+ return tuple(float(n) for n in value)++ boxes, surfaces = collision["solid_boxes"], collision["support_surfaces"]+ if not 1 <= len(boxes) <= 512 or not 1 <= len(surfaces) <= 128:+ raise ValueError("invalid bounded collision geometry")+ for rows in (boxes, surfaces):+ ids = [row["id"] for row in rows]+ if len(set(ids)) != len(ids) or any(not isinstance(i, str) or not i for i in ids):+ raise ValueError("invalid collision identities")+ for row in boxes:+ lo, hi = vector(row["min"], 3), vector(row["max"], 3)+ if any(a >= b for a, b in zip(lo, hi, strict=True)):+ raise ValueError("invalid collision box")+ self.boxes.append((lo, hi))+ for row in surfaces:+ if not 3 <= len(row["polygon"]) <= 512:+ raise ValueError("invalid support polygon")+ polygon = [(p[0], p[1]) for p in (vector(v, 2) for v in row["polygon"])]+ area = sum(+ a[0] * b[1] - b[0] * a[1]+ for a, b in zip(polygon, polygon[1:] + polygon[:1], strict=True)+ )+ if abs(area) < _EPS or len(set(polygon)) != len(polygon):+ raise ValueError("degenerate support polygon")+ self.surfaces.append((polygon, vector(row["plane"], 3)))++ @staticmethod+ def _valid(position: tuple[float, ...] | list[float], *sizes: float) -> bool:+ return (+ len(position) == 3+ and all(math.isfinite(v) for v in position)+ and all(math.isfinite(size) and size > 0 for size in sizes)+ )++ def supported(self, position: tuple[float, ...] | list[float], radius: float = 0) -> bool:+ if not self._valid(position) or not math.isfinite(radius) or radius < 0:+ return False+ x, y, z = position+ for polygon, (a, b, c) in self.surfaces:+ if abs(a * x + b * z + c - y) + radius * math.hypot(a, b) > _GROUND_TOLERANCE:+ continue+ if _inside((x, z), polygon) and all(+ _segment_distance((x, z), p, q) + _EPS >= radius+ for p, q in zip(polygon, polygon[1:] + polygon[:1], strict=True)+ ):+ return True+ return False++ def capsule_clear(+ self, position: tuple[float, ...] | list[float], radius: float = 0.6, height: float = 1.8+ ) -> bool:+ if not self._valid(position, radius, height) or not self.supported(position, radius):+ return False+ x, y, z = position+ for lo, hi in self.boxes:+ if y + height <= lo[1] or y >= hi[1]:+ continue+ nearest = (max(lo[0], min(hi[0], x)), max(lo[2], min(hi[2], z)))+ if math.dist((x, z), nearest) <= radius + _EPS:+ return False+ return True++ def _footprint_clear(+ self, footprint: list[Point], plane: tuple[float, float, float], height: float+ ) -> bool:+ a, b, c = plane+ if not any(+ _contains_footprint(polygon, footprint)+ and all(+ abs((sa - a) * x + (sb - b) * z + sc - c) <= _GROUND_TOLERANCE for x, z in footprint+ )+ for polygon, (sa, sb, sc) in self.surfaces+ ):+ return False+ low = min(a * x + b * z + c for x, z in footprint)+ high = max(a * x + b * z + c for x, z in footprint) + height+ for lo, hi in self.boxes:+ if high <= lo[1] or low >= hi[1]:+ continue+ rectangle = [(lo[0], lo[2]), (hi[0], lo[2]), (hi[0], hi[2]), (lo[0], hi[2])]+ if _overlap(footprint, rectangle):+ return False+ return True++ def vehicle_clear(+ self,+ position: tuple[float, ...] | list[float],+ yaw: float,+ width: float = 3.4,+ length: float = 4.8,+ height: float = 2.6,+ ) -> bool:+ if not self._valid(position, width, length, height) or not math.isfinite(yaw):+ return False+ x, y, z = position+ return self._footprint_clear(_rectangle((x, z), yaw, width, length), (0, 0, y), height)++ def path_clear(+ self,+ start: tuple[float, ...] | list[float],+ end: tuple[float, ...] | list[float],+ width: float = 3.4,+ length: float = 4.8,+ height: float = 2.6,+ ) -> bool:+ if not self._valid(start, width, length, height) or not self._valid(end):+ return False+ dx, dz = end[0] - start[0], end[2] - start[2]+ distance2 = dx * dx + dz * dz+ if distance2 < _EPS:+ return False+ a, b = (end[1] - start[1]) * dx / distance2, (end[1] - start[1]) * dz / distance2+ plane = (a, b, start[1] - a * start[0] - b * start[2])+ center = ((start[0] + end[0]) / 2, (start[2] + end[2]) / 2)+ swept = _rectangle(center, math.atan2(dx, dz), width, length + math.sqrt(distance2))+ return self._footprint_clear(swept, plane, height)diff --git a/jarvis/society/mars/models.py b/jarvis/society/mars/models.pynew file mode 100644index 0000000000..1d900c1dc8--- /dev/null+++ b/jarvis/society/mars/models.py@@ -0,0 +1,174 @@+"""Versioned, bounded station messages shared by storage and HTTP projections."""++from __future__ import annotations++import re+from enum import StrEnum+from typing import Annotated, Literal++from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator++WORLD_ID = "mars:ordinary"+STATION_ID = "communications-console"+CAPABILITY_ID = "communication-draft"+SCHEMA_VERSION = 1+LAYOUT_VERSION = 1++Identity = Annotated[str, Field(min_length=1, max_length=128, pattern=r"^[A-Za-z0-9_.:-]+$")]+Reference = Annotated[str, Field(min_length=1, max_length=256)]+++class CommandState(StrEnum):+ QUEUED = "queued"+ ACTIVE = "active"+ COMPLETED = "completed"+ FAILED = "failed"+ CANCELED = "canceled"+ INTERRUPTED = "interrupted"+ UNKNOWN = "unknown"+++TERMINAL_STATES = frozenset({CommandState.COMPLETED, CommandState.FAILED, CommandState.CANCELED})+++class StationError(Exception):+ """Public generic error code; never carries an upstream provider response."""++ def __init__(self, reason: str, status_code: int = 409) -> None:+ if re.fullmatch(r"[a-z_]{1,80}", reason) is None:+ reason = "station_operation_failed"+ super().__init__(reason)+ self.reason = reason+ self.status_code = status_code+++class DispatchRejected(StationError):+ """Trusted adapter guarantees no task or side effect was accepted."""+++def reject_draft_credentials(draft: str) -> None:+ """Reject credentials before any storage, session creation or execution.++ This belongs at the acceptance boundary, outside Pydantic validators:+ HTTP validation errors otherwise include the rejected input by default.+ The public reason points to in-app key settings without echoing a value.+ """+ from jarvis.memory.wiki.secret_guard import contains_secret++ if contains_secret(draft):+ raise DispatchRejected("credential_input_use_api_key_settings", 422)+++class ContractModel(BaseModel):+ model_config = ConfigDict(extra="forbid", frozen=True, strict=True)+++class StationCommand(ContractModel):+ """Identity of the acting agent comes from the trusted server boundary."""++ world_id: Literal["mars:ordinary"] = WORLD_ID+ station_id: Literal["communications-console"] = STATION_ID+ capability_id: Literal["communication-draft"] = CAPABILITY_ID+ schema_version: Literal[1] = SCHEMA_VERSION+ layout_version: Literal[1] = LAYOUT_VERSION+ request_id: Identity+ draft: str = Field(min_length=1, max_length=4000)++ @field_validator("schema_version", "layout_version", mode="before")+ @classmethod+ def exact_version(cls, value: object) -> object:+ if type(value) is not int or value != 1:+ raise ValueError("unsupported station contract version")+ return value++ @field_validator("draft")+ @classmethod+ def nonblank_draft(cls, value: str) -> str:+ value = value.strip()+ if not value or "\x00" in value:+ raise ValueError("draft must contain text without null characters")+ return value+++class CommandRecord(ContractModel):+ command_id: Identity+ world_id: Literal["mars:ordinary"] = WORLD_ID+ station_id: Literal["communications-console"] = STATION_ID+ capability_id: Literal["communication-draft"] = CAPABILITY_ID+ agent_id: Identity+ request_id: Identity+ trace_id: Identity+ state: CommandState+ # Private local input is retained for dispatch, never sent in world events/snapshots.+ draft: str = Field(exclude=True)+ created_ms: int+ updated_ms: int+ fence: int = 0+ task_ref: Reference | None = None+ result_ref: Reference | None = None+ reason: str = ""+ cancel_requested: bool = False+ cancel_dispatched: bool = Field(default=False, exclude=True)+++class StationLease(ContractModel):+ station_id: Literal["communications-console"] = STATION_ID+ command_id: Identity+ agent_id: Identity+ fence: int+ expires_ms: int+++class ExecutionReceipt(ContractModel):+ """Trusted adapter evidence. A missing result cannot count as completion."""++ state: CommandState+ task_ref: Reference | None = None+ result_ref: Reference | None = None+ # Only cancellation receipts set this. A proven no-op may be retried once+ # prerequisites recover; an attempted or uncertain stop must be reconciled.+ cancel_attempt: Literal["not_attempted", "attempted", "unknown"] | None = None++ @model_validator(mode="after")+ def valid_outcome(self) -> ExecutionReceipt:+ if self.state is CommandState.QUEUED:+ raise ValueError("executor cannot return a station queue state")+ if self.state in {CommandState.ACTIVE, CommandState.COMPLETED} and not self.task_ref:+ raise ValueError("accepted execution requires a durable task reference")+ if self.state is CommandState.COMPLETED and not self.result_ref:+ raise ValueError("completion requires a durable result reference")+ return self+++class StationEvent(ContractModel):+ seq: int+ command_id: str+ trace_id: str+ agent_id: str+ state: CommandState+ fence: int+ task_ref: str | None = None+ result_ref: str | None = None+ reason: str+ cancel_requested: bool+ ts_ms: int+++class StationSnapshot(ContractModel):+ world_id: Literal["mars:ordinary"] = WORLD_ID+ schema_version: Literal[1] = SCHEMA_VERSION+ layout_version: Literal[1] = LAYOUT_VERSION+ seq: int+ commands: tuple[CommandRecord, ...]+ lease: StationLease | None+++class StationEventBatch(ContractModel):+ world_id: Literal["mars:ordinary"] = WORLD_ID+ schema_version: Literal[1] = SCHEMA_VERSION+ layout_version: Literal[1] = LAYOUT_VERSION+ events: tuple[StationEvent, ...]+ next_cursor: int+ latest_seq: int+ has_more: bool+ resync_required: booldiff --git a/jarvis/society/mars/navigation.py b/jarvis/society/mars/navigation.pynew file mode 100644index 0000000000..5bc8690297--- /dev/null+++ b/jarvis/society/mars/navigation.py@@ -0,0 +1,243 @@+"""Canonical, deterministic graph routing with explicit travel clearance."""++from __future__ import annotations++import hashlib+import heapq+import json+import math+from dataclasses import dataclass+from typing import Any++from .models import StationError+from .navigation_models import (+ NavigationOccupancy,+ NavigationRecord,+ RoverRideRecord,+ TravelMode,+ VehicleRecord,+)+++@dataclass(frozen=True)+class RouteEdge:+ id: str+ start: str+ end: str+ length: float+ width: float+ modes: frozenset[str]+++class NavigationGraph:+ """Copies its inputs; the caller cannot mutate an in-flight route graph.++ This logical checkpoint uses conservative single-occupant edge segments.+ Width checks include body clearance; visual local avoidance is not authority.+ """++ def __init__(self, definition: dict[str, Any]) -> None:+ data = json.loads(json.dumps(definition, allow_nan=False))+ if data["world_id"] != "mars:ordinary":+ raise ValueError("unsupported navigation world")+ nav = data["navigation"]+ self.definition = data+ self.migrations = nav.get("graph_migrations", [])+ signature_nav = {k: v for k, v in nav.items() if k != "graph_migrations"}+ self.version = nav["version"]+ self.layout_version = data["layout_version"]+ if type(self.version) is not int or self.version < 1:+ raise ValueError("invalid graph version")+ if type(self.layout_version) is not int or self.layout_version < 1:+ raise ValueError("invalid layout version")+ self.signature = hashlib.sha256(+ json.dumps(+ [signature_nav, data["stations"], data["spawn"]],+ sort_keys=True,+ separators=(",", ":"),+ ).encode()+ ).hexdigest()+ self.nodes = {+ node["id"]: tuple(float(v) for v in node["position"]) for node in nav["nodes"]+ }+ if not 1 <= len(self.nodes) <= 512 or len(self.nodes) != len(nav["nodes"]):+ raise ValueError("invalid bounded navigation nodes")+ if any(len(p) != 3 or not all(math.isfinite(v) for v in p) for p in self.nodes.values()):+ raise ValueError("invalid navigation position")+ self.resource_aliases = {+ "node:" + row["id"]: tuple(row.get("resource_ids", ())) for row in nav["nodes"]+ }+ self.edges: dict[str, RouteEdge] = {}+ self.adjacent: dict[str, list[tuple[str, RouteEdge]]] = {key: [] for key in self.nodes}+ if len(nav["edges"]) > 2048:+ raise ValueError("too many navigation edges")+ for row in nav["edges"]:+ start, end, width = row["from"], row["to"], row["width"]+ if start not in self.nodes or end not in self.nodes or start == end:+ raise ValueError("invalid edge endpoint")+ length = math.dist(self.nodes[start], self.nodes[end])+ if length <= 0 or not math.isfinite(width) or width <= 0:+ raise ValueError("invalid route dimensions")+ edge = RouteEdge(row["id"], start, end, length, width, frozenset(row["modes"]))+ if edge.id in self.edges:+ raise ValueError("duplicate route identity")+ self.edges[edge.id] = edge+ self.resource_aliases["edge:" + edge.id] = tuple(row.get("resource_ids", ()))+ self.adjacent[start].append((end, edge))+ self.adjacent[end].append((start, edge))+ # Visit-only destinations share physical slots with task stations, but+ # have no capability and can never be dispatched through a task API.+ destinations = [*data["stations"], *nav.get("destinations", [])]+ self.stations = {row["id"]: row["anchor"] for row in destinations}+ if (+ not 1 <= len(self.stations) <= 64+ or len(self.stations) != len(destinations)+ or any(+ anchor not in self.nodes or row["capacity"] != 1+ for row in destinations+ for anchor in [row["anchor"]]+ )+ ):+ raise ValueError("invalid physical station slot")+ self.docks = {row["id"]: row for row in nav.get("rover_docks", [])}+ self.rovers = {row["id"]: row for row in nav.get("rovers", [])}+ self.geometry = None+ if self.rovers:+ from .mobility_geometry import MobilityGeometry++ self.geometry = MobilityGeometry(data)+ if len(self.rovers) > 16 or not 2 <= len(self.docks) <= 32:+ raise ValueError("invalid bounded rover catalogue")+ for dock in self.docks.values():+ node = dock["node_id"]+ if node not in self.nodes:+ raise ValueError("unknown rover dock node")+ for station in [dock["boarding_station_id"], *dock["exit_station_ids"]]:+ if station not in self.stations:+ raise ValueError("unknown rover pedestrian dock station")+ point = self.nodes[self.stations[station]]+ if not 0.5 <= math.dist(point, self.nodes[node]) <= 4.0:+ raise ValueError("invalid rover transfer clearance")+ if not self.geometry.capsule_clear(point):+ raise ValueError("unsafe rover pedestrian dock station")+ self.stations["rover-dock:" + dock["id"]] = node+ for rover in self.rovers.values():+ if (+ rover["home_dock_id"] not in self.docks+ or rover["seat_capacity"] != 1+ or rover["width_m"] != 3.4+ or rover["length_m"] != 4.8+ or rover["height_m"] != 2.6+ or rover["speed_m_s"] != 4+ ):+ raise ValueError("unsupported rover envelope")+ for dock in self.docks.values():+ if not self.geometry.vehicle_clear(+ self.nodes[dock["node_id"]], self.dock_yaw(dock["id"])+ ):+ raise ValueError("unsafe rover dock")+ spawn = data["spawn"]["position"]+ self.spawn_node = min(self.nodes, key=lambda key: (math.dist(spawn, self.nodes[key]), key))++ @staticmethod+ def supports(edge: RouteEdge, mode: TravelMode) -> bool:+ # Declared logical envelopes; final character/rover geometry still needs alignment.+ clearance = 1.2 if mode is TravelMode.PEDESTRIAN else 3.4+ return mode.value in edge.modes and edge.width >= clearance++ def path(+ self, start: str, station_id: str, mode: TravelMode, blocked: frozenset[str] = frozenset()+ ) -> tuple[str, ...] | None:+ if station_id not in self.stations:+ raise StationError("unknown_navigation_station", 404)+ target = self.stations[station_id]+ if start not in self.nodes:+ return None+ pending: list[tuple[float, str, tuple[str, ...]]] = [(0, start, ())]+ best: dict[str, float] = {start: 0}+ while pending:+ distance, node, route = heapq.heappop(pending)+ if distance != best[node]:+ continue+ if node == target:+ return route+ for destination, edge in sorted(self.adjacent[node], key=lambda item: item[1].id):+ candidate = distance + edge.length+ if (+ edge.id not in blocked+ and self.supports(edge, mode)+ and candidate < best.get(destination, math.inf)+ ):+ best[destination] = candidate+ heapq.heappush(pending, (candidate, destination, (*route, edge.id)))+ return None++ def destination(self, edge_id: str, node: str) -> str:+ edge = self.edges[edge_id]+ if node not in (edge.start, edge.end):+ raise StationError("invalid_navigation_location", 409)+ return edge.end if node == edge.start else edge.start++ def position(self, start: str, end: str, fraction: float) -> tuple[float, float, float]:+ return tuple(+ a + (b - a) * fraction for a, b in zip(self.nodes[start], self.nodes[end], strict=True)+ ) # type: ignore[return-value]++ def resources(self, resource_id: str) -> tuple[str, ...]:+ return (resource_id, *self.resource_aliases.get(resource_id, ()))++ def dock_yaw(self, dock_id: str) -> float:+ dock = self.docks[dock_id]+ if "yaw" in dock:+ return float(dock["yaw"])+ node = dock["node_id"]+ for destination, edge in self.adjacent[node]:+ if self.supports(edge, TravelMode.ROVER):+ start, end = self.nodes[node], self.nodes[destination]+ return math.atan2(end[0] - start[0], end[2] - start[2])+ raise ValueError("rover dock has no compatible road")++ def occupancies(+ self,+ records: list[NavigationRecord],+ vehicles: list[VehicleRecord] = (),+ rides: list[RoverRideRecord] = (),+ ) -> tuple[NavigationOccupancy, ...]:+ """Derive bodies from each actor's latest receipt, even terminal receipts.++ An edge chosen while queueing with zero progress is not occupied yet.+ Bodies at endpoints occupy nodes and any station sharing that anchor.+ Graph changes do not silently erase old physical resource identities.+ """+ attached = {ride.agent_id for ride in rides if ride.attached}+ latest = {record.agent_id: record for record in records}+ bodies = [record for agent_id, record in latest.items() if agent_id not in attached]+ occupied = []+ for record in [*bodies, *vehicles]:+ if record.presence == "spawn_queue":+ continue+ if record.edge_id is not None and 0 < record.edge_progress < 1:+ resources = ["edge:" + record.edge_id]+ else:+ node = record.current_node+ resources = ["node:" + node]+ resources.extend(+ "station:" + station+ for station, anchor in self.stations.items()+ if anchor == node+ )+ resources = list(+ dict.fromkeys(item for resource in resources for item in self.resources(resource))+ )+ occupied.extend(+ NavigationOccupancy(+ resource_id=resource,+ command_id=record.command_id,+ agent_id=record.agent_id if isinstance(record, NavigationRecord) else None,+ actor=record.actor,+ position=record.position,+ graph_signature=record.graph_signature,+ )+ for resource in resources+ )+ return tuple(occupied)diff --git a/jarvis/society/mars/navigation_migration.py b/jarvis/society/mars/navigation_migration.pynew file mode 100644index 0000000000..29f77d7b33--- /dev/null+++ b/jarvis/society/mars/navigation_migration.py@@ -0,0 +1,130 @@+"""Conservative graph migration: only proven geometry-preserving subdivisions."""++from __future__ import annotations++import hashlib+import json+import math+++def _descriptor_signature(descriptor):+ nav = {+ key: value for key, value in descriptor["navigation"].items() if key != "graph_migrations"+ }+ return hashlib.sha256(+ json.dumps(+ [nav, descriptor["stations"], descriptor["spawn"]],+ sort_keys=True,+ separators=(",", ":"),+ ).encode()+ ).hexdigest()+++def migrate_record(record, graph):+ """Retain a frozen record unless its exact old graph and pose can be proven."""+ if record.graph_signature == graph.signature:+ return record+ for migration in graph.migrations:+ descriptor = migration["source_descriptor"]+ if (+ migration["source_signature"] != record.graph_signature+ or _descriptor_signature(descriptor) != record.graph_signature+ ):+ continue+ old = descriptor["navigation"]+ nodes = {row["id"]: tuple(row["position"]) for row in old["nodes"]}+ edges = {row["id"]: row for row in old["edges"]}+ stations = {+ row["id"]: row["anchor"]+ for row in [*descriptor["stations"], *old.get("destinations", [])]+ }+ if (+ any(graph.nodes.get(key) != point for key, point in nodes.items())+ or any(graph.stations.get(key) != node for key, node in stations.items())+ or descriptor["spawn"] != graph.definition["spawn"]+ ):+ continue+ splits = migration.get("edge_splits", {})+ mapped_edges = {}+ valid = True+ for edge_id, edge in edges.items():+ chain = splits.get(edge_id, [edge_id])+ node = edge["from"]+ a, b = nodes[node], nodes[edge["to"]]+ length = math.dist(a, b)+ segments, total = [], 0.0+ for new_id in chain:+ new = graph.edges.get(new_id)+ if (+ new is None+ or node not in (new.start, new.end)+ or new.width != edge["width"]+ or new.modes != frozenset(edge["modes"])+ ):+ valid = False+ break+ end = new.end if node == new.start else new.start+ point = graph.nodes[end]+ distance = math.dist(a, point)+ # Both triangle equality and accumulated length prohibit detours,+ # reversals and changes disguised as a split.+ if not math.isclose(+ distance + math.dist(point, b), length, abs_tol=1e-7+ ) or not math.isclose(total + new.length, distance, abs_tol=1e-7):+ valid = False+ break+ segments.append((new_id, node, end, total / length, (total + new.length) / length))+ total += new.length+ node = end+ if not valid or node != edge["to"] or not math.isclose(total, length, abs_tol=1e-7):+ valid = False+ break+ mapped_edges[edge_id] = segments+ if not valid or record.current_node not in nodes:+ continue+ updates = {}+ if record.edge_id and 0 < record.edge_progress < 1:+ edge = edges.get(record.edge_id)+ if edge is None or {record.current_node, record.next_node} != {+ edge["from"],+ edge["to"],+ }:+ continue+ forward = record.current_node == edge["from"]+ t = record.edge_progress if forward else 1 - record.edge_progress+ a, b = nodes[edge["from"]], nodes[edge["to"]]+ expected = tuple(x + (y - x) * t for x, y in zip(a, b, strict=True))+ if math.dist(expected, record.position) > 1e-7:+ continue+ for edge_id, start, end, lo, hi in mapped_edges[record.edge_id]:+ if lo - 1e-10 <= t <= hi + 1e-10:+ q = min(1.0, max(0.0, (t - lo) / (hi - lo)))+ if q < 1e-9 or q > 1 - 1e-9:+ updates = {+ "current_node": start if q < 0.5 else end,+ "edge_id": None,+ "next_node": None,+ "edge_progress": 0,+ }+ else:+ updates = {+ "current_node": start if forward else end,+ "next_node": end if forward else start,+ "edge_id": edge_id,+ "edge_progress": q if forward else 1 - q,+ }+ break+ else:+ if math.dist(nodes[record.current_node], record.position) > 1e-7:+ continue+ updates = {"edge_id": None, "next_node": None, "edge_progress": 0}+ return record.model_copy(+ update={+ **updates,+ "path": (),+ "graph_signature": graph.signature,+ "graph_version": graph.version,+ "layout_version": graph.layout_version,+ }+ )+ return recorddiff --git a/jarvis/society/mars/navigation_models.py b/jarvis/society/mars/navigation_models.pynew file mode 100644index 0000000000..c7fcc9004c--- /dev/null+++ b/jarvis/society/mars/navigation_models.py@@ -0,0 +1,211 @@+"""Public logical travel messages, deliberately independent of task execution."""++from __future__ import annotations++from enum import StrEnum+from typing import Literal++from pydantic import Field, field_validator++from .models import ContractModel, Identity+++class TravelMode(StrEnum):+ PEDESTRIAN = "pedestrian"+ ROVER = "rover"+++class NavigationState(StrEnum):+ QUEUEING = "queueing"+ MOVING = "moving"+ TEMPORARILY_BLOCKED = "temporarily_blocked"+ REROUTING = "rerouting"+ ARRIVED = "arrived"+ UNREACHABLE = "unreachable"+ CANCELED = "canceled"+++NAVIGATION_TERMINAL = frozenset(+ {NavigationState.ARRIVED, NavigationState.UNREACHABLE, NavigationState.CANCELED}+)+++class MoveCommand(ContractModel):+ world_id: Literal["mars:ordinary"] = "mars:ordinary"+ schema_version: Literal[1] = 1+ layout_version: int = Field(default=1, ge=1)+ graph_version: int = Field(default=1, ge=1)+ request_id: Identity+ station_id: Identity+ mode: TravelMode = TravelMode.PEDESTRIAN++ @field_validator("schema_version", "layout_version", "graph_version", mode="before")+ @classmethod+ def integer_version(cls, value: object) -> object:+ if type(value) is not int:+ raise ValueError("navigation versions must be integers")+ return value+++class PedestrianMoveCommand(MoveCommand):+ """The public visit API does not yet expose vehicle control."""++ mode: Literal[TravelMode.PEDESTRIAN] = TravelMode.PEDESTRIAN+++class ActorRef(ContractModel):+ """Physical identity, distinct from the user or agent requesting movement."""++ kind: Literal["agent", "vehicle"]+ id: Identity+++class TravelRecord(ContractModel):+ command_id: Identity+ request_id: Identity+ trace_id: Identity+ world_id: Literal["mars:ordinary"] = "mars:ordinary"+ schema_version: Literal[1] = 1+ layout_version: int+ graph_version: int+ graph_signature: str+ station_id: Identity+ mode: TravelMode+ state: NavigationState+ # Positions are logical graph coordinates, not client animation observations.+ position: tuple[float, float, float]+ current_node: Identity+ edge_id: Identity | None = None+ next_node: Identity | None = None+ edge_progress: float = Field(default=0, ge=0, le=1)+ path: tuple[str, ...] = Field(default=(), max_length=512)+ placement: Literal["canonical_spawn", "persisted"]+ # A spawn queue position is an approach coordinate, not a materialized body.+ # Missing fields in old durable records conservatively mean physically placed.+ presence: Literal["spawn_queue", "placed"] = "placed"+ created_ms: int+ updated_ms: int+ last_progress_ms: int+ deadline_ms: int+ retry_at_ms: int = 0+ retries: int = 0+ reason: str = ""+++class NavigationRecord(TravelRecord):+ agent_id: Identity++ @property+ def actor(self) -> ActorRef:+ return ActorRef(kind="agent", id=self.agent_id)+++class VehicleRecord(TravelRecord):+ vehicle_id: Identity+ ride_id: Identity | None = None++ @property+ def actor(self) -> ActorRef:+ return ActorRef(kind="vehicle", id=self.vehicle_id)+++class RideState(StrEnum):+ APPROACHING = "approaching"+ READY_TO_BOARD = "ready_to_board"+ BOARDED = "boarded"+ TRAVELING = "traveling"+ ARRIVED = "arrived"+ STOPPED = "stopped"+ EXIT_BLOCKED = "exit_blocked"+ COMPLETED = "completed"+ CANCELED = "canceled"+++RIDE_TERMINAL = frozenset({RideState.COMPLETED, RideState.CANCELED})+++class RoverReserveCommand(ContractModel):+ world_id: Literal["mars:ordinary"] = "mars:ordinary"+ schema_version: Literal[1] = 1+ layout_version: int = Field(default=1, ge=1)+ graph_version: int = Field(default=1, ge=1)+ request_id: Identity+ vehicle_id: Identity++ @field_validator("schema_version", "layout_version", "graph_version", mode="before")+ @classmethod+ def integer_version(cls, value: object) -> object:+ return MoveCommand.integer_version(value)+++class RoverActionCommand(ContractModel):+ request_id: Identity+++class RoverTravelCommand(RoverActionCommand):+ destination_dock_id: Identity+++class RoverRideRecord(ContractModel):+ ride_id: Identity+ request_id: Identity+ agent_id: Identity+ vehicle_id: Identity+ trace_id: Identity+ origin_dock_id: Identity+ destination_dock_id: Identity | None = None+ approach_command_id: Identity+ state: RideState+ attached: bool = False+ created_ms: int+ updated_ms: int+ deadline_ms: int+ reason: str = ""+++class NavigationLease(ContractModel):+ resource_id: str+ command_id: Identity+ agent_id: Identity | None = None+ actor: ActorRef | None = None+ expires_ms: int++ @property+ def owner(self) -> ActorRef:+ if self.actor is not None:+ return self.actor+ if self.agent_id is None:+ raise ValueError("lease requires a physical owner")+ return ActorRef(kind="agent", id=self.agent_id)+++class NavigationOccupancy(ContractModel):+ """Physical placement persists independently of command/intent lease lifetime."""++ resource_id: str+ command_id: Identity+ agent_id: Identity | None = None+ actor: ActorRef | None = None+ position: tuple[float, float, float]+ graph_signature: str++ @property+ def owner(self) -> ActorRef:+ if self.actor is not None:+ return self.actor+ if self.agent_id is None:+ raise ValueError("occupancy requires a physical owner")+ return ActorRef(kind="agent", id=self.agent_id)+++class NavigationSnapshot(ContractModel):+ world_id: Literal["mars:ordinary"] = "mars:ordinary"+ schema_version: Literal[1] = 1+ graph_version: int+ graph_signature: str+ seq: int+ commands: tuple[NavigationRecord, ...]+ leases: tuple[NavigationLease, ...]+ occupancies: tuple[NavigationOccupancy, ...] = ()+ vehicles: tuple[VehicleRecord, ...] = ()+ rides: tuple[RoverRideRecord, ...] = ()diff --git a/jarvis/society/mars/navigation_ordinary.py b/jarvis/society/mars/navigation_ordinary.pynew file mode 100644index 0000000000..9d09c81668--- /dev/null+++ b/jarvis/society/mars/navigation_ordinary.py@@ -0,0 +1,42 @@+"""Read existing ordinary-agent authority without opening a task or chat turn."""++from __future__ import annotations++from typing import TYPE_CHECKING++from jarvis.society.events import AgentState++from .navigation_models import TravelMode++if TYPE_CHECKING:+ from jarvis.society.runtime import SocietyRuntime+++class OrdinaryNavigationAuthority:+ """Logical visits need an active roster identity and respect the kill switch.++ No provider, session, capability grant, task scheduler or external tool is+ involved. Task execution continues using its separate station authority.+ """++ def __init__(self, runtime: SocietyRuntime) -> None:+ self.runtime = runtime++ async def __call__(self, agent_id: str, _destination: str, mode: TravelMode) -> bool:+ if mode is not TravelMode.PEDESTRIAN:+ return False+ return await self._active(agent_id)++ async def rover(self, agent_id: str, _destination: str, mode: TravelMode) -> bool:+ """Only the seat-bearing rover action boundary uses this capability."""+ if mode is not TravelMode.ROVER:+ return False+ return await self._active(agent_id)++ async def _active(self, agent_id: str) -> bool:+ agent = await self.runtime.roster.get(agent_id)+ return (+ agent is not None+ and agent.state is AgentState.ACTIVE+ and not await self.runtime.store.kill_switch()+ )diff --git a/jarvis/society/mars/navigation_service.py b/jarvis/society/mars/navigation_service.pynew file mode 100644index 0000000000..7f412055f3--- /dev/null+++ b/jarvis/society/mars/navigation_service.py@@ -0,0 +1,525 @@+"""No-client logical travel controller; never dispatches or completes real work."""++from __future__ import annotations++import asyncio+import logging+from collections.abc import Awaitable, Callable, Iterable+from typing import Any++from .models import StationError+from .navigation import NavigationGraph+from .navigation_models import (+ NAVIGATION_TERMINAL,+ MoveCommand,+ NavigationLease,+ NavigationRecord,+ NavigationSnapshot,+ NavigationState,+ TravelMode,+)+from .navigation_store import MarsNavigationStore+from .rover_service import RoverServiceMixin++_LOG = logging.getLogger(__name__)+NavigationAuthorizer = Callable[[str, str, TravelMode], Awaitable[bool]]+++class MarsNavigationService(RoverServiceMixin):+ """Host calls advance independently of renderers, sockets, and task workers.++ Missing ticks catch up at most five seconds, checking each crossed edge.+ Process downtime is paused travel, with exact saved placement retained and+ reservations reacquired on restart. A render chunk has no effect on travel;+ player collision/asset readiness remains a separate frontend obligation.+ Expiring leases reserve intended resources; they never erase a body. Latest+ persisted actor placements continue occupying nodes, station slots and edges+ after arrival, cancellation, process loss, and lease expiry. New actors wait+ in an explicit logical spawn queue until they can enter a clear route.+ These reservations never obstruct remote communication-draft tasks.+ """++ def __init__(+ self,+ store: MarsNavigationStore,+ definition: dict[str, Any],+ *,+ authorize: NavigationAuthorizer,+ authorize_rover: NavigationAuthorizer | None = None,+ lease_ms: int = 10_000,+ deadline_ms: int = 600_000,+ retry_interval_ms: int = 2_000,+ max_retries: int = 5,+ max_advance_ms: int = 5_000,+ authorization_timeout_s: float = 10,+ ) -> None:+ if not (+ 1_000 <= lease_ms <= 60_000+ and 1_000 <= deadline_ms <= 1_800_000+ and 100 <= retry_interval_ms <= 60_000+ and 1 <= max_retries <= 20+ and 1 <= max_advance_ms <= 5_000+ and 0 < authorization_timeout_s <= 30+ ):+ raise ValueError("invalid bounded navigation configuration")+ self.store = store+ self.graph = NavigationGraph(definition)+ self.authorize = authorize+ self.authorize_rover = authorize_rover+ self.lease_ms = lease_ms+ self.deadline_ms = deadline_ms+ self.retry_interval_ms = retry_interval_ms+ self.max_retries = max_retries+ self.max_advance_ms = max_advance_ms+ self.authorization_timeout_s = authorization_timeout_s+ self._lock = asyncio.Lock()+ self._started = False++ async def start(self) -> None:+ async with self._lock:+ if self._started:+ return+ await self.store.open()++ def recover(world, now):+ self._recover_rovers(world, now)+ records, leases = world.records, world.leases+ leases.clear()+ for key, record in records.items():+ if record.state not in NAVIGATION_TERMINAL:+ records[key] = record.model_copy(+ update={+ "state": NavigationState.REROUTING,+ "reason": "process_restarted",+ "updated_ms": now,+ "retry_at_ms": 0,+ }+ )++ try:+ await self.store.mutate_world(recover)+ except BaseException:+ await self.store.close()+ raise+ self._started = True++ async def close(self) -> None:+ async with self._lock:+ try:+ if self._started:+ await self.store.mutate(lambda records, leases, now: leases.clear())+ finally:+ await self.store.close()+ self._started = False++ async def submit(self, agent_id: str, request: MoveCommand) -> NavigationRecord:+ if request.mode is not TravelMode.PEDESTRIAN:+ raise StationError("rover_ride_required", 422)+ async with self._lock:+ existing = await self.store.duplicate(agent_id, request)+ if existing is not None:+ return existing+ if (+ request.graph_version != self.graph.version+ or request.layout_version != self.graph.layout_version+ ):+ raise StationError("navigation_graph_version_mismatch", 409)+ if request.station_id not in self.graph.stations:+ raise StationError("unknown_navigation_station", 404)+ await self._authorize(agent_id, request.station_id, request.mode)+ if any(+ body.graph_signature != self.graph.signature+ for body in (await self.store.snapshot(self.graph)).occupancies+ ):+ raise StationError("navigation_location_graph_changed", 409)+ return await self.store.accept(+ agent_id, request, self.graph, deadline_ms=self.deadline_ms+ )++ async def _authorize(+ self, agent_id: str, station_id: str, mode: TravelMode, *, rover: bool = False+ ) -> None:+ callback = self.authorize_rover if rover else self.authorize+ if callback is None:+ raise StationError("navigation_not_authorized", 403)+ try:+ allowed = await asyncio.wait_for(+ callback(agent_id, station_id, mode),+ timeout=self.authorization_timeout_s,+ )+ except StationError:+ raise+ except Exception:+ # Do not expose callback/provider errors or caller identity in logs.+ _LOG.warning("Navigation authorization did not complete")+ raise StationError("navigation_authorization_unavailable", 503) from None+ if allowed is not True:+ raise StationError("navigation_not_authorized", 403)++ async def cancel(self, agent_id: str, command_id: str) -> NavigationRecord:+ async with self._lock:+ record = await self.store.get(command_id)+ if record.agent_id != agent_id:+ raise StationError("navigation_command_not_found", 404)++ def cancel(records, leases, now):+ current = records[command_id]+ if current.state not in {NavigationState.CANCELED, NavigationState.UNREACHABLE}:+ records[command_id] = current.model_copy(+ update={+ "state": NavigationState.CANCELED,+ "reason": "user_canceled",+ "updated_ms": now,+ }+ )+ self._release(leases, command_id)++ await self.store.mutate(cancel, include_id=command_id)+ return await self.store.get(command_id)++ async def snapshot(self) -> NavigationSnapshot:+ return await self.store.snapshot(self.graph)++ @staticmethod+ def _release(leases: dict[str, NavigationLease], command_id: str) -> None:+ for key in [key for key, lease in leases.items() if lease.command_id == command_id]:+ del leases[key]++ def _available(self, leases, occupancy, resource_id: str, record: NavigationRecord) -> bool:+ resources = self.graph.resources(resource_id)+ if any(body.resource_id in resources and body.owner != record.actor for body in occupancy):+ return False+ return all(+ leases.get(item) is None or leases[item].owner == record.actor for item in resources+ )++ def _claim(self, leases, occupancy, resource_id, record, now) -> bool:+ if not self._available(leases, occupancy, resource_id, record):+ return False+ for item in self.graph.resources(resource_id):+ leases[item] = NavigationLease(+ resource_id=item,+ command_id=record.command_id,+ agent_id=getattr(record, "agent_id", None),+ actor=record.actor,+ expires_ms=now + self.lease_ms,+ )+ return True++ def _blocked(self, record: NavigationRecord, now: int, reason: str) -> NavigationRecord:+ retries = record.retries + (now >= record.retry_at_ms)+ state = NavigationState.TEMPORARILY_BLOCKED+ if retries >= self.max_retries:+ state, reason = NavigationState.UNREACHABLE, "navigation_retry_exhausted"+ return record.model_copy(+ update={+ "state": state,+ "reason": reason,+ "updated_ms": now,+ "retries": retries,+ "retry_at_ms": now + self.retry_interval_ms+ if now >= record.retry_at_ms+ else record.retry_at_ms,+ }+ )++ async def advance(+ self, *, blocked_edges: Iterable[str] = (), unavailable_stations: Iterable[str] = ()+ ) -> None:+ """Advance authoritative state in FIFO order against host-known obstructions.++ Inputs describe logical obstructions, never client visibility or asset+ loading. The host retains these inputs while an obstruction is present.+ """+ blocked, unavailable = frozenset(blocked_edges), frozenset(unavailable_stations)+ if not blocked <= self.graph.edges.keys() or not unavailable <= self.graph.stations.keys():+ raise StationError("unknown_navigation_obstruction", 422)+ async with self._lock:+ candidates = [+ record+ for record in (await self.store.snapshot(self.graph)).commands+ if record.state not in NAVIGATION_TERMINAL+ ]++ async def reauthorize(record):+ try:+ await self._authorize(record.agent_id, record.station_id, record.mode)+ except StationError as exc:+ return record.command_id, (+ "denied" if exc.status_code in {401, 403, 404} else "unavailable"+ )+ return record.command_id, "allowed"++ # At most 64 candidates; one unavailable authority cannot make the+ # controller await 64 sequential ten-second timeouts.+ authorization = dict(await asyncio.gather(*(reauthorize(row) for row in candidates)))++ ride_authorization = await self._ride_authorization()++ def step(world, now):+ records, leases = world.records, world.leases+ if self._unmapped_bodies(world):+ # Old edge IDs cannot prove separation from replacement+ # corridors. Keep every body fixed until geometry is mapped.+ leases.clear()+ for key, record in records.items():+ if record.state not in NAVIGATION_TERMINAL:+ records[key] = record.model_copy(+ update={+ "state": NavigationState.UNREACHABLE,+ "reason": "navigation_location_graph_changed",+ "updated_ms": now,+ }+ )+ for ride in list(world.rides.values()):+ self._stop_ride(world, ride, now, "navigation_location_graph_changed")+ return+ for key in [key for key, lease in leases.items() if lease.expires_ms <= now]:+ del leases[key]+ self._admit_rovers(world, now)+ attached = {ride.agent_id for ride in world.rides.values() if ride.attached}+ # Store supplies insertion order, so station/segment contention is FIFO.+ for key, record in records.items():+ if record.state in NAVIGATION_TERMINAL or record.agent_id in attached:+ continue+ decision = authorization.get(key, "unavailable")+ if decision == "denied":+ result = record.model_copy(+ update={+ "state": NavigationState.CANCELED,+ "reason": "navigation_not_authorized",+ "updated_ms": now,+ }+ )+ self._release(leases, key)+ elif decision == "unavailable":+ result = self._blocked(record, now, "navigation_authorization_unavailable")+ self._release(leases, key)+ else:+ occupancy = self._world_occupancy(world)+ result = self._advance_one(+ record, leases, occupancy, now, blocked, unavailable+ )+ records[key] = result+ if result.state in {NavigationState.UNREACHABLE, NavigationState.CANCELED}:+ self._release(leases, key)++ self._advance_rovers(world, now, blocked, unavailable, ride_authorization)++ await self.store.mutate_world(step)++ def _advance_one(+ self, record, leases, occupancy, now, blocked, unavailable+ ) -> NavigationRecord:+ if record.graph_signature != self.graph.signature:+ return record.model_copy(+ update={+ "state": NavigationState.UNREACHABLE,+ "reason": "navigation_graph_changed",+ "updated_ms": now,+ }+ )+ if now >= record.deadline_ms:+ return record.model_copy(+ update={+ "state": NavigationState.UNREACHABLE,+ "reason": "navigation_deadline_exceeded",+ "updated_ms": now,+ }+ )+ if record.station_id in unavailable:+ self._release(leases, record.command_id)+ return self._blocked(record, now, "destination_temporarily_unavailable")+ if not self._claim(leases, occupancy, "station:" + record.station_id, record, now):+ return record.model_copy(+ update={+ "state": NavigationState.QUEUEING,+ "reason": "physical_station_occupied",+ "updated_ms": now,+ }+ )+ if record.edge_id and record.edge_id in blocked:+ return self._blocked(record, now, "route_temporarily_blocked")+ if record.presence == "spawn_queue" and not self._available(+ leases, occupancy, "node:" + record.current_node, record+ ):+ return record.model_copy(+ update={+ "state": NavigationState.QUEUEING,+ "reason": "physical_spawn_occupied",+ "updated_ms": now,+ }+ )+ start = record.next_node if record.edge_id else record.current_node+ path = self.graph.path(start, record.station_id, record.mode, blocked)+ if path is None:+ self._release(leases, record.command_id)+ if self.graph.path(start, record.station_id, record.mode) is None:+ return record.model_copy(+ update={+ "state": NavigationState.UNREACHABLE,+ "reason": "navigation_route_unreachable",+ "updated_ms": now,+ }+ )+ return self._blocked(record, now, "route_temporarily_blocked")+ if record.presence == "spawn_queue":+ # Admit a new body only when its whole entry corridor is clear.+ # Reserving the console's approach while its previous occupant is+ # leaving would strand both agents head-on in a single-lane path.+ # A logical spawn waiter has no body and must yield to departures.+ corridor = ((record.edge_id,) if record.edge_id else ()) + path+ resources = {+ resource+ for edge_id in corridor+ for resource in (+ "edge:" + edge_id,+ "node:" + self.graph.edges[edge_id].start,+ "node:" + self.graph.edges[edge_id].end,+ )+ }+ if any(not self._available(leases, occupancy, item, record) for item in resources):+ intent = {}+ if record.edge_id is None and path:+ intent = {+ "edge_id": path[0],+ "next_node": self.graph.destination(path[0], record.current_node),+ "path": path[1:],+ }+ return record.model_copy(+ update={+ **intent,+ "state": NavigationState.QUEUEING,+ "reason": "physical_route_occupied",+ "updated_ms": now,+ }+ )+ if (+ record.path+ and any(edge in blocked for edge in record.path)+ and record.state is not NavigationState.REROUTING+ ):+ return record.model_copy(+ update={+ "state": NavigationState.REROUTING,+ "reason": "route_changed",+ "path": path,+ "updated_ms": now,+ }+ )+ seconds = min(max(now - record.updated_ms, 0), self.max_advance_ms) / 1000+ distance = seconds * (1.8 if record.mode is TravelMode.PEDESTRIAN else 4.0)+ # A gap cannot turn a parked/queued body into unchecked motion.+ if (+ record.state is NavigationState.QUEUEING+ and record.reason == "physical_station_occupied"+ ):+ distance = 0+ current = record.model_copy(+ update={"path": path, "updated_ms": now, "reason": "", "state": NavigationState.MOVING}+ )+ for _ in range(len(self.graph.edges) + 1):+ if current.edge_id is None:+ if current.current_node == self.graph.stations[current.station_id]:+ if not self._claim(+ leases, occupancy, "node:" + current.current_node, current, now+ ):+ return current.model_copy(+ update={+ "state": NavigationState.QUEUEING,+ "reason": "physical_destination_occupied",+ }+ )+ return current.model_copy(+ update={+ "state": NavigationState.ARRIVED,+ "path": (),+ "reason": "physical_destination_reached",+ "presence": "placed",+ }+ )+ if not current.path:+ return self._blocked(current, now, "route_temporarily_blocked")+ edge_id = current.path[0]+ current = current.model_copy(+ update={+ "edge_id": edge_id,+ "next_node": self.graph.destination(edge_id, current.current_node),+ "edge_progress": 0,+ "path": current.path[1:],+ }+ )+ resource_id = "edge:" + current.edge_id+ destination_id = "node:" + current.next_node+ if not all(+ self._available(leases, occupancy, resource, current)+ for resource in (+ resource_id,+ destination_id,+ )+ ):+ # A waiter outside an edge must not reserve it against a body+ # that needs that edge to leave the occupied endpoint.+ if current.edge_progress == 0:+ lease = leases.get(resource_id)+ if lease is not None and lease.owner == current.actor:+ del leases[resource_id]+ return current.model_copy(+ update={"state": NavigationState.QUEUEING, "reason": "physical_route_occupied"}+ )+ self._claim(leases, occupancy, resource_id, current, now)+ self._claim(leases, occupancy, destination_id, current, now)+ edge = self.graph.edges[current.edge_id]+ if (+ current.mode is TravelMode.ROVER+ and self.graph.geometry is not None+ and not self.graph.geometry.path_clear(+ self.graph.nodes[current.current_node],+ self.graph.nodes[current.next_node],+ width=3.4,+ length=4.8,+ height=2.6,+ )+ ):+ self._release(leases, current.command_id)+ return current.model_copy(+ update={+ "state": NavigationState.UNREACHABLE,+ "reason": "rover_route_clearance_failed",+ }+ )+ remaining = edge.length * (1 - current.edge_progress)+ moved = min(distance, remaining)+ fraction = min(1.0, current.edge_progress + moved / edge.length)+ current = current.model_copy(+ update={+ "edge_progress": fraction,+ "position": current.position+ if moved == 0+ else self.graph.position(current.current_node, current.next_node, fraction),+ "last_progress_ms": now if moved > 0 else current.last_progress_ms,+ "retries": 0 if moved > 0 else current.retries,+ "retry_at_ms": 0 if moved > 0 else current.retry_at_ms,+ "presence": "placed" if moved > 0 else current.presence,+ }+ )+ if moved > 0:+ departed_node = "node:" + current.current_node+ lease = leases.get(departed_node)+ if lease is not None and lease.owner == current.actor:+ del leases[departed_node]+ if fraction < 1:+ return current+ for item in self.graph.resources(resource_id):+ if item in leases and leases[item].owner == current.actor:+ del leases[item]+ distance -= moved+ current = current.model_copy(+ update={+ "current_node": current.next_node,+ "edge_id": None,+ "next_node": None,+ "edge_progress": 0,+ }+ )+ raise StationError("navigation_step_limit_exceeded", 503)diff --git a/jarvis/society/mars/navigation_store.py b/jarvis/society/mars/navigation_store.pynew file mode 100644index 0000000000..12de023d6b--- /dev/null+++ b/jarvis/society/mars/navigation_store.py@@ -0,0 +1,466 @@+"""Single-owner durable navigation journal and separate physical reservations."""++from __future__ import annotations++import asyncio+import hashlib+import json+import time+from collections.abc import AsyncIterator, Callable+from contextlib import asynccontextmanager+from dataclasses import dataclass, field+from pathlib import Path+from uuid import NAMESPACE_URL, uuid4, uuid5++import aiosqlite+from filelock import FileLock, Timeout+from pydantic import TypeAdapter++from .models import Identity, StationError+from .navigation import NavigationGraph+from .navigation_models import (+ NAVIGATION_TERMINAL,+ MoveCommand,+ NavigationLease,+ NavigationRecord,+ NavigationSnapshot,+ NavigationState,+ RoverRideRecord,+ VehicleRecord,+)+from .sqlite_transaction import atomic_transaction++_IDENTITY = TypeAdapter(Identity)+_SCHEMA = """+CREATE TABLE IF NOT EXISTS navigation_meta (+ id INTEGER PRIMARY KEY CHECK(id=1), version INTEGER NOT NULL, seq INTEGER NOT NULL+);+INSERT OR IGNORE INTO navigation_meta VALUES(1,1,0);+CREATE TABLE IF NOT EXISTS navigation_commands (+ ordinal INTEGER PRIMARY KEY AUTOINCREMENT, command_id TEXT UNIQUE NOT NULL,+ agent_id TEXT NOT NULL, fingerprint TEXT NOT NULL,+ state TEXT NOT NULL CHECK(state IN+ ('queueing','moving','temporarily_blocked','rerouting','arrived','unreachable','canceled')),+ record TEXT NOT NULL+);+CREATE INDEX IF NOT EXISTS navigation_agent ON navigation_commands(agent_id, ordinal);+CREATE TABLE IF NOT EXISTS navigation_motion_owners (command_id TEXT PRIMARY KEY);+CREATE TABLE IF NOT EXISTS navigation_leases (+ resource_id TEXT PRIMARY KEY,+ command_id TEXT NOT NULL REFERENCES navigation_motion_owners(command_id),+ record TEXT NOT NULL+);+CREATE TABLE IF NOT EXISTS rover_vehicles (+ vehicle_id TEXT PRIMARY KEY, record TEXT NOT NULL+);+CREATE TABLE IF NOT EXISTS rover_rides (+ ordinal INTEGER PRIMARY KEY AUTOINCREMENT,+ ride_id TEXT UNIQUE NOT NULL, agent_id TEXT NOT NULL, vehicle_id TEXT NOT NULL,+ state TEXT NOT NULL CHECK(state IN+ ('approaching','ready_to_board','boarded','traveling','arrived','stopped',+ 'exit_blocked','completed','canceled')), record TEXT NOT NULL+);+CREATE INDEX IF NOT EXISTS rover_rider ON rover_rides(agent_id, ordinal);+CREATE TABLE IF NOT EXISTS rover_actions (+ action_id TEXT PRIMARY KEY, fingerprint TEXT NOT NULL, ride_id TEXT NOT NULL+);+"""+++@dataclass+class NavigationWorld:+ records: dict[str, NavigationRecord]+ leases: dict[str, NavigationLease]+ vehicles: dict[str, VehicleRecord]+ rides: dict[str, RoverRideRecord]+ fingerprints: dict[str, str]+ actions: dict[str, tuple[str, str]] = field(default_factory=dict)+++class MarsNavigationStore:+ """Construction does no I/O; history preserves replay identity across restarts.++ The working set and snapshots are bounded, while durable command receipts+ remain on disk so an old retry cannot start a second journey.+ """++ def __init__(+ self,+ path: Path,+ *,+ clock_ms: Callable[[], int] | None = None,+ queue_limit: int = 64,+ actor_limit: int = 256,+ ) -> None:+ if not 1 <= queue_limit <= 64 or not 1 <= actor_limit <= 256:+ raise ValueError("invalid navigation queue limit")+ self.path = Path(path).resolve()+ self.clock = clock_ms or (lambda: time.time_ns() // 1_000_000)+ self.queue_limit = queue_limit+ self.actor_limit = actor_limit+ self._lock = asyncio.Lock()+ self._conn: aiosqlite.Connection | None = None+ self._owner: FileLock | None = None++ async def open(self) -> None:+ async with self._lock:+ if self._conn is not None:+ return+ self.path.parent.mkdir(parents=True, exist_ok=True)+ owner = FileLock(str(self.path) + ".owner.lock", thread_local=False)+ try:+ owner.acquire(timeout=0)+ except Timeout as exc:+ raise StationError("navigation_owned_by_another_process", 503) from exc+ conn = None+ try:+ conn = await aiosqlite.connect(self.path, isolation_level=None)+ conn.row_factory = aiosqlite.Row+ await conn.execute("PRAGMA journal_mode=WAL")+ await conn.execute("PRAGMA synchronous=FULL")+ await conn.execute("PRAGMA busy_timeout=5000")+ await conn.execute("PRAGMA foreign_keys=ON")+ await conn.executescript(_SCHEMA)+ row = await self._one(conn, "SELECT version FROM navigation_meta WHERE id=1")+ if row[0] == 1:+ async with atomic_transaction(conn):+ await conn.execute(+ "INSERT OR IGNORE INTO navigation_motion_owners SELECT command_id "+ "FROM navigation_commands"+ )+ # SQLite cannot alter the FK target in place. Keep all+ # leases and migrate their owner registry atomically.+ await conn.execute("ALTER TABLE navigation_leases RENAME TO legacy_leases")+ await conn.execute(+ "CREATE TABLE navigation_leases (resource_id TEXT PRIMARY KEY, "+ "command_id TEXT NOT NULL "+ "REFERENCES navigation_motion_owners(command_id), "+ "record TEXT NOT NULL)"+ )+ await conn.execute(+ "INSERT INTO navigation_leases SELECT * FROM legacy_leases"+ )+ await conn.execute("DROP TABLE legacy_leases")+ await conn.execute("UPDATE navigation_meta SET version=2 WHERE id=1")+ elif row[0] != 2:+ raise StationError("unsupported_navigation_storage_version", 503)+ self._conn, self._owner = conn, owner+ except BaseException:+ if conn is not None:+ await conn.close()+ owner.release()+ raise++ async def close(self) -> None:+ async with self._lock:+ try:+ if self._conn is not None:+ await self._conn.close()+ finally:+ self._conn = None+ if self._owner is not None:+ self._owner.release()+ self._owner = None++ @asynccontextmanager+ async def transaction(self) -> AsyncIterator[aiosqlite.Connection]:+ async with self._lock:+ if self._conn is None:+ raise StationError("navigation_not_started", 503)+ conn = self._conn+ async with atomic_transaction(conn):+ yield conn++ @staticmethod+ async def _one(conn: aiosqlite.Connection, sql: str, args: tuple = ()):+ async with conn.execute(sql, args) as cursor:+ return await cursor.fetchone()++ @staticmethod+ def identity(agent_id: str, request: MoveCommand) -> tuple[str, str]:+ _IDENTITY.validate_python(agent_id)+ command_id = "mars-move:" + str(+ uuid5(NAMESPACE_URL, json.dumps([agent_id, request.request_id]))+ )+ fingerprint = hashlib.sha256(request.model_dump_json().encode()).hexdigest()+ return command_id, fingerprint++ async def duplicate(self, agent_id: str, request: MoveCommand) -> NavigationRecord | None:+ command_id, fingerprint = self.identity(agent_id, request)+ async with self.transaction() as conn:+ row = await self._one(+ conn, "SELECT * FROM navigation_commands WHERE command_id=?", (command_id,)+ )+ if row is None:+ return None+ if row["fingerprint"] != fingerprint:+ raise StationError("idempotency_payload_mismatch", 409)+ return NavigationRecord.model_validate_json(row["record"])++ async def accept(+ self, agent_id: str, request: MoveCommand, graph: NavigationGraph, *, deadline_ms: int+ ) -> NavigationRecord:+ command_id, fingerprint = self.identity(agent_id, request)+ async with self.transaction() as conn:+ duplicate = await self._one(+ conn, "SELECT * FROM navigation_commands WHERE command_id=?", (command_id,)+ )+ if duplicate is not None:+ if duplicate["fingerprint"] != fingerprint:+ raise StationError("idempotency_payload_mismatch", 409)+ return NavigationRecord.model_validate_json(duplicate["record"])+ ride = await self._one(+ conn,+ "SELECT ride_id FROM rover_rides WHERE agent_id=? "+ "AND state NOT IN ('completed','canceled') LIMIT 1",+ (agent_id,),+ )+ if ride is not None:+ raise StationError("agent_has_rover_reservation", 409)+ active = await self._one(+ conn,+ "SELECT COUNT(*) FROM navigation_commands "+ "WHERE state NOT IN ('arrived','unreachable','canceled')",+ )+ if active[0] >= self.queue_limit:+ raise StationError("navigation_queue_full", 429)+ previous = await self._one(+ conn,+ "SELECT record FROM navigation_commands WHERE agent_id=? "+ "ORDER BY ordinal DESC LIMIT 1",+ (agent_id,),+ )+ prior = (+ NavigationRecord.model_validate_json(previous[0]) if previous is not None else None+ )+ if prior is None:+ actors = await self._one(+ conn, "SELECT COUNT(DISTINCT agent_id) FROM navigation_commands"+ )+ if actors[0] >= self.actor_limit:+ raise StationError("navigation_actor_limit_reached", 429)+ if prior is not None and prior.state not in NAVIGATION_TERMINAL:+ raise StationError("agent_already_moving", 409)+ if prior is not None and prior.graph_signature != graph.signature:+ raise StationError("navigation_location_graph_changed", 409)+ # A queued edge is only intent. Only an actually entered segment+ # carries physical progress into a new request after cancellation.+ transit = (+ prior+ if prior is not None+ and prior.presence == "placed"+ and prior.edge_id is not None+ and 0 < prior.edge_progress < 1+ else None+ )+ if transit is not None and transit.mode is not request.mode:+ raise StationError("navigation_mode_change_in_transit", 409)+ now = self.clock()+ record = NavigationRecord(+ command_id=command_id,+ request_id=request.request_id,+ agent_id=agent_id,+ trace_id=str(uuid4()),+ layout_version=graph.layout_version,+ graph_version=graph.version,+ graph_signature=graph.signature,+ station_id=request.station_id,+ mode=request.mode,+ state=NavigationState.QUEUEING,+ position=prior.position if prior else graph.nodes[graph.spawn_node],+ current_node=prior.current_node if prior else graph.spawn_node,+ edge_id=transit.edge_id if transit else None,+ next_node=transit.next_node if transit else None,+ edge_progress=transit.edge_progress if transit else 0,+ placement="persisted" if prior else "canonical_spawn",+ presence=prior.presence if prior else "spawn_queue",+ created_ms=now,+ updated_ms=now,+ last_progress_ms=now,+ deadline_ms=now + deadline_ms,+ )+ if prior is not None:+ await conn.execute(+ "DELETE FROM navigation_leases WHERE command_id=?", (prior.command_id,)+ )+ await conn.execute(+ "INSERT INTO navigation_motion_owners(command_id) VALUES(?)", (command_id,)+ )+ await conn.execute(+ "INSERT INTO navigation_commands(command_id,agent_id,fingerprint,state,record) "+ "VALUES(?,?,?,?,?)",+ (command_id, agent_id, fingerprint, record.state.value, record.model_dump_json()),+ )+ await conn.execute("UPDATE navigation_meta SET seq=seq+1 WHERE id=1")+ return record++ async def get(self, command_id: str) -> NavigationRecord:+ async with self.transaction() as conn:+ row = await self._one(+ conn, "SELECT record FROM navigation_commands WHERE command_id=?", (command_id,)+ )+ if row is None:+ raise StationError("navigation_command_not_found", 404)+ return NavigationRecord.model_validate_json(row[0])++ async def _load_world(self, conn, include_id=None) -> NavigationWorld:+ async with conn.execute(+ "SELECT command_id,record,fingerprint FROM navigation_commands "+ "WHERE state NOT IN ('arrived','unreachable','canceled') "+ "OR command_id IN (SELECT command_id FROM navigation_leases) "+ "OR ordinal IN (SELECT MAX(ordinal) FROM navigation_commands GROUP BY agent_id) "+ "OR command_id=? ORDER BY ordinal",+ (include_id,),+ ) as cursor:+ rows = await cursor.fetchall()+ async with conn.execute("SELECT resource_id,record FROM navigation_leases") as cursor:+ leases = {+ row[0]: NavigationLease.model_validate_json(row[1])+ for row in await cursor.fetchall()+ }+ async with conn.execute("SELECT vehicle_id,record FROM rover_vehicles") as cursor:+ vehicles = {+ row[0]: VehicleRecord.model_validate_json(row[1]) for row in await cursor.fetchall()+ }+ async with conn.execute(+ "SELECT ride_id,record FROM rover_rides WHERE state NOT IN ('completed','canceled') "+ "OR ordinal IN (SELECT ordinal FROM rover_rides ORDER BY ordinal DESC LIMIT 64) "+ "OR ordinal IN (SELECT MAX(ordinal) FROM rover_rides GROUP BY agent_id) "+ "ORDER BY ordinal"+ ) as cursor:+ rides = {+ row[0]: RoverRideRecord.model_validate_json(row[1])+ for row in await cursor.fetchall()+ }+ return NavigationWorld(+ {row[0]: NavigationRecord.model_validate_json(row[1]) for row in rows},+ leases,+ vehicles,+ rides,+ {row[0]: row[2] for row in rows},+ )++ async def mutate(self, operation, *, include_id: str | None = None) -> None:+ """Compatibility wrapper for pedestrian-only administrative updates."""+ await self.mutate_world(+ lambda world, now: operation(world.records, world.leases, now), include_id=include_id+ )++ async def mutate_world(self, operation, *, include_id: str | None = None) -> None:+ """Commit bodies, riders, seats and shared resource leases in one transaction."""+ async with self.transaction() as conn:+ world = await self._load_world(conn, include_id)+ before = repr(world)+ operation(world, self.clock())+ if before == repr(world):+ return+ for record in [*world.records.values(), *world.vehicles.values()]:+ await conn.execute(+ "INSERT OR IGNORE INTO navigation_motion_owners(command_id) VALUES(?)",+ (record.command_id,),+ )+ for record in world.records.values():+ await conn.execute(+ "INSERT INTO navigation_commands(command_id,agent_id,fingerprint,state,record) "+ "VALUES(?,?,?,?,?) ON CONFLICT(command_id) DO UPDATE SET "+ "state=excluded.state,record=excluded.record",+ (+ record.command_id,+ record.agent_id,+ world.fingerprints[record.command_id],+ record.state.value,+ record.model_dump_json(),+ ),+ )+ for vehicle in world.vehicles.values():+ await conn.execute(+ "INSERT INTO rover_vehicles VALUES(?,?) ON CONFLICT(vehicle_id) "+ "DO UPDATE SET record=excluded.record",+ (vehicle.vehicle_id, vehicle.model_dump_json()),+ )+ for ride in world.rides.values():+ await conn.execute(+ "INSERT INTO rover_rides(ride_id,agent_id,vehicle_id,state,record) "+ "VALUES(?,?,?,?,?) "+ "ON CONFLICT(ride_id) DO UPDATE SET "+ "state=excluded.state,record=excluded.record",+ (+ ride.ride_id,+ ride.agent_id,+ ride.vehicle_id,+ ride.state.value,+ ride.model_dump_json(),+ ),+ )+ for action_id, (fingerprint, ride_id) in world.actions.items():+ await conn.execute(+ "INSERT INTO rover_actions VALUES(?,?,?)", (action_id, fingerprint, ride_id)+ )+ await conn.execute("DELETE FROM navigation_leases")+ await conn.executemany(+ "INSERT INTO navigation_leases(resource_id,command_id,record) VALUES(?,?,?)",+ [+ (lease.resource_id, lease.command_id, lease.model_dump_json())+ for lease in world.leases.values()+ ],+ )+ await conn.execute("UPDATE navigation_meta SET seq=seq+1 WHERE id=1")++ async def get_ride(self, ride_id: str) -> RoverRideRecord:+ async with self.transaction() as conn:+ row = await self._one(+ conn, "SELECT record FROM rover_rides WHERE ride_id=?", (ride_id,)+ )+ if row is None:+ raise StationError("rover_ride_not_found", 404)+ return RoverRideRecord.model_validate_json(row[0])++ async def duplicate_action(self, action_id: str, fingerprint: str) -> RoverRideRecord | None:+ async with self.transaction() as conn:+ row = await self._one(+ conn,+ "SELECT fingerprint,ride_id FROM rover_actions WHERE action_id=?",+ (action_id,),+ )+ if row is None:+ return None+ if row[0] != fingerprint:+ raise StationError("idempotency_payload_mismatch", 409)+ ride = await self._one(+ conn, "SELECT record FROM rover_rides WHERE ride_id=?", (row[1],)+ )+ return RoverRideRecord.model_validate_json(ride[0])++ async def snapshot(self, graph: NavigationGraph) -> NavigationSnapshot:+ async with self.transaction() as conn:+ seq = await self._one(conn, "SELECT seq FROM navigation_meta WHERE id=1")+ world = await self._load_world(conn)+ # SQL ordinal, rather than a wall-clock tie, determines the latest+ # body when multiple commands were accepted within one clock tick.+ async with conn.execute(+ "SELECT command_id,record FROM navigation_commands "+ "WHERE state NOT IN ('arrived','unreachable','canceled') "+ "OR command_id IN (SELECT command_id FROM navigation_leases) "+ "OR ordinal IN (SELECT ordinal FROM navigation_commands "+ "ORDER BY ordinal DESC LIMIT 64) "+ "OR ordinal IN (SELECT MAX(ordinal) FROM navigation_commands GROUP BY agent_id) "+ "ORDER BY ordinal"+ ) as cursor:+ world.records = {+ row[0]: NavigationRecord.model_validate_json(row[1])+ for row in await cursor.fetchall()+ }+ return NavigationSnapshot(+ graph_version=graph.version,+ graph_signature=graph.signature,+ seq=seq[0],+ commands=tuple(world.records.values()),+ leases=tuple(sorted(world.leases.values(), key=lambda r: r.resource_id)),+ occupancies=graph.occupancies(+ list(world.records.values()),+ list(world.vehicles.values()),+ list(world.rides.values()),+ ),+ vehicles=tuple(world.vehicles.values()),+ rides=tuple(world.rides.values()),+ )diff --git a/jarvis/society/mars/ordinary.py b/jarvis/society/mars/ordinary.pynew file mode 100644index 0000000000..f3af41a0eb--- /dev/null+++ b/jarvis/society/mars/ordinary.py@@ -0,0 +1,174 @@+"""Adapt a Mars draft station to the existing ordinary-agent task authority."""++from __future__ import annotations++from typing import TYPE_CHECKING, Any++from jarvis.society.events import AgentState, MsgType, SocietyEnvelope++from .models import reject_draft_credentials++if TYPE_CHECKING:+ from jarvis.society.runtime import SocietyRuntime+++class OrdinaryStationExecutor:+ """No renderer callbacks, outgoing sends or alternative task scheduler."""++ def __init__(self, runtime: SocietyRuntime) -> None:+ self.runtime = runtime++ async def authorize(self, *, agent_id: str, capability_id: str) -> None:+ if capability_id != "communication-draft":+ raise PermissionError("station capability is unavailable")+ agent = await self.runtime.roster.get(agent_id)+ if agent is None or agent.state is not AgentState.ACTIVE:+ raise PermissionError("an active ordinary agent is required")+ if await self.runtime.store.kill_switch():+ raise PermissionError("agent execution is stopped")+ service = self.runtime.chat_service()+ if service is None:+ raise PermissionError("agent chat is unavailable")+ from jarvis.agent_chat.control import supports_restricted_turn+ from jarvis.society.chat_binding import ensure_session++ session = ensure_session(service, self.runtime.config(), agent)+ if not supports_restricted_turn(session):+ raise PermissionError("this agent runner cannot enforce a draft-only task")++ async def dispatch(+ self, *, agent_id: str, command_id: str, trace_id: str, draft: str+ ) -> dict[str, Any]:+ reject_draft_credentials(draft)+ await self.authorize(agent_id=agent_id, capability_id="communication-draft")+ event_id = f"mars-assign:{command_id}"+ previous = await self.runtime.store.get_event(event_id)+ if previous is None:+ await self.runtime.store.append_and_publish(+ SocietyEnvelope(+ event_id=event_id,+ msg_type=MsgType.ASSIGN,+ from_agent="user",+ to_agent=agent_id,+ trace_id=trace_id,+ payload={+ "text": (+ "Prepare a communication draft for review. "+ "Do not send or publish it.\n\n" + draft+ ),+ "runner": "chat",+ "read_only": True,+ "mars_command_id": command_id,+ },+ )+ )+ elif previous.to_agent != agent_id or previous.trace_id != trace_id:+ raise PermissionError("station command identity conflict")+ return await self.inspect(+ agent_id=agent_id, command_id=command_id, trace_id=trace_id, task_ref=None+ )++ async def inspect(+ self, *, agent_id: str, command_id: str, trace_id: str, task_ref: str | None+ ) -> dict[str, Any]:+ assignment_id = f"mars-assign:{command_id}"+ assignment = await self.runtime.store.get_event(assignment_id)+ if assignment is None or assignment.to_agent != agent_id or assignment.trace_id != trace_id:+ return {"state": "unknown"}+ events = await self.runtime.store.events_for_trace(trace_id)+ related = [event for event in events if event.parent_event_id == assignment_id]+ result = next(+ (+ event+ for event in reversed(related)+ if event.msg_type is MsgType.RESULT and event.from_agent == agent_id+ ),+ None,+ )+ claim = next(+ (+ event+ for event in related+ if event.msg_type is MsgType.CLAIM and event.from_agent == agent_id+ ),+ None,+ )+ # Ownership comes from the persisted assignment's own children, never+ # from a stale caller-supplied reference that could target a newer turn.+ source = result if result is not None else claim+ run_id = str(source.payload.get("run_id") or "") if source is not None else ""+ if task_ref and run_id and task_ref != run_id:+ return {"state": "unknown", "task_ref": task_ref}+ terminal = await self._chat_terminal(agent_id, run_id)+ if result is not None:+ state = "completed" if result.payload.get("status") == "done" else "failed"+ if terminal is not None and terminal["state"] == "canceled":+ state = "canceled"+ return {+ "state": state,+ "task_ref": result.payload.get("run_id"),+ "result_ref": result.event_id,+ }+ veto = next((event for event in related if event.msg_type is MsgType.VETO), None)+ if veto is not None:+ return {+ "state": "failed",+ "result_ref": veto.event_id,+ }+ # Chat commits its terminal event before the asynchronous Society+ # watcher writes RESULT. The gap cannot turn natural completion into a+ # cancellation, or lose a confirmed cancellation after a disconnect.+ if terminal is not None:+ return terminal+ if run_id and self.runtime.scheduler.running.get(run_id) == agent_id:+ return {"state": "active", "task_ref": run_id}+ return {+ "state": "unknown",+ "task_ref": run_id or task_ref,+ }++ async def _chat_terminal(self, agent_id: str, run_id: str) -> dict[str, Any] | None:+ if not run_id.startswith("turn:"):+ return None+ service = self.runtime.chat_service()+ agent = await self.runtime.roster.get(agent_id)+ if service is None or agent is None:+ return None+ terminal = service.store.turn_terminal(agent.session_id, run_id[5:])+ if terminal is None:+ return None+ status = str(terminal["payload"].get("status") or "")+ if status in {"ok", "done", "completed"}:+ state = "completed"+ elif status in {"canceled", "cancelled"}:+ state = "canceled"+ elif status in {"error", "failed", "blocked"}:+ state = "failed"+ else:+ return None+ return {+ "state": state,+ "task_ref": run_id,+ "result_ref": f"chat:{agent.session_id}#seq={terminal['seq']}",+ }++ async def cancel(+ self, *, agent_id: str, command_id: str, trace_id: str, task_ref: str | None+ ) -> dict[str, Any]:+ current = await self.inspect(+ agent_id=agent_id, command_id=command_id, trace_id=trace_id, task_ref=task_ref+ )+ if current["state"] in ("completed", "failed", "canceled"):+ return {**current, "cancel_attempt": "not_attempted"}+ run_id = current.get("task_ref")+ agent = await self.runtime.roster.get(agent_id)+ service = self.runtime.chat_service()+ if not agent or service is None or not str(run_id or "").startswith("turn:"):+ return {**current, "cancel_attempt": "not_attempted"}+ attempted = await service.cancel(agent.session_id, expected_turn_id=run_id[5:])+ # A True return means a stop was requested, not that the task ended by+ # cancellation: it may have finished naturally during the grace period.+ outcome = await self.inspect(+ agent_id=agent_id, command_id=command_id, trace_id=trace_id, task_ref=run_id+ )+ return {**outcome, "cancel_attempt": "attempted" if attempted else "not_attempted"}diff --git a/jarvis/society/mars/rover_service.py b/jarvis/society/mars/rover_service.pynew file mode 100644index 0000000000..0023a9e6cc--- /dev/null+++ b/jarvis/society/mars/rover_service.py@@ -0,0 +1,545 @@+"""Server-owned, one-seat route-driven rover actions inside navigation.db."""++from __future__ import annotations++import asyncio+import hashlib+import json+from uuid import NAMESPACE_URL, uuid4, uuid5++from pydantic import TypeAdapter++from .models import Identity, StationError+from .navigation_migration import migrate_record+from .navigation_models import (+ NAVIGATION_TERMINAL,+ RIDE_TERMINAL,+ MoveCommand,+ NavigationRecord,+ NavigationState,+ RideState,+ RoverActionCommand,+ RoverReserveCommand,+ RoverRideRecord,+ RoverTravelCommand,+ TravelMode,+ VehicleRecord,+)++_IDENTITY = TypeAdapter(Identity)+++class RoverServiceMixin:+ """Uses the navigation service lock, owner, store and physical allocator.++ Reservations expire after ten wall-clock minutes including process downtime.+ Expiry revokes an unboarded reservation; boarded rides stop exactly in place+ and retain their seat until an explicit safe exit. A fresh travel action gets+ a fresh bounded deadline. Neither client absence nor wall time advances a body.+ """++ def _world_occupancy(self, world):+ return self.graph.occupancies(+ list(world.records.values()), list(world.vehicles.values()), list(world.rides.values())+ )++ def _recover_rovers(self, world, now):+ for key, record in world.records.items():+ world.records[key] = migrate_record(record, self.graph)+ for key, vehicle in world.vehicles.items():+ world.vehicles[key] = migrate_record(vehicle, self.graph).model_copy(+ update={"updated_ms": now}+ )+ # A changed graph cannot place a new vehicle over an unmigrated old body.+ if any(+ row.graph_signature != self.graph.signature+ for row in [*world.records.values(), *world.vehicles.values()]+ ):+ return+ for vehicle_id, spec in self.graph.rovers.items():+ if vehicle_id in world.vehicles:+ continue+ dock = self.graph.docks[spec["home_dock_id"]]+ node = dock["node_id"]+ command_id = "mars-rover:" + str(uuid5(NAMESPACE_URL, vehicle_id))+ world.vehicles[vehicle_id] = VehicleRecord(+ vehicle_id=vehicle_id,+ command_id=command_id,+ request_id=command_id,+ trace_id=str(uuid4()),+ graph_version=self.graph.version,+ graph_signature=self.graph.signature,+ layout_version=self.graph.layout_version,+ station_id="rover-dock:" + dock["id"],+ mode=TravelMode.ROVER,+ state=NavigationState.ARRIVED,+ position=self.graph.nodes[node],+ current_node=node,+ placement="canonical_spawn",+ presence="spawn_queue",+ created_ms=now,+ updated_ms=now,+ last_progress_ms=now,+ deadline_ms=now + self.deadline_ms,+ )+ self._admit_rovers(world, now)++ def _admit_rovers(self, world, now):+ if self._unmapped_bodies(world):+ return+ for key, vehicle in world.vehicles.items():+ if vehicle.presence != "spawn_queue" or vehicle.graph_signature != self.graph.signature:+ continue+ if self._available(+ world.leases, self._world_occupancy(world), "node:" + vehicle.current_node, vehicle+ ):+ world.vehicles[key] = vehicle.model_copy(+ update={"presence": "placed", "updated_ms": now}+ )++ def _unmapped_bodies(self, world):+ return any(+ body.graph_signature != self.graph.signature for body in self._world_occupancy(world)+ )++ @staticmethod+ def _rover_identity(agent_id, action, ride_id, request):+ _IDENTITY.validate_python(agent_id)+ action_id = "mars-rover-action:" + str(+ uuid5(NAMESPACE_URL, json.dumps([agent_id, request.request_id]))+ )+ payload = json.dumps(+ [action, ride_id, request.model_dump(mode="json")],+ sort_keys=True,+ separators=(",", ":"),+ )+ return action_id, hashlib.sha256(payload.encode()).hexdigest()++ async def reserve_ride(self, agent_id: str, request: RoverReserveCommand) -> RoverRideRecord:+ async with self._lock:+ action_id, fingerprint = self._rover_identity(agent_id, "reserve", None, request)+ duplicate = await self.store.duplicate_action(action_id, fingerprint)+ if duplicate is not None:+ return duplicate+ if (+ request.graph_version != self.graph.version+ or request.layout_version != self.graph.layout_version+ ):+ raise StationError("navigation_graph_version_mismatch", 409)+ if request.vehicle_id not in self.graph.rovers:+ raise StationError("rover_not_found", 404)+ await self._authorize(agent_id, request.vehicle_id, TravelMode.ROVER, rover=True)+ ride_id = "mars-ride:" + str(uuid5(NAMESPACE_URL, action_id))++ def reserve(world, now):+ if self._unmapped_bodies(world):+ raise StationError("navigation_location_graph_changed", 409)+ vehicle = world.vehicles.get(request.vehicle_id)+ if vehicle is None or vehicle.presence != "placed":+ raise StationError("rover_not_ready", 409)+ if vehicle.graph_signature != self.graph.signature:+ raise StationError("navigation_location_graph_changed", 409)+ if any(+ ride.state not in RIDE_TERMINAL and ride.agent_id == agent_id+ for ride in world.rides.values()+ ):+ raise StationError("agent_has_rover_reservation", 409)+ if any(+ ride.state not in RIDE_TERMINAL and ride.vehicle_id == request.vehicle_id+ for ride in world.rides.values()+ ):+ raise StationError("rover_seat_reserved", 409)+ dock_id = self._vehicle_dock(vehicle)+ if dock_id is None:+ raise StationError("rover_not_at_dock", 409)+ dock = self.graph.docks[dock_id]+ move = MoveCommand(+ request_id="rover-approach:" + str(uuid5(NAMESPACE_URL, ride_id)),+ station_id=dock["boarding_station_id"],+ graph_version=self.graph.version,+ layout_version=self.graph.layout_version,+ )+ command_id, move_fingerprint = self.store.identity(agent_id, move)+ prior = next(+ (+ row+ for row in reversed(list(world.records.values()))+ if row.agent_id == agent_id+ ),+ None,+ )+ if prior and prior.state not in NAVIGATION_TERMINAL:+ raise StationError("agent_already_moving", 409)+ if prior and prior.graph_signature != self.graph.signature:+ raise StationError("navigation_location_graph_changed", 409)+ if (+ sum(row.state not in NAVIGATION_TERMINAL for row in world.records.values())+ >= self.store.queue_limit+ ):+ raise StationError("navigation_queue_full", 429)+ if (+ prior is None+ and len({row.agent_id for row in world.records.values()})+ >= self.store.actor_limit+ ):+ raise StationError("navigation_actor_limit_reached", 429)+ transit = prior if prior and prior.edge_id and 0 < prior.edge_progress < 1 else None+ record = NavigationRecord(+ command_id=command_id,+ request_id=move.request_id,+ agent_id=agent_id,+ trace_id=str(uuid4()),+ layout_version=self.graph.layout_version,+ graph_version=self.graph.version,+ graph_signature=self.graph.signature,+ station_id=move.station_id,+ mode=TravelMode.PEDESTRIAN,+ state=NavigationState.QUEUEING,+ position=prior.position if prior else self.graph.nodes[self.graph.spawn_node],+ current_node=prior.current_node if prior else self.graph.spawn_node,+ edge_id=transit.edge_id if transit else None,+ next_node=transit.next_node if transit else None,+ edge_progress=transit.edge_progress if transit else 0,+ placement="persisted" if prior else "canonical_spawn",+ presence=prior.presence if prior else "spawn_queue",+ created_ms=now,+ updated_ms=now,+ last_progress_ms=now,+ deadline_ms=now + self.deadline_ms,+ )+ if prior:+ self._release(world.leases, prior.command_id)+ world.records[command_id] = record+ world.fingerprints[command_id] = move_fingerprint+ world.rides[ride_id] = RoverRideRecord(+ ride_id=ride_id,+ request_id=request.request_id,+ agent_id=agent_id,+ vehicle_id=request.vehicle_id,+ trace_id=record.trace_id,+ origin_dock_id=dock_id,+ approach_command_id=command_id,+ state=RideState.APPROACHING,+ created_ms=now,+ updated_ms=now,+ deadline_ms=now + self.deadline_ms,+ )+ world.vehicles[vehicle.vehicle_id] = vehicle.model_copy(update={"ride_id": ride_id})+ world.actions[action_id] = (fingerprint, ride_id)++ await self.store.mutate_world(reserve)+ return await self.store.get_ride(ride_id)++ async def _ride_action(self, action, agent_id, ride_id, request):+ async with self._lock:+ action_id, fingerprint = self._rover_identity(agent_id, action, ride_id, request)+ duplicate = await self.store.duplicate_action(action_id, fingerprint)+ if duplicate is not None:+ return duplicate+ prior = await self.store.get_ride(ride_id)+ if prior.agent_id != agent_id:+ raise StationError("rover_ride_not_found", 404)+ await self._authorize(agent_id, prior.vehicle_id, TravelMode.ROVER, rover=True)++ def apply(world, now):+ ride = world.rides.get(ride_id)+ # A retained durable receipt outside the bounded working set is+ # terminal; include it solely to replay a no-op cancellation.+ if ride is None:+ ride = prior+ world.rides[ride_id] = ride+ vehicle = world.vehicles[ride.vehicle_id]+ if action == "cancel":+ self._stop_ride(world, ride, now, "user_canceled")+ else:+ if self._unmapped_bodies(world):+ raise StationError("navigation_location_graph_changed", 409)+ if ride.state in RIDE_TERMINAL:+ raise StationError("rover_ride_finished", 409)+ if vehicle.graph_signature != self.graph.signature:+ raise StationError("navigation_location_graph_changed", 409)+ if action == "board":+ self._board_ride(world, ride, vehicle, now)+ elif action == "travel":+ self._travel_ride(world, ride, vehicle, request.destination_dock_id, now)+ elif action == "exit":+ self._exit_ride(world, ride, vehicle, now)+ world.actions[action_id] = (fingerprint, ride_id)++ await self.store.mutate_world(apply, include_id=prior.approach_command_id)+ return await self.store.get_ride(ride_id)++ async def board_ride(+ self, agent_id: str, ride_id: str, request: RoverActionCommand+ ) -> RoverRideRecord:+ return await self._ride_action("board", agent_id, ride_id, request)++ async def travel_ride(+ self, agent_id: str, ride_id: str, request: RoverTravelCommand+ ) -> RoverRideRecord:+ return await self._ride_action("travel", agent_id, ride_id, request)++ async def cancel_ride(+ self, agent_id: str, ride_id: str, request: RoverActionCommand+ ) -> RoverRideRecord:+ return await self._ride_action("cancel", agent_id, ride_id, request)++ async def exit_ride(+ self, agent_id: str, ride_id: str, request: RoverActionCommand+ ) -> RoverRideRecord:+ return await self._ride_action("exit", agent_id, ride_id, request)++ async def rover_snapshot(self):+ return await self.snapshot()++ def _vehicle_dock(self, vehicle):+ if vehicle.edge_id is not None and 0 < vehicle.edge_progress < 1:+ return None+ return next(+ (+ key+ for key, dock in self.graph.docks.items()+ if dock["node_id"] == vehicle.current_node+ ),+ None,+ )++ def _board_ride(self, world, ride, vehicle, now):+ if ride.state is not RideState.READY_TO_BOARD or ride.attached:+ raise StationError("rover_rider_not_ready", 409)+ if now >= ride.deadline_ms:+ raise StationError("rover_reservation_expired", 409)+ dock = self.graph.docks[ride.origin_dock_id]+ agent = world.records[ride.approach_command_id]+ if (+ agent.state is not NavigationState.ARRIVED+ or agent.presence != "placed"+ or agent.current_node != self.graph.stations[dock["boarding_station_id"]]+ or self._vehicle_dock(vehicle) != ride.origin_dock_id+ or vehicle.presence != "placed"+ ):+ raise StationError("rover_rider_not_at_boarding_anchor", 409)+ if not self.graph.geometry.capsule_clear(agent.position):+ raise StationError("rover_boarding_clearance_failed", 409)+ self._release(world.leases, agent.command_id)+ world.rides[ride.ride_id] = ride.model_copy(+ update={"state": RideState.BOARDED, "attached": True, "updated_ms": now}+ )++ def _travel_ride(self, world, ride, vehicle, destination, now):+ if not ride.attached or ride.state is RideState.TRAVELING:+ raise StationError("rover_rider_not_ready", 409)+ if destination not in self.graph.docks:+ raise StationError("rover_dock_not_found", 404)+ station = "rover-dock:" + destination+ start = (+ vehicle.next_node+ if vehicle.edge_id and 0 < vehicle.edge_progress < 1+ else vehicle.current_node+ )+ path = self.graph.path(start, station, TravelMode.ROVER)+ if path is None:+ raise StationError("rover_route_unreachable", 409)+ for edge_id in (+ *((vehicle.edge_id,) if vehicle.edge_id and 0 < vehicle.edge_progress < 1 else ()),+ *path,+ ):+ edge = self.graph.edges[edge_id]+ if not self.graph.geometry.path_clear(+ self.graph.nodes[edge.start],+ self.graph.nodes[edge.end],+ width=3.4,+ length=4.8,+ height=2.6,+ ):+ raise StationError("rover_route_clearance_failed", 409)+ self._release(world.leases, vehicle.command_id)+ updates = {+ "station_id": station,+ "state": NavigationState.QUEUEING,+ "path": (),+ "updated_ms": now,+ "deadline_ms": now + self.deadline_ms,+ "reason": "",+ "retries": 0,+ "retry_at_ms": 0,+ }+ if not (vehicle.edge_id and 0 < vehicle.edge_progress < 1):+ updates.update(edge_id=None, next_node=None, edge_progress=0)+ world.vehicles[vehicle.vehicle_id] = vehicle.model_copy(update=updates)+ world.rides[ride.ride_id] = ride.model_copy(+ update={+ "state": RideState.TRAVELING,+ "destination_dock_id": destination,+ "updated_ms": now,+ "deadline_ms": now + self.deadline_ms,+ "reason": "",+ }+ )++ def _stop_ride(self, world, ride, now, reason):+ if ride.state in RIDE_TERMINAL:+ return+ vehicle = world.vehicles[ride.vehicle_id]+ self._release(world.leases, vehicle.command_id)+ if ride.attached:+ world.vehicles[vehicle.vehicle_id] = vehicle.model_copy(+ update={"state": NavigationState.CANCELED, "updated_ms": now, "reason": reason}+ )+ world.rides[ride.ride_id] = ride.model_copy(+ update={"state": RideState.STOPPED, "updated_ms": now, "reason": reason}+ )+ else:+ agent = world.records.get(ride.approach_command_id)+ if agent is not None:+ self._release(world.leases, agent.command_id)+ world.records[agent.command_id] = agent.model_copy(+ update={"state": NavigationState.CANCELED, "updated_ms": now, "reason": reason}+ )+ world.vehicles[vehicle.vehicle_id] = vehicle.model_copy(update={"ride_id": None})+ world.rides[ride.ride_id] = ride.model_copy(+ update={"state": RideState.CANCELED, "updated_ms": now, "reason": reason}+ )++ def _exit_ride(self, world, ride, vehicle, now):+ if not ride.attached:+ raise StationError("rover_rider_not_boarded", 409)+ dock_id = self._vehicle_dock(vehicle)+ if ride.state is RideState.TRAVELING or dock_id is None:+ world.rides[ride.ride_id] = ride.model_copy(+ update={+ "state": RideState.EXIT_BLOCKED,+ "updated_ms": now,+ "reason": "rover_exit_requires_stopped_dock",+ }+ )+ # An exit request is a bounded safe stop, never mid-road detachment.+ world.vehicles[vehicle.vehicle_id] = vehicle.model_copy(+ update={"state": NavigationState.CANCELED, "updated_ms": now}+ )+ self._release(world.leases, vehicle.command_id)+ return+ agent = world.records[ride.approach_command_id]+ occupancy = self._world_occupancy(world)+ for station in self.graph.docks[dock_id]["exit_station_ids"]:+ node = self.graph.stations[station]+ position = self.graph.nodes[node]+ if (+ station in getattr(self, "_rover_unavailable", frozenset())+ or not self.graph.geometry.capsule_clear(position)+ or not self._available(world.leases, occupancy, "node:" + node, agent)+ or not self._available(world.leases, occupancy, "station:" + station, agent)+ ):+ continue+ world.records[agent.command_id] = agent.model_copy(+ update={+ "state": NavigationState.ARRIVED,+ "station_id": station,+ "current_node": node,+ "position": position,+ "edge_id": None,+ "next_node": None,+ "edge_progress": 0,+ "presence": "placed",+ "placement": "persisted",+ "updated_ms": now,+ "graph_signature": self.graph.signature,+ "graph_version": self.graph.version,+ "path": (),+ "reason": "rover_exit_completed",+ }+ )+ self._release(world.leases, vehicle.command_id)+ world.vehicles[vehicle.vehicle_id] = vehicle.model_copy(+ update={+ "ride_id": None,+ "state": NavigationState.ARRIVED,+ "updated_ms": now,+ "station_id": "rover-dock:" + dock_id,+ "reason": "",+ }+ )+ world.rides[ride.ride_id] = ride.model_copy(+ update={+ "state": RideState.COMPLETED,+ "attached": False,+ "updated_ms": now,+ "reason": "rover_exit_completed",+ }+ )+ return+ world.rides[ride.ride_id] = ride.model_copy(+ update={+ "state": RideState.EXIT_BLOCKED,+ "updated_ms": now,+ "reason": "rover_exit_occupied",+ }+ )++ async def _ride_authorization(self):+ rides = (await self.store.snapshot(self.graph)).rides++ async def check(ride):+ try:+ await self._authorize(ride.agent_id, ride.vehicle_id, TravelMode.ROVER, rover=True)+ except StationError as exc:+ return ride.ride_id, "denied" if exc.status_code in {+ 401,+ 403,+ 404,+ } else "unavailable"+ return ride.ride_id, "allowed"++ return dict(+ await asyncio.gather(+ *(check(ride) for ride in rides if ride.state not in RIDE_TERMINAL)+ )+ )++ def _advance_rovers(self, world, now, blocked, unavailable, authorization):+ self._rover_unavailable = unavailable+ for ride_id, ride in world.rides.items():+ if ride.state in RIDE_TERMINAL:+ continue+ vehicle = world.vehicles[ride.vehicle_id]+ decision = authorization.get(ride_id, "unavailable")+ if decision == "denied" or now >= ride.deadline_ms:+ self._stop_ride(+ world,+ ride,+ now,+ "navigation_not_authorized"+ if decision == "denied"+ else "rover_deadline_exceeded",+ )+ continue+ if decision != "allowed":+ # No elapsed-time catch-up after authority returns.+ world.vehicles[vehicle.vehicle_id] = vehicle.model_copy(update={"updated_ms": now})+ continue+ if ride.state is RideState.APPROACHING:+ agent = world.records[ride.approach_command_id]+ if agent.state is NavigationState.ARRIVED:+ world.rides[ride_id] = ride.model_copy(+ update={"state": RideState.READY_TO_BOARD, "updated_ms": now}+ )+ elif agent.state in {NavigationState.CANCELED, NavigationState.UNREACHABLE}:+ self._stop_ride(world, ride, now, "rover_approach_failed")+ elif ride.state is RideState.TRAVELING:+ result = self._advance_one(+ vehicle, world.leases, self._world_occupancy(world), now, blocked, unavailable+ )+ world.vehicles[vehicle.vehicle_id] = result+ if result.state is NavigationState.ARRIVED:+ world.rides[ride_id] = ride.model_copy(+ update={"state": RideState.ARRIVED, "updated_ms": now}+ )+ elif result.state in {NavigationState.UNREACHABLE, NavigationState.CANCELED}:+ self._release(world.leases, vehicle.command_id)+ world.rides[ride_id] = ride.model_copy(+ update={+ "state": RideState.STOPPED,+ "updated_ms": now,+ "reason": result.reason,+ }+ )diff --git a/jarvis/society/mars/schema.sql b/jarvis/society/mars/schema.sqlnew file mode 100644index 0000000000..aa55b3c233--- /dev/null+++ b/jarvis/society/mars/schema.sql@@ -0,0 +1,53 @@+CREATE TABLE IF NOT EXISTS mars_meta (+ key TEXT PRIMARY KEY,+ value INTEGER NOT NULL+);++CREATE TABLE IF NOT EXISTS mars_commands (+ command_id TEXT PRIMARY KEY,+ world_id TEXT NOT NULL CHECK (world_id = 'mars:ordinary'),+ station_id TEXT NOT NULL CHECK (station_id = 'communications-console'),+ capability_id TEXT NOT NULL CHECK (capability_id = 'communication-draft'),+ agent_id TEXT NOT NULL,+ request_id TEXT NOT NULL,+ fingerprint TEXT NOT NULL,+ trace_id TEXT NOT NULL UNIQUE,+ draft TEXT NOT NULL CHECK (length(draft) BETWEEN 1 AND 4000),+ state TEXT NOT NULL CHECK (+ state IN ('queued','active','completed','failed','canceled','interrupted','unknown')+ ),+ created_ms INTEGER NOT NULL,+ updated_ms INTEGER NOT NULL,+ fence INTEGER NOT NULL DEFAULT 0,+ task_ref TEXT,+ result_ref TEXT,+ reason TEXT NOT NULL DEFAULT '',+ cancel_requested INTEGER NOT NULL DEFAULT 0 CHECK (cancel_requested IN (0, 1)),+ cancel_dispatched INTEGER NOT NULL DEFAULT 0 CHECK (cancel_dispatched IN (0, 1)),+ UNIQUE(world_id, agent_id, request_id)+);+CREATE INDEX IF NOT EXISTS mars_commands_pending ON mars_commands(state, created_ms);++-- The monotonically increasing generation survives every release and process restart.+CREATE TABLE IF NOT EXISTS mars_station (+ station_id TEXT PRIMARY KEY CHECK (station_id = 'communications-console'),+ generation INTEGER NOT NULL DEFAULT 0,+ command_id TEXT REFERENCES mars_commands(command_id),+ expires_ms INTEGER NOT NULL DEFAULT 0+);++CREATE TABLE IF NOT EXISTS mars_events (+ seq INTEGER PRIMARY KEY AUTOINCREMENT,+ command_id TEXT NOT NULL,+ trace_id TEXT NOT NULL,+ agent_id TEXT NOT NULL,+ state TEXT NOT NULL CHECK (+ state IN ('queued','active','completed','failed','canceled','interrupted','unknown')+ ),+ fence INTEGER NOT NULL,+ task_ref TEXT,+ result_ref TEXT,+ reason TEXT NOT NULL,+ cancel_requested INTEGER NOT NULL,+ ts_ms INTEGER NOT NULL+);diff --git a/jarvis/society/mars/service.py b/jarvis/society/mars/service.pynew file mode 100644index 0000000000..77afa66af1--- /dev/null+++ b/jarvis/society/mars/service.py@@ -0,0 +1,204 @@+"""Station resource coordination over an injected trusted executor, never a renderer.++The application owns this service and calls ``reconcile`` periodically while its+backend runs. This class does not run agents, choose providers, or install another+job scheduler. Only the existing execution adapter can accept or complete work.+"""++from __future__ import annotations++import asyncio+import logging+from typing import TYPE_CHECKING++from .models import (+ CAPABILITY_ID,+ TERMINAL_STATES,+ CommandRecord,+ CommandState,+ DispatchRejected,+ ExecutionReceipt,+ StationCommand,+ StationError,+ StationEventBatch,+ StationSnapshot,+ reject_draft_credentials,+)+from .store import MarsStore++if TYPE_CHECKING:+ from jarvis.core.protocols import MarsStationExecutor++log = logging.getLogger(__name__)+++class MarsStationService:+ def __init__(+ self,+ store: MarsStore,+ executor: MarsStationExecutor,+ *,+ operation_timeout_s: float = 10.0,+ cancellation_timeout_s: float = 20.0,+ ) -> None:+ if operation_timeout_s <= 0 or cancellation_timeout_s <= 0:+ raise ValueError("operation timeout must be positive")+ self.store = store+ self.executor = executor+ self._timeout = operation_timeout_s+ self._cancel_timeout = cancellation_timeout_s+ self._coordination = asyncio.Lock()+ self._lifecycle = asyncio.Lock()+ self._background: set[asyncio.Task[None]] = set()+ self._started = False++ async def start(self) -> None:+ async with self._lifecycle:+ if not self._started:+ await self.store.open()+ self._started = True++ async def close(self) -> None:+ """Release local resources. Backend stop/cancel policy remains application-owned."""+ async with self._lifecycle:+ self._started = False+ tasks = tuple(self._background)+ for task in tasks:+ task.cancel()+ if tasks:+ await asyncio.gather(*tasks, return_exceptions=True)+ self._background.clear()+ async with self._coordination:+ await self.store.close()++ async def _authorize(self, agent_id: str) -> None:+ try:+ await asyncio.wait_for(+ self.executor.authorize(agent_id=agent_id, capability_id=CAPABILITY_ID),+ timeout=self._timeout,+ )+ except StationError:+ raise+ except Exception as exc:+ log.warning("Mars station authorization unavailable (%s)", type(exc).__name__)+ raise StationError("station_authority_unavailable", 503) from exc++ def _wake(self) -> None:+ # At most one queued wakeup; periodic reconciliation is owned by the app.+ if not self._started or self._background:+ return+ task = asyncio.create_task(self._reconcile_safely(), name="mars-station-reconcile")+ self._background.add(task)+ task.add_done_callback(self._background.discard)++ async def _reconcile_safely(self) -> None:+ try:+ await self.reconcile()+ except Exception as exc:+ # No provider response or private draft is copied into logs or event labels.+ log.warning("Mars station reconciliation failed (%s)", type(exc).__name__)++ async def submit(self, agent_id: str, command: StationCommand) -> CommandRecord:+ reject_draft_credentials(command.draft)+ await self.start()+ await self._authorize(agent_id)+ record = await self.store.submit(agent_id, command)+ self._wake()+ return record++ async def cancel(self, agent_id: str, command_id: str) -> CommandRecord:+ await self.start()+ # The authenticated controller must be able to stop its own job after a+ # capability was revoked. Store ownership guards this path independently.+ record = await self.store.request_cancel(agent_id, command_id)+ self._wake()+ return record++ async def snapshot(self) -> StationSnapshot:+ await self.start()+ return await self.store.snapshot()++ async def events(self, after_seq: int, *, limit: int = 100) -> StationEventBatch:+ await self.start()+ return await self.store.events(after_seq, limit=limit)++ async def reconcile(self) -> None:+ """One bounded station step. No browser connection or animation is involved."""+ if not self._started:+ return+ async with self._coordination:+ if not self._started:+ return+ current = await self.store.current()+ if current is not None:+ if current.cancel_requested and not current.cancel_dispatched:+ current = await self.store.begin_cancel(current.command_id, current.fence)+ await self._execution_step(current, "cancel")+ else:+ await self._execution_step(current, "inspect")+ return+ claimed = await self.store.claim_next()+ if claimed is None:+ return+ # A queued command's grants/agent state may have changed while waiting.+ try:+ await self._authorize(claimed.agent_id)+ except StationError as exc:+ await self.store.apply(+ claimed.command_id,+ claimed.fence,+ ExecutionReceipt(state=CommandState.FAILED),+ reason=exc.reason,+ )+ return+ await self._execution_step(claimed, "dispatch")++ async def _execution_step(self, record: CommandRecord, operation: str) -> None:+ args = {+ "agent_id": record.agent_id,+ "command_id": record.command_id,+ "trace_id": record.trace_id,+ }+ reason = ""+ try:+ if operation == "dispatch":+ call = self.executor.dispatch(**args, draft=record.draft)+ elif operation == "cancel":+ call = self.executor.cancel(**args, task_ref=record.task_ref)+ else:+ call = self.executor.inspect(**args, task_ref=record.task_ref)+ timeout = self._cancel_timeout if operation == "cancel" else self._timeout+ raw = await asyncio.wait_for(call, timeout=timeout)+ receipt = ExecutionReceipt.model_validate(raw, strict=False)+ if operation != "cancel" and receipt.cancel_attempt is not None:+ raise ValueError("cancellation attempt evidence belongs only to cancel receipts")+ except DispatchRejected as exc:+ if operation == "dispatch":+ receipt = ExecutionReceipt(state=CommandState.FAILED)+ reason = exc.reason+ else:+ receipt = ExecutionReceipt(state=CommandState.UNKNOWN)+ reason = "execution_outcome_unknown"+ except asyncio.CancelledError:+ await self.store.apply(+ record.command_id,+ record.fence,+ ExecutionReceipt(state=CommandState.UNKNOWN),+ reason="execution_outcome_unknown",+ )+ raise+ except Exception as exc:+ log.warning("Mars station %s outcome uncertain (%s)", operation, type(exc).__name__)+ receipt = ExecutionReceipt(state=CommandState.UNKNOWN)+ reason = "execution_outcome_unknown"+ if receipt.state in {CommandState.UNKNOWN, CommandState.INTERRUPTED} and not reason:+ reason = (+ "execution_outcome_unknown"+ if receipt.state is CommandState.UNKNOWN+ else "execution_interrupted"+ )+ if operation == "cancel" and receipt.cancel_attempt == "not_attempted":+ reason = "cancel_not_attempted" if receipt.state not in TERMINAL_STATES else ""+ if record.cancel_requested and receipt.state not in TERMINAL_STATES and not reason:+ reason = "cancel_pending"+ await self.store.apply(record.command_id, record.fence, receipt, reason=reason)diff --git a/jarvis/society/mars/sqlite_transaction.py b/jarvis/society/mars/sqlite_transaction.pynew file mode 100644index 0000000000..54a1fd0de9--- /dev/null+++ b/jarvis/society/mars/sqlite_transaction.py@@ -0,0 +1,41 @@+"""Cancellation-safe transaction cleanup for the two process-owned Mars journals."""++from __future__ import annotations++import asyncio+from collections.abc import AsyncIterator+from contextlib import asynccontextmanager++import aiosqlite+++async def _finish_rollback(connection: aiosqlite.Connection) -> None:+ # aiosqlite queues work on a thread: canceling its await does not cancel the+ # SQL statement. Rollback is queued behind BEGIN or any pending write and+ # must finish before the caller releases the connection's ownership lock.+ rollback = asyncio.create_task(connection.rollback(), name="mars-sqlite-rollback")+ canceled = False+ while not rollback.done():+ try:+ await asyncio.shield(rollback)+ except asyncio.CancelledError:+ # A second stop/cancel may arrive during cleanup. Keep joining the+ # owned rollback, then propagate cancellation after SQL is settled.+ canceled = True+ rollback.result()+ if canceled:+ raise asyncio.CancelledError+++@asynccontextmanager+async def atomic_transaction(+ connection: aiosqlite.Connection,+) -> AsyncIterator[aiosqlite.Connection]:+ """Caller holds its journal lock throughout BEGIN, work and rollback/commit."""+ try:+ await connection.execute("BEGIN IMMEDIATE")+ yield connection+ await connection.commit()+ except BaseException:+ await _finish_rollback(connection)+ raisediff --git a/jarvis/society/mars/store.py b/jarvis/society/mars/store.pynew file mode 100644index 0000000000..ddab81b591--- /dev/null+++ b/jarvis/society/mars/store.py@@ -0,0 +1,432 @@+"""Single-owner SQLite station journal with atomic state/event commits and fencing."""++from __future__ import annotations++import asyncio+import hashlib+import json+import time+from collections.abc import AsyncIterator, Callable+from contextlib import asynccontextmanager+from pathlib import Path+from uuid import uuid4++import aiosqlite+from filelock import FileLock, Timeout+from pydantic import TypeAdapter++from .models import (+ SCHEMA_VERSION,+ STATION_ID,+ TERMINAL_STATES,+ WORLD_ID,+ CommandRecord,+ CommandState,+ ExecutionReceipt,+ Identity,+ StationCommand,+ StationError,+ StationEvent,+ StationEventBatch,+ StationLease,+ StationSnapshot,+ reject_draft_credentials,+)+from .sqlite_transaction import atomic_transaction++_IDENTITY = TypeAdapter(Identity)+++class MarsStore:+ """Lazy store: constructing it opens neither database nor process lock.++ The lock lives as long as the connection. Other processes must use HTTP;+ they must not take over a live owner's lease or start another controller.+ """++ def __init__(+ self,+ path: Path,+ *,+ clock_ms: Callable[[], int] | None = None,+ lease_ms: int = 30_000,+ queue_limit: int = 64,+ retain_events: int = 2000,+ ) -> None:+ if not 1 <= queue_limit <= 64 or lease_ms < 100 or retain_events < 1:+ raise ValueError("invalid bounded station store configuration")+ self.path = Path(path).resolve()+ self._clock = clock_ms or (lambda: time.time_ns() // 1_000_000)+ self._lease_ms = lease_ms+ self._queue_limit = queue_limit+ self._retain_events = retain_events+ self._lock = asyncio.Lock()+ self._conn: aiosqlite.Connection | None = None+ self._owner: FileLock | None = None++ async def open(self) -> None:+ async with self._lock:+ if self._conn is not None:+ return+ self.path.parent.mkdir(parents=True, exist_ok=True)+ owner = FileLock(str(self.path) + ".owner.lock", thread_local=False)+ try:+ owner.acquire(timeout=0)+ except Timeout as exc:+ raise StationError("world_owned_by_another_process", 503) from exc+ conn: aiosqlite.Connection | None = None+ try:+ conn = await aiosqlite.connect(self.path, isolation_level=None)+ conn.row_factory = aiosqlite.Row+ await conn.execute("PRAGMA journal_mode=WAL")+ await conn.execute("PRAGMA synchronous=FULL")+ await conn.execute("PRAGMA busy_timeout=5000")+ await conn.execute("PRAGMA foreign_keys=ON")+ await conn.executescript(Path(__file__).with_name("schema.sql").read_text("utf-8"))+ row = await self._one(+ conn, "SELECT value FROM mars_meta WHERE key='schema_version'"+ )+ if row is not None and row[0] != SCHEMA_VERSION:+ raise StationError("unsupported_storage_version", 503)+ await conn.execute(+ "INSERT OR IGNORE INTO mars_meta(key,value) VALUES ('schema_version',?)",+ (SCHEMA_VERSION,),+ )+ await conn.execute(+ "INSERT OR IGNORE INTO mars_station(station_id) VALUES (?)", (STATION_ID,)+ )+ # Taking ownership fences old callbacks, but never blindly re-dispatches work.+ async with atomic_transaction(conn):+ await self._interrupt_owned(conn, "process_interrupted")+ self._conn, self._owner = conn, owner+ except BaseException:+ if conn is not None:+ await conn.close()+ owner.release()+ raise++ async def close(self) -> None:+ async with self._lock:+ try:+ if self._conn is not None:+ await self._conn.close()+ finally:+ self._conn = None+ if self._owner is not None:+ self._owner.release()+ self._owner = None++ @asynccontextmanager+ async def _transaction(self) -> AsyncIterator[aiosqlite.Connection]:+ async with self._lock:+ conn = self._conn+ if conn is None:+ raise StationError("world_not_started", 503)+ async with atomic_transaction(conn):+ yield conn++ @staticmethod+ async def _one(conn: aiosqlite.Connection, sql: str, args: tuple = ()):+ async with conn.execute(sql, args) as cursor:+ return await cursor.fetchone()++ @staticmethod+ def _record(row: aiosqlite.Row) -> CommandRecord:+ fields = dict(row)+ fields.pop("fingerprint")+ fields["state"] = CommandState(fields["state"])+ fields["cancel_requested"] = bool(fields["cancel_requested"])+ fields["cancel_dispatched"] = bool(fields["cancel_dispatched"])+ return CommandRecord(**fields)++ async def _command(self, conn: aiosqlite.Connection, command_id: str) -> CommandRecord:+ row = await self._one(conn, "SELECT * FROM mars_commands WHERE command_id=?", (command_id,))+ if row is None:+ raise StationError("command_not_found", 404)+ return self._record(row)++ async def _event(self, conn: aiosqlite.Connection, command_id: str) -> None:+ await conn.execute(+ "INSERT INTO mars_events(command_id,trace_id,agent_id,state,fence,task_ref,"+ "result_ref,reason,cancel_requested,ts_ms) SELECT command_id,trace_id,agent_id,"+ "state,fence,task_ref,result_ref,reason,cancel_requested,updated_ms "+ "FROM mars_commands WHERE command_id=?",+ (command_id,),+ )+ await conn.execute(+ "DELETE FROM mars_events WHERE seq <= (SELECT COALESCE(MAX(seq),0)-? FROM mars_events)",+ (self._retain_events,),+ )++ async def _interrupt_owned(self, conn: aiosqlite.Connection, reason: str) -> None:+ station = await self._one(+ conn, "SELECT * FROM mars_station WHERE station_id=?", (STATION_ID,)+ )+ if station is None or station["command_id"] is None:+ return+ command_id, generation = station["command_id"], station["generation"] + 1+ now = self._clock()+ await conn.execute(+ "UPDATE mars_station SET generation=?, expires_ms=? WHERE station_id=?",+ (generation, now + self._lease_ms, STATION_ID),+ )+ await conn.execute(+ "UPDATE mars_commands SET state='interrupted',fence=?,reason=?,updated_ms=? "+ "WHERE command_id=?",+ (generation, reason, now, command_id),+ )+ await self._event(conn, command_id)++ async def submit(self, agent_id: str, command: StationCommand) -> CommandRecord:+ reject_draft_credentials(command.draft)+ _IDENTITY.validate_python(agent_id, strict=True)+ # Immutable validated request; request_id is identity, not part of its content.+ content = command.model_dump(exclude={"request_id"})+ fingerprint = hashlib.sha256(+ json.dumps(content, sort_keys=True, separators=(",", ":")).encode("utf-8")+ ).hexdigest()+ async with self._transaction() as conn:+ old = await self._one(+ conn,+ "SELECT * FROM mars_commands WHERE world_id=? AND agent_id=? AND request_id=?",+ (WORLD_ID, agent_id, command.request_id),+ )+ if old is not None:+ if old["fingerprint"] != fingerprint:+ raise StationError("idempotency_payload_mismatch")+ return self._record(old)+ count = await self._one(+ conn,+ "SELECT COUNT(*) FROM mars_commands WHERE state NOT IN "+ "('completed','failed','canceled')",+ )+ if count is not None and count[0] >= self._queue_limit:+ raise StationError("station_queue_full", 429)+ command_id = f"mars-command:{uuid4()}"+ now = self._clock()+ await conn.execute(+ "INSERT INTO mars_commands(command_id,world_id,station_id,capability_id,"+ "agent_id,request_id,fingerprint,trace_id,draft,state,created_ms,updated_ms) "+ "VALUES (?,?,?,?,?,?,?,?,?,'queued',?,?)",+ (+ command_id,+ WORLD_ID,+ STATION_ID,+ command.capability_id,+ agent_id,+ command.request_id,+ fingerprint,+ command_id,+ command.draft,+ now,+ now,+ ),+ )+ await self._event(conn, command_id)+ return await self._command(conn, command_id)++ async def get(self, command_id: str, *, agent_id: str | None = None) -> CommandRecord:+ async with self._transaction() as conn:+ result = await self._command(conn, command_id)+ if agent_id is not None and result.agent_id != agent_id:+ raise StationError("command_not_found", 404)+ return result++ async def claim_next(self) -> CommandRecord | None:+ """Reserve the first queued command and commit dispatch intent before any call."""+ async with self._transaction() as conn:+ station = await self._one(+ conn, "SELECT * FROM mars_station WHERE station_id=?", (STATION_ID,)+ )+ if station["command_id"] is not None:+ return None+ row = await self._one(+ conn,+ "SELECT command_id FROM mars_commands WHERE state='queued' ORDER BY rowid LIMIT 1",+ )+ if row is None:+ return None+ command_id, fence, now = row[0], station["generation"] + 1, self._clock()+ await conn.execute(+ "UPDATE mars_station SET generation=?,command_id=?,expires_ms=? WHERE station_id=?",+ (fence, command_id, now + self._lease_ms, STATION_ID),+ )+ await conn.execute(+ "UPDATE mars_commands SET state='active',fence=?,updated_ms=?,"+ "reason='dispatch_started' "+ "WHERE command_id=?",+ (fence, now, command_id),+ )+ await self._event(conn, command_id)+ return await self._command(conn, command_id)++ async def current(self) -> CommandRecord | None:+ async with self._transaction() as conn:+ station = await self._one(+ conn, "SELECT * FROM mars_station WHERE station_id=?", (STATION_ID,)+ )+ if station["command_id"] is None:+ return None+ if station["expires_ms"] <= self._clock():+ await self._interrupt_owned(conn, "lease_expired")+ return await self._command(conn, station["command_id"])++ async def apply(+ self, command_id: str, fence: int, receipt: ExecutionReceipt, *, reason: str = ""+ ) -> CommandRecord:+ """Only the current server-side fence may acknowledge an execution outcome."""+ async with self._transaction() as conn:+ command = await self._command(conn, command_id)+ station = await self._one(+ conn, "SELECT * FROM mars_station WHERE station_id=?", (STATION_ID,)+ )+ if command.state in TERMINAL_STATES:+ if command.fence == fence and command.state is receipt.state:+ return command+ raise StationError("stale_station_lease")+ if command.task_ref and receipt.task_ref and command.task_ref != receipt.task_ref:+ raise StationError("task_reference_mismatch")+ if station["command_id"] != command_id or station["generation"] != fence:+ raise StationError("stale_station_lease")+ if station["expires_ms"] <= self._clock():+ # Do not accept a late worker result. The next reconcile fences it.+ raise StationError("stale_station_lease")+ now = self._clock()+ task_ref, result_ref = (+ receipt.task_ref or command.task_ref,+ receipt.result_ref or command.result_ref,+ )+ cancel_dispatched = command.cancel_dispatched+ if receipt.cancel_attempt == "not_attempted":+ cancel_dispatched = False+ changed = (+ command.state,+ command.task_ref,+ command.result_ref,+ command.reason,+ command.cancel_dispatched,+ ) != (+ receipt.state,+ task_ref,+ result_ref,+ reason,+ cancel_dispatched,+ )+ await conn.execute(+ "UPDATE mars_commands SET state=?,task_ref=?,result_ref=?,reason=?,updated_ms=?,"+ "cancel_dispatched=? "+ "WHERE command_id=?",+ (+ str(receipt.state),+ task_ref,+ result_ref,+ reason,+ now,+ int(cancel_dispatched),+ command_id,+ ),+ )+ if receipt.state in TERMINAL_STATES:+ await conn.execute(+ "UPDATE mars_station SET command_id=NULL,expires_ms=0 WHERE station_id=?",+ (STATION_ID,),+ )+ else:+ # An unknown external outcome keeps the exclusive resource until reconciled.+ await conn.execute(+ "UPDATE mars_station SET expires_ms=? WHERE station_id=?",+ (now + self._lease_ms, STATION_ID),+ )+ if changed:+ await self._event(conn, command_id)+ return await self._command(conn, command_id)++ async def request_cancel(self, agent_id: str, command_id: str) -> CommandRecord:+ async with self._transaction() as conn:+ command = await self._command(conn, command_id)+ if command.agent_id != agent_id:+ raise StationError("command_not_found", 404)+ if command.state in TERMINAL_STATES or command.cancel_requested:+ return command+ state = CommandState.CANCELED if command.state is CommandState.QUEUED else command.state+ await conn.execute(+ "UPDATE mars_commands SET state=?,cancel_requested=1,"+ "reason='cancel_requested',updated_ms=? "+ "WHERE command_id=?",+ (str(state), self._clock(), command_id),+ )+ await self._event(conn, command_id)+ return await self._command(conn, command_id)++ async def begin_cancel(self, command_id: str, fence: int) -> CommandRecord:+ """Persist cancellation intent once; an uncertain response is inspected, not repeated."""+ async with self._transaction() as conn:+ command = await self._command(conn, command_id)+ station = await self._one(+ conn, "SELECT * FROM mars_station WHERE station_id=?", (STATION_ID,)+ )+ if station["command_id"] != command_id or station["generation"] != fence:+ raise StationError("stale_station_lease")+ if not command.cancel_requested:+ raise StationError("cancellation_not_requested")+ if command.cancel_dispatched:+ return command+ await conn.execute(+ "UPDATE mars_commands SET cancel_dispatched=1,reason='cancel_pending',updated_ms=? "+ "WHERE command_id=?",+ (self._clock(), command_id),+ )+ await self._event(conn, command_id)+ return await self._command(conn, command_id)++ async def snapshot(self) -> StationSnapshot:+ async with self._transaction() as conn:+ seq = await self._one(conn, "SELECT COALESCE(MAX(seq),0) FROM mars_events")+ # All pending records (at most 64), plus bounded newest terminal history.+ async with conn.execute(+ "SELECT * FROM mars_commands ORDER BY "+ "(state IN ('completed','failed','canceled')) ASC, rowid DESC LIMIT 100"+ ) as cursor:+ commands = tuple(self._record(row) for row in await cursor.fetchall())+ station = await self._one(+ conn, "SELECT * FROM mars_station WHERE station_id=?", (STATION_ID,)+ )+ lease = None+ if station["command_id"] is not None:+ owner = await self._command(conn, station["command_id"])+ lease = StationLease(+ command_id=owner.command_id,+ agent_id=owner.agent_id,+ fence=station["generation"],+ expires_ms=station["expires_ms"],+ )+ return StationSnapshot(seq=seq[0], commands=commands, lease=lease)++ async def events(self, after_seq: int, *, limit: int = 100) -> StationEventBatch:+ if type(after_seq) is not int or after_seq < 0 or type(limit) is not int or limit < 1:+ raise StationError("invalid_event_cursor", 422)+ limit = min(limit, 250)+ async with self._transaction() as conn:+ bounds = await self._one(+ conn, "SELECT COALESCE(MIN(seq),0),COALESCE(MAX(seq),0) FROM mars_events"+ )+ oldest, latest = bounds+ resync = after_seq > latest or (oldest > 0 and after_seq < oldest - 1)+ records = []+ if not resync:+ async with conn.execute(+ "SELECT * FROM mars_events WHERE seq>? ORDER BY seq LIMIT ?", (after_seq, limit)+ ) as cursor:+ for row in await cursor.fetchall():+ fields = dict(row)+ fields["state"] = CommandState(fields["state"])+ fields["cancel_requested"] = bool(fields["cancel_requested"])+ records.append(StationEvent(**fields))+ delivered = records[-1].seq if records else after_seq+ return StationEventBatch(+ events=tuple(records),+ next_cursor=delivered,+ latest_seq=latest,+ has_more=not resync and delivered < latest,+ resync_required=resync,+ )diff --git a/jarvis/society/roster.py b/jarvis/society/roster.pyindex 0f062d1569..68b56d42bf 100644--- a/jarvis/society/roster.py+++ b/jarvis/society/roster.py@@ -20,6 +20,9 @@ import unicodedatafrom dataclasses import dataclass, fieldfrom typing import Any, Final+from pydantic import ValidationError++from .companion import validate_avatar_companionfrom .events import (AgentState,BrowserMode,@@ -339,6 +342,12 @@ def _coerce(field_name: str, value: Any) -> Any:if field_name == "avatar":if not isinstance(value, dict):raise RosterError(FailureReason.BLOCKED_BY_POLICY, "avatar must be an object")+ try:+ value = validate_avatar_companion(value)+ except ValidationError as exc:+ raise RosterError(+ FailureReason.BLOCKED_BY_POLICY, "invalid companion appearance"+ ) from excreturn json.dumps(value, ensure_ascii=False)if field_name == "approval_rules":return json.dumps(_validate_rules(value))diff --git a/jarvis/society/routine_runner.py b/jarvis/society/routine_runner.pyindex 3307be6d64..a6375504b7 100644--- a/jarvis/society/routine_runner.py+++ b/jarvis/society/routine_runner.py@@ -1,12 +1,13 @@-"""Run a scheduled task through the owner's canonical chat and current policy."""+"""Run each scheduled execution in its own persisted, unattended owner chat."""from __future__ import annotationsimport asynciofrom typing import Any+from uuid import uuid4-from .chat_binding import ensure_session-from .routines import agent_id_from_tags+from .chat_binding import SURFACE, _workspace, pair_for+from .routines import agent_id_from_tags, routine_seatasync def guard_owned_routine(runtime: Any, tags: tuple[str, ...]) -> Any:@@ -22,8 +23,104 @@ async def guard_owned_routine(runtime: Any, tags: tuple[str, ...]) -> Any:return agent+def _billed_via_api(provider: str) -> bool:+ """Whether ``provider`` answers through an API key on the society surface.++ CLI seats (subscriptions) and keyless local providers never touch an API+ key; ``brain``/``api`` runners do. Decided by asking the runner and the+ row, never by matching a provider name (AP-21).+ """+ try:+ from jarvis.agent_chat.catalog import provider_row+ from jarvis.agent_chat.service import resolve_runner+ except Exception: # noqa: BLE001 — without the catalog every seat counts as billed+ return True+ row = provider_row(provider)+ if row is not None and bool(getattr(row, "keyless", False)):+ return False+ return resolve_runner(provider, surface=SURFACE) in ("brain", "api", "unknown")+++def _subscription_seat(cfg: Any) -> tuple[str, str, str] | None:+ """The Jarvis chat's current subscription seat, if it has one.++ Mirrors what a typed turn on the front page resolves to+ (``AgentChatService.send``): the global worker pick mapped through the+ subscription aliases. ``None`` when the front page itself runs on an API+ key or is unconfigured.+ """+ try:+ from jarvis.core.model_selection import worker_selection+ from jarvis.core.task_agent import subscription_seat+ except Exception: # noqa: BLE001 — no selection layer: no subscription seat+ return None+ try:+ selection = worker_selection(cfg)+ except Exception: # noqa: BLE001 — unreadable config reads as no seat+ return None+ if selection is None or not selection.provider:+ return None+ mapped = subscription_seat(selection.provider)+ if mapped is not None:+ return mapped[0], selection.model or "", selection.reasoning_effort or ""+ if not _billed_via_api(selection.provider):+ return selection.provider, selection.model or "", selection.reasoning_effort or ""+ return None+++async def _seat_for_run(runtime: Any, agent: Any, task_id: str) -> tuple[str, str, str, str]:+ """The ``(provider, model, effort, account_id)`` this run answers on.++ A pinned routine seat wins (the model the owner ran on when the routine+ was created, or what the person later picked for it — an explicit choice,+ billed as chosen). Unpinned legacy rows follow the owner's live seat, but+ never slide silently onto an API-key chain: an owner without an explicit+ provider takes the Jarvis chat's subscription seat, and when there is no+ usable subscription seat the run fails honestly instead of billing a key.+ """+ cfg = runtime.config()+ pinned = {"provider": "", "model": "", "effort": "", "account_id": ""}+ try:+ task_store, _ = runtime.task_services()+ if task_store is not None:+ spec = await task_store.get_spec(task_id)+ if spec is not None:+ pinned = routine_seat(spec)+ except Exception: # noqa: BLE001 — an unreadable spec falls back to the live seat+ pinned = {"provider": "", "model": "", "effort": "", "account_id": ""}+ if pinned["provider"]:+ return pinned["provider"], pinned["model"], pinned["effort"], pinned["account_id"]+ account_id = str(getattr(agent, "account_id", "") or "")+ if getattr(agent, "provider", ""):+ _provider, _model, _effort = pair_for(cfg, agent)+ return _provider, _model, _effort, account_id+ subscription = _subscription_seat(cfg)+ if subscription is not None:+ provider, model, effort = subscription+ return provider, model, effort, account_id+ try:+ provider, model, effort = pair_for(cfg, agent)+ except PermissionError as exc:+ raise RuntimeError(+ "The routine has no model seat: the owner names no provider and no "+ f"subscription seat is available ({exc}). Pick a model for the agent "+ "or for this routine."+ ) from exc+ if _billed_via_api(provider):+ raise RuntimeError(+ "The routine stays on its owner's model and was not rerouted: the owner "+ "names no provider and the only fallback would bill an API key. Pick a "+ "subscription model for the agent or for this routine."+ )+ return provider, model, effort, account_id++async def run_owned_routine(- runtime: Any, task_id: str, tags: tuple[str, ...], prompt: str, cancel_token: Any = None+ runtime: Any,+ task_id: str,+ tags: tuple[str, ...],+ prompt: str,+ cancel_token: Any = None,) -> str | None:agent = await guard_owned_routine(runtime, tags)if agent is None:@@ -31,16 +128,33 @@ async def run_owned_routine(service = runtime.chat_service()if service is None:raise RuntimeError("The canonical chat service is unavailable")- session = ensure_session(service, runtime.config(), agent)- if service.is_running(session.session_id):- from jarvis.core.protocols import RoutineDeferred+ from jarvis.agent_chat.effort import default_effort- raise RoutineDeferred("The routine owner is busy; waiting for the current turn")+ cfg = runtime.config()+ provider, model, effort, account_id = await _seat_for_run(runtime, agent, task_id)+ session = service.store.create_session(+ session_id=f"{agent.session_id}:routine:{task_id}:{uuid4().hex}",+ surface=SURFACE,+ provider=provider,+ model=model,+ effort=effort or default_effort(provider),+ account_id=account_id,+ cwd=_workspace(cfg, agent),+ permission_mode="bypass",+ title=f"{agent.name} · Routine {task_id}",+ )+ # Persist the link before starting work, including runs that fail or are cancelled.+ task_store, _ = runtime.task_services()+ if task_store is not None:+ await task_store.append_step(+ task_id, "log", {"event": "routine_chat", "session_id": session.session_id}+ )# Legacy tasks contain an identity snapshot. The live briefing owns identity now._, separator, original = prompt.partition("\nRoutine:\n")task = original if separator else prompttask = (- f"Scheduled routine {task_id}. Follow your CURRENT standing instructions and permissions.\n"+ f"Scheduled routine {task_id}. Follow your CURRENT standing instructions.\n"+ "This execution has its own background chat with bypass permissions.\n""Use your memory and conversation archive for prior results. For information watches, ""check sources and dates, remember last-seen items, ""and report only meaningful new findings.\n\n" + task@@ -51,7 +165,6 @@ async def run_owned_routine(turn_id = await service.send(session.session_id, task, direct_user=False)while True:if cancel_token is not None and cancel_token.is_cancelled():- await service.cancel(session.session_id)raise asyncio.CancelledErrortry:event = await asyncio.wait_for(queue.get(), timeout=0.25)@@ -63,11 +176,16 @@ async def run_owned_routine(if event.get("kind") == "assistant_text":answer = str(payload.get("text") or answer)if event.get("kind") == "turn_finished":+ if payload.get("status") == "cancelled":+ raise asyncio.CancelledErrorif payload.get("status") not in {"done", "ok", "completed"}:raise RuntimeError(str(payload.get("error") or "The routine failed"))return answerexcept asyncio.CancelledError:await service.cancel(session.session_id)raise+ except Exception as exc:+ # A started execution must not silently move to another agent/context.+ raise RuntimeError(f"The routine chat failed: {exc}") from excfinally:service.unsubscribe(session.session_id, queue)diff --git a/jarvis/society/routines.py b/jarvis/society/routines.pyindex 0af63c45dc..7f18511a77 100644--- a/jarvis/society/routines.py+++ b/jarvis/society/routines.py@@ -42,6 +42,7 @@ __all__ = ["create_routine","is_agent_routine","list_routines",+ "routine_seat",]ROUTINE_TAG: Final[str] = "society"@@ -131,6 +132,10 @@ def build_task_spec(plugin_grants: list[dict[str, str]] | None = None,announce_on_success: str | None = None,workflow_id: str | None = None,+ provider: str | None = None,+ model: str | None = None,+ effort: str | None = None,+ account_id: str | None = None,) -> TaskSpec:grants = tuple(PluginGrant(plugin_id=str(g["plugin_id"]), scope=g.get("scope", "read")) # type: ignore[arg-type]@@ -138,13 +143,37 @@ def build_task_spec(if g.get("plugin_id"))clean_title = " ".join(title.split())[:200] or "routine"+ # Pin the owner's current seat onto the routine: the default run uses+ # exactly the model the agent runs on now, and stays there until the+ # person picks another seat for this routine. An explicit choice wins.+ seat = {+ "provider": str(provider).strip().lower()+ if provider is not None+ else str(getattr(agent, "provider", "") or ""),+ "model": str(model).strip()+ if model is not None+ else str(getattr(agent, "model", "") or ""),+ "effort": str(effort).strip()+ if effort is not None+ else str(getattr(agent, "effort", "") or ""),+ "account_id": str(account_id).strip()+ if account_id is not None+ else str(getattr(agent, "account_id", "") or ""),+ }return TaskSpec(title=f"[agent:{agent.name}] {clean_title}",trigger=_trigger(schedule),action=(WorkflowAction(workflow_id=UUID(workflow_id))if workflow_id- else AgentAction(prompt=_routine_prompt(agent, prompt), plugin_grants=grants)+ else AgentAction(+ prompt=_routine_prompt(agent, prompt),+ plugin_grants=grants,+ provider=seat["provider"],+ model=seat["model"],+ effort=seat["effort"],+ account_id=seat["account_id"],+ )),created_by="society",tags=(ROUTINE_TAG, agent_tag(agent.agent_id)),@@ -152,6 +181,26 @@ def build_task_spec()+def routine_seat(spec: TaskSpec | dict[str, Any]) -> dict[str, str]:+ """The pinned model seat of a routine spec (empty strings = legacy row)."""+ action = spec.action if isinstance(spec, TaskSpec) else (spec.get("action") or {})+ if isinstance(action, AgentAction):+ return {+ "provider": action.provider,+ "model": action.model,+ "effort": action.effort,+ "account_id": action.account_id,+ }+ if isinstance(action, dict):+ return {+ "provider": str(action.get("provider") or ""),+ "model": str(action.get("model") or ""),+ "effort": str(action.get("effort") or ""),+ "account_id": str(action.get("account_id") or ""),+ }+ return {"provider": "", "model": "", "effort": "", "account_id": ""}++def agent_id_from_tags(tags: Sequence[str]) -> str | None:"""The owning agent behind a task's tags (``agent:<id>``), else ``None``."""prefix = agent_tag("")@@ -186,6 +235,7 @@ def _summary(row: dict[str, Any]) -> dict[str, Any]:spec = json.loads(raw) if isinstance(raw, str) else dict(raw)except ValueError:spec = {}+ action = spec.get("action") or {}return {"id": row.get("id"),"title": row.get("title") or spec.get("title"),@@ -194,11 +244,15 @@ def _summary(row: dict[str, Any]) -> dict[str, Any]:"webhook_path": f"/api/tasks/hooks/{row.get('id')}"if (spec.get("trigger") or {}).get("type") == "webhook"else None,- "prompt": str((spec.get("action") or {}).get("prompt") or "").partition("\nRoutine:\n")[2],+ "prompt": str(action.get("prompt") or "").partition("\nRoutine:\n")[2],"announce_on_success": spec.get("announce_on_success"),"due_at_ns": row.get("due_at_ns"),"last_run_ns": row.get("started_at_ns") or row.get("last_run_ns"),"tags": list(_tags_of(row)),+ "provider": str(action.get("provider") or ""),+ "model": str(action.get("model") or ""),+ "effort": str(action.get("effort") or ""),+ "account_id": str(action.get("account_id") or ""),}@@ -234,6 +288,19 @@ async def manage_routine(operation = payload["operation"]if operation == "update":old = await task_store.get_spec(tid)+ old_seat = routine_seat(old)+ # A title/prompt/schedule edit keeps the routine's pinned seat; only+ # an explicit seat in the payload moves it ("" = follow the owner).+ seat_override: dict[str, str] = {+ key: (+ str(payload[key]).strip().lower()+ if key == "provider"+ else str(payload[key]).strip()+ )+ for key in ("provider", "model", "effort", "account_id")+ if key in payload and payload[key] is not None+ }+ seat = {**old_seat, **seat_override}spec = build_task_spec(agent,title=payload["title"],@@ -243,16 +310,24 @@ async def manage_routine(workflow_id=payload.get("workflow_id")or (str(old.action.workflow_id) if old.action.kind == "workflow" else None),announce_on_success=payload.get("announce_on_success"),+ **seat,)- changes = {- "title": spec.title,- "trigger": spec.trigger,- "action": (- old.action.model_copy(update={"prompt": spec.action.prompt})- if old.action.kind == "agent" and spec.action.kind == "agent"- else spec.action- ),- }+ if old.action.kind == "agent" and spec.action.kind == "agent":+ action_update: dict[str, Any] = {"prompt": spec.action.prompt}+ for key in ("provider", "model", "effort", "account_id"):+ if key in seat_override:+ action_update[key] = seat[key]+ changes = {+ "title": spec.title,+ "trigger": spec.trigger,+ "action": old.action.model_copy(update=action_update),+ }+ else:+ changes = {+ "title": spec.title,+ "trigger": spec.trigger,+ "action": spec.action,+ }if "announce_on_success" in payload:changes["announce_on_success"] = payload["announce_on_success"]await scheduler.update_task(tid, old.model_copy(update=changes))diff --git a/jarvis/society/runtime.py b/jarvis/society/runtime.pyindex 027c3da0a4..f6f9f7c43f 100644--- a/jarvis/society/runtime.py+++ b/jarvis/society/runtime.py@@ -20,6 +20,7 @@ from __future__ import annotationsimport asyncioimport loggingfrom collections.abc import Callable, Iterable, Mapping+from contextlib import AsyncExitStackfrom pathlib import Pathfrom typing import Any, Finalfrom uuid import uuid4@@ -31,7 +32,9 @@ from .bridge import MissionBridgefrom .browser.session import BrowserJobsfrom .capabilities import CapabilityRow, build_catalogfrom .checkpoints import CheckpointEngine+from .communication import reply_policy, should_reportfrom .conversation import ConversationArchive+from .delivery import IncomingMessage, incoming_contextfrom .events import MsgType, QuestState, RoomState, SocietyEnvelope, Tierfrom .focus import derive_approval_rules, derive_focusfrom .learning import AgentSkills, LearningPass, TurnDigest, default_creator_factory@@ -49,6 +52,12 @@ log = logging.getLogger(__name__)__all__ = ["SocietyRuntime", "current_runtime", "set_current_runtime"]_DB_NAME = "society.db"+_CLOSE_TASK_TIMEOUT_S = 2.0+++class SocietyRuntimeClosed(RuntimeError):+ """This runtime owner has entered terminal shutdown."""+#: What the person hears when a task Jarvis handed out comes back._LEAD_DONE: dict[str, str] = {@@ -189,6 +198,8 @@ class SocietyRuntime:self._delivery_unsubscribe: Callable[[], None] | None = Noneself._lead_incoming_unsubscribe: Callable[[], None] | None = Noneself._started = False+ self._closing = False+ self._starting_task: asyncio.Task[Any] | None = Noneself._context_start_task: asyncio.Task[bool] | None = None# ------------------------------------------------------------ lifecycle@@ -199,6 +210,8 @@ class SocietyRuntime:Voice/chat may continue while storage is slow. One owned task does thework; close cancels and reaps it before dismantling runtime components."""+ if self._closing:+ return Falseif self._started:return Truetask = self._context_start_task@@ -219,36 +232,59 @@ class SocietyRuntime:return Trueasync def ensure_started(self) -> SocietyRuntime:+ self._require_open_owner()async with self._start_lock:+ self._require_open_owner()if self._started:return self- await self.store.open()- self.scheduler._budget = self._get_budget() # noqa: SLF001 — the runtime owns its scheduler- self.scheduler.attach()- self._delivery_unsubscribe = self.store.bus.subscribe_all(self._delivery_failed)- self._lead_incoming_unsubscribe = self.store.bus.subscribe_all(self._on_lead_incoming)- bus = self._get_mission_bus()- if bus is not None:- self.bridge.attach(bus)- self.checkpoints.attach()- self.quests.attach()- self.world_feed.attach()- await self.seed_lead()- if self._seed_starter_team:- created = await seed_first_run(self.roster, self.store)- if created:- log.info("society: starter team seeded: %s", ", ".join(created))- # Warm the roster snapshot so the lead card (lead_card.py) — a- # synchronous reader on the brain's prompt build — sees the team from- # the first turn, not from the first REST listing.- await self.roster.refresh()- self._started = True- self._delivery_task = asyncio.create_task(self._deliver_pending())- set_current_runtime(self)- await self.coding_supervision.start()- self.background(self.recover_reviews())- log.info("society runtime started (%s)", self.store.path)- return self+ self._starting_task = asyncio.current_task()+ try:+ return await self._start_runtime()+ finally:+ # A slow startup that outlives the shutdown deadline still owns+ # its provisional store until it unwinds; never orphan it.+ try:+ if self._closing:+ await self.store.close()+ finally:+ self._starting_task = None++ def _require_open_owner(self) -> None:+ if self._closing:+ raise SocietyRuntimeClosed("society runtime stopped")++ async def _start_runtime(self) -> SocietyRuntime:+ await self.store.open()+ self._require_open_owner()+ self.scheduler._budget = self._get_budget() # noqa: SLF001 — the runtime owns its scheduler+ self.scheduler.attach()+ self._delivery_unsubscribe = self.store.bus.subscribe_all(self._delivery_failed)+ self._lead_incoming_unsubscribe = self.store.bus.subscribe_all(self._on_lead_incoming)+ bus = self._get_mission_bus()+ if bus is not None:+ self.bridge.attach(bus)+ self.checkpoints.attach()+ self.quests.attach()+ self.world_feed.attach()+ await self.seed_lead()+ self._require_open_owner()+ if self._seed_starter_team:+ created = await seed_first_run(self.roster, self.store)+ if created:+ log.info("society: starter team seeded: %s", ", ".join(created))+ # Warm the roster snapshot so the lead card (lead_card.py) — a+ # synchronous reader on the brain's prompt build — sees the team from+ # the first turn, not from the first REST listing.+ await self.roster.refresh()+ self._require_open_owner()+ self._started = True+ self._delivery_task = asyncio.create_task(self._deliver_pending())+ set_current_runtime(self)+ await self.coding_supervision.start()+ self._require_open_owner()+ self.background(self.recover_reviews())+ log.info("society runtime started (%s)", self.store.path)+ return selfasync def _delivery_failed(self, env: SocietyEnvelope) -> None:"""Project a terminal scheduler veto onto an already-visible chat receipt."""@@ -281,13 +317,25 @@ class SocietyRuntime:if sender is None:returnrequests = await self.store.events_for_trace(env.trace_id)- if not any(- request.from_agent == LEAD_AGENT_ID- and request.to_agent == env.from_agent- and request.msg_type in (MsgType.SAY, MsgType.QUERY, MsgType.ASSIGN)- and request.event_id == env.parent_event_id- for request in requests- ):+ request = next(+ (+ item+ for item in requests+ if item.from_agent == LEAD_AGENT_ID+ and item.to_agent == env.from_agent+ and item.msg_type+ in (MsgType.SAY, MsgType.QUERY, MsgType.PROPOSE, MsgType.ASSIGN)+ and item.event_id == env.parent_event_id+ ),+ None,+ )+ if request is None:+ return+ if request.msg_type is MsgType.ASSIGN and "reply_policy" in request.payload:+ # The turn watcher owns this completion, including semantic blockers.+ return+ status = str(env.payload.get("reply_status") or "done")+ if not should_report(request, status):returnawait self.announce_lead_message(sender, env)except Exception: # noqa: BLE001 - a silent message is a lost courtesy, not a lost result@@ -407,37 +455,59 @@ class SocietyRuntime:return self._get_cfg()async def close(self) -> None:- await self.coding_supervision.close()- if self._context_start_task is not None:- self._context_start_task.cancel()- await asyncio.gather(self._context_start_task, return_exceptions=True)- self._context_start_task = None- if self._delivery_task is not None:- self._delivery_task.cancel()- await asyncio.gather(self._delivery_task, return_exceptions=True)- self._delivery_task = None- if self._delivery_unsubscribe is not None:- self._delivery_unsubscribe()- self._delivery_unsubscribe = None- if self._lead_incoming_unsubscribe is not None:- self._lead_incoming_unsubscribe()- self._lead_incoming_unsubscribe = None- await self.browser.close()- for task in list(self._watchers):- task.cancel()- if self._watchers:- await asyncio.gather(*list(self._watchers), return_exceptions=True)- self._watchers.clear()- self.conversations.close()- self.scheduler.detach()- self.bridge.detach()- self.checkpoints.detach()- self.quests.detach()- self.world_feed.detach()- await self.store.close()- self._started = False- if current_runtime() is self:- set_current_runtime(None)+ # HTTP serving continues during independent server cleanup. Fence this+ # owner synchronously so a late roster/context request cannot reopen it.+ self._closing = True++ def clear_runtime() -> None:+ self._started = False+ if current_runtime() is self:+ set_current_runtime(None)++ # Register every release before the first await. A failing or cancelled+ # browser/supervisor cleanup must still close SQLite's non-daemon worker.+ # Exit-stack callbacks run in reverse order, keeping storage alive until+ # tasks and subscriptions have relinquished it; failures still propagate.+ async with AsyncExitStack() as cleanup:+ cleanup.callback(clear_runtime)+ cleanup.push_async_callback(self.store.close)+ for release in (+ self.world_feed.detach,+ self.quests.detach,+ self.checkpoints.detach,+ self.bridge.detach,+ self.scheduler.detach,+ self.conversations.close,+ ):+ cleanup.callback(release)+ cleanup.push_async_callback(self.browser.close)+ for attribute in ("_delivery_unsubscribe", "_lead_incoming_unsubscribe"):+ unsubscribe = getattr(self, attribute)+ if unsubscribe is not None:+ cleanup.callback(unsubscribe)+ setattr(self, attribute, None)+ cleanup.push_async_callback(self.coding_supervision.close)++ tasks: set[asyncio.Task[Any]] = set(self._watchers)+ for task in (self._starting_task, self._context_start_task, self._delivery_task):+ if task is not None:+ tasks.add(task)+ for task in tasks:+ task.cancel()+ try:+ if tasks:+ done, pending = await asyncio.wait(tasks, timeout=_CLOSE_TASK_TIMEOUT_S)+ for task in done:+ if not task.cancelled() and (error := task.exception()) is not None:+ log.warning("society shutdown task failed: %s", type(error).__name__)+ if pending:+ raise TimeoutError("society task shutdown incomplete")+ finally:+ if self._context_start_task is not None and self._context_start_task.done():+ self._context_start_task = None+ if self._delivery_task is not None and self._delivery_task.done():+ self._delivery_task = None+ self._watchers.difference_update(task for task in tasks if task.done())def skills_for(self, agent_id: str) -> AgentSkills:"""The agent's private skill namespace (lazy registry)."""@@ -452,6 +522,7 @@ class SocietyRuntime:events = json.loads(completion.events_json)self.conversations.ingest(session.session_id, events)+ await self._complete_message_reply(session, completion, events)terminal = [e for e in events if e.get("kind") == "turn_finished"]if not terminal or terminal[-1].get("payload", {}).get("status") not in {"done",@@ -467,7 +538,8 @@ class SocietyRuntime:from .memory_intent import has_write_receiptif (- names and names <= {"society_propose_change", "society_wiki_note"}+ names+ and names <= {"society_propose_change", "society_wiki_note"}and has_write_receipt(events)):# These turns already have a successful durable-write receipt.@@ -482,6 +554,64 @@ class SocietyRuntime:):self.background(self.recover_reviews())+ async def _complete_message_reply(+ self, session: Any, completion: Any, events: list[dict[str, Any]]+ ) -> None:+ """Return a requested answer even when the receiver only writes its final text."""+ incoming = incoming_context.get()+ if incoming is None or completion.turn.direct_user:+ return+ request = await self.store.get_event(incoming.message_id)+ if (+ request is None+ or request.to_agent is None+ or request.msg_type not in (MsgType.QUERY, MsgType.SAY, MsgType.PROPOSE)+ or session.session_id != f"society:{request.to_agent}"+ or reply_policy(request) == "none"+ or await self.store.kill_switch()+ ):+ return+ replies = await self.store.events_for_trace(request.trace_id)+ if any(+ item.msg_type is MsgType.ANSWER+ and item.parent_event_id == request.event_id+ and item.from_agent == request.to_agent+ and item.to_agent == request.from_agent+ for item in replies+ ):+ return+ final = next(+ (+ str(item.get("payload", {}).get("text") or "").strip()+ for item in reversed(events)+ if item.get("kind") == "assistant_text"+ ),+ "",+ )+ terminal: dict[str, Any] = next(+ (+ item.get("payload", {})+ for item in reversed(events)+ if item.get("kind") == "turn_finished"+ ),+ {},+ )+ status = (+ "done" if final and terminal.get("status") in ("done", "ok", "completed") else "blocked"+ )+ if not should_report(request, status):+ return+ await self.say(+ from_agent=request.to_agent,+ to_agent=request.from_agent,+ text=final+ or "The receiving turn ended without an answer; the request remains unresolved.",+ trace_id=request.trace_id,+ parent_event_id=request.event_id,+ msg_type=MsgType.ANSWER,+ payload={"reply_policy": "none", "reply_status": status},+ )+async def recover_reviews(self) -> None:from .review_queue import drain_reviews@@ -598,6 +728,8 @@ class SocietyRuntime:if not runner:runner = "chat" if self._get_chat() is not None else "mission"if runner == "mission":+ if reply_policy(env) != "always":+ raise RuntimeError("this reply policy requires an available agent chat service")return await self._dispatch_mission(target, env)return await self._dispatch_chat(target, env)@@ -611,10 +743,23 @@ class SocietyRuntime:if svc.is_running(session.session_id):raise RuntimeError(f"target busy: {target.name} is running a turn")queue = svc.subscribe(session.session_id)+ # Both API and CLI turns inherit the same trusted request provenance.+ token = incoming_context.set(+ IncomingMessage(+ message_id=env.event_id,+ sender_id=env.from_agent,+ sender_name=env.from_agent,+ sender_kind="jarvis" if env.from_agent == LEAD_AGENT_ID else "agent",+ text=env.text,+ prompt=frame_assignment(env),+ trace_id=env.trace_id,+ )+ )try:turn_id = await svc.send(session.session_id,frame_assignment(env),+ **({"read_only": True} if env.payload.get("read_only") is True else {}),**({"direct_user": False}if getattr(svc, "supports_turn_completion", False)@@ -624,6 +769,8 @@ class SocietyRuntime:except Exception:svc.unsubscribe(session.session_id, queue)raise+ finally:+ incoming_context.reset(token)run_id = f"turn:{turn_id}"watcher = asyncio.create_task(self._watch_turn(svc, session.session_id, queue, turn_id, run_id, target, env)@@ -682,6 +829,20 @@ class SocietyRuntime:svc.unsubscribe(session_id, queue)self.scheduler.note_run_ended(run_id)summary = (final_text or error or "turn finished").strip()+ # A successful model turn can still report an unfinished task. Use the+ # correlated, typed report, never a keyword guess over the final prose.+ reports = [+ item+ for item in await self.store.events_for_trace(env.trace_id)+ if item.parent_event_id == env.event_id+ and item.from_agent == target.agent_id+ and item.to_agent == env.from_agent+ and item.msg_type is MsgType.ANSWER+ and item.payload.get("reply_status") == "blocked"+ ]+ if reports:+ status = "blocked"+ error = summary = reports[-1].texttry:await self.store.append_and_publish(SocietyEnvelope(@@ -733,6 +894,8 @@ class SocietyRuntime:realtime session both read ``AnnouncementRequested``) and posted as anotice into the newest front-page chat. Neither leg may fail the run."""+ if not should_report(env, status):+ returnlang = str(env.payload.get("lang") or "en").lower()line = (_LEAD_DONE if status == "done" else _LEAD_BLOCKED).get(lang, (_LEAD_DONE if status == "done" else _LEAD_BLOCKED)["en"]diff --git a/jarvis/society/scheduler.py b/jarvis/society/scheduler.pyindex 1e08712a59..e3141066ee 100644--- a/jarvis/society/scheduler.py+++ b/jarvis/society/scheduler.py@@ -292,6 +292,8 @@ class SocietyScheduler:async with self._delivery_lock:busy: set[str | None] = set()for env in await self._store.pending_deliveries():+ if await self._record_assignment_reply(env):+ continueif env.to_agent in busy:receive = getattr(self._deliver, "receive", None)target = await self._resolve_target(env)@@ -306,6 +308,23 @@ class SocietyScheduler:if not await self._on_deliver(env):busy.add(env.to_agent)+ async def _record_assignment_reply(self, env: SocietyEnvelope) -> bool:+ """Assignment outcomes belong to the watcher, not a second chat turn."""+ if env.msg_type is not MsgType.ANSWER or not env.parent_event_id:+ return False+ parent = await self._store.get_event(env.parent_event_id)+ if (+ parent is None+ or parent.msg_type is not MsgType.ASSIGN+ or "reply_policy" not in parent.payload+ or parent.trace_id != env.trace_id+ or parent.from_agent != env.to_agent+ or parent.to_agent != env.from_agent+ ):+ return False+ await self._store.mark_delivery(env.event_id, "delivered")+ return True+async def _on_deliver(self, env: SocietyEnvelope) -> bool:if await self._store.delivery_status(env.event_id) != "queued":return Truediff --git a/jarvis/society/surface.py b/jarvis/society/surface.pyindex 121c0bf86c..7a1e7546f2 100644--- a/jarvis/society/surface.py+++ b/jarvis/society/surface.py@@ -37,6 +37,7 @@ from .agent_tools import ()from .capabilities import CapabilityKind, CapabilityRow, capability_id_for_tool, select_toolsfrom .coding_tool import CodingSessionTool+from .communication import COMMUNICATION_GUIDANCEfrom .conversation_tool import ConversationRecallTool, RoutineInvokeTool, RoutineListToolfrom .learning import RunLearnedSkillToolfrom .memory import resolve_society_vault@@ -173,10 +174,10 @@ your location, use these names."""def agent_id_of(session_id: str) -> str | None:- """``society:<agent_id>`` → ``agent_id``; ``None`` for any other session."""+ """Resolve canonical and per-execution routine chats to their live owner."""if not session_id.startswith(_PREFIX):return None- agent_id = session_id[len(_PREFIX) :].strip()+ agent_id = session_id[len(_PREFIX) :].split(":routine:", 1)[0].strip()return agent_id or None@@ -286,7 +287,7 @@ async def tools_for_cli_session(or session.surface != SURFACEor agent is Noneor str(agent.state) != "active"- or agent.session_id != session_id+ or agent_id_of(session_id) != agent.agent_id):return {}rt.cache_agent(agent)@@ -315,7 +316,9 @@ def society_tools(cfg: Any, brain: Any, session: Any) -> dict[str, Tool]:# kit's tools REPLACE the folder tools (runner_brain.build_override), so the# agent would otherwise have no file hands at all; and the plain folder tools# accept absolute paths, which its workspace rule forbids.- tools[CodingSessionTool.name] = cast(Tool, CodingSessionTool(rt, agent_id))+ tools[CodingSessionTool.name] = cast(+ Tool, CodingSessionTool(rt, agent_id, session_id=str(getattr(session, "session_id", "")))+ )tools.update(_contained_folder_tools(workspace, getattr(session, "permission_mode", "")))tools.update({@@ -679,6 +682,7 @@ def build_briefing(lines.append(line)parts.append("\n".join(lines))parts.append(_ECOSYSTEM_CARD)+ parts.append(COMMUNICATION_GUIDANCE)mates = [a for a in roster if a.agent_id != agent.agent_id and str(a.state) == "active"]if mates:diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.pyindex c22c6b8490..8fca8f90d3 100644--- a/jarvis/speech/pipeline.py+++ b/jarvis/speech/pipeline.py@@ -4422,6 +4422,10 @@ class SpeechPipeline:return Falseif self._dictation_blocks_activation():return False+ from jarvis.live.runtime import owns_microphone++ if owns_microphone(except_session_id=getattr(self, "_current_voice_session_id", None)):+ return Falsereturn self._capture_permission_allowed()@property@@ -7635,10 +7639,7 @@ class SpeechPipeline:and realtime_browser_audio(getattr(self, "_config", None)))buffer = await self._claim_wake_capture_for_session()- if browser_media:- if buffer is not None:- await buffer.close()- await self._wake_capture_released.wait()+ if browser_media and buffer is None:browser_buffer = _SessionInputBuffer()try:yield browser_buffer@@ -9121,6 +9122,8 @@ class SpeechPipeline:return await run_browser_call(self._bus, self._hangup_event,timeout_s=max(45.0, realtime_handshake_budget_s(self._config) + 5.0),+ input_buffer=input_buffer,+ session_id=self._current_voice_session_id or "",)allow_classic_fallback = Truetry:diff --git a/jarvis/state/turn_trace.py b/jarvis/state/turn_trace.pyindex 024438a4f4..9d7c983076 100644--- a/jarvis/state/turn_trace.py+++ b/jarvis/state/turn_trace.py@@ -46,6 +46,7 @@ TRACE_EVENT_KINDS: frozenset[str] = frozenset({"BrainTurnStarted","BrainTurnCompleted",+ "ReasoningSummaryUpdated","ToolCallStarted","ToolCallCompleted","ActionProposed",@@ -62,6 +63,7 @@ TRACE_EVENT_KINDS: frozenset[str] = frozenset(#: Per event kind, the payload keys worth keeping. Free text is previewed._PAYLOAD_KEYS: dict[str, tuple[str, ...]] = {+ "ReasoningSummaryUpdated": ("response_id", "text", "done"),"BrainTurnStarted": ("provider", "model", "intent_level"),"BrainTurnCompleted": ("provider", "model", "finish_reason", "tokens_in", "tokens_out"),"ToolCallStarted": ("tool_name", "args_preview"),@@ -114,7 +116,8 @@ def trace_payload_for(name: str, event: Any) -> dict[str, Any]:args[str(k)] = _scalar(v, max_chars=_ARG_MAX)out[key] = argscontinue- out[key] = _scalar(value, max_chars=_TEXT_MAX)+ maximum = 4000 if name == "ReasoningSummaryUpdated" and key == "text" else _TEXT_MAX+ out[key] = _scalar(value, max_chars=maximum)return outdiff --git a/jarvis/tasks/runner.py b/jarvis/tasks/runner.pyindex 3d5992e689..4d355b1b47 100644--- a/jarvis/tasks/runner.py+++ b/jarvis/tasks/runner.py@@ -582,6 +582,25 @@ class TaskRunner:except Exception as exc:if _owner_blocks_fallback(exc):raise+ if _is_society_routine(tags):+ # A society routine stays on its owner's model seat and is+ # never rerouted onto the generic API-key chain: a failed+ # seat fails the run honestly instead of billing a key.+ message = (+ f"{readable_error(exc)} The routine stays on its owner's "+ "model and was not rerouted."+ )+ seq = await self._store.append_step(+ task_id,+ "log",+ {"event": "owner_seat_failed", "message": message, "fallback": "none"},+ )+ await self._bus.publish(+ TaskStepRecorded(+ task_id=task_id, seq=seq, kind="log", source_layer="tasks.runner"+ )+ )+ raise RuntimeError(message) from excowned_failed = exclog.warning("task %s: owner seat failed (%s); continuing via task tools",@@ -758,6 +777,11 @@ def _targets_computer_use(harness_name: str) -> bool:return harness_name == HARNESS_NAME+def _is_society_routine(tags: tuple[str, ...]) -> bool:+ """Whether these tags belong to a society agent routine (never rerouted)."""+ return "society" in tags or any(str(tag).startswith("agent:") for tag in tags)++def _owner_blocks_fallback(exc: BaseException) -> bool:"""True when the owner's state, not the seat, is why the routine cannot run.@@ -774,6 +798,7 @@ def _owner_blocks_fallback(exc: BaseException) -> bool:"the routine owner is unavailable","the routine owner is paused","canonical chat service is unavailable",+ "the routine chat failed",))diff --git a/jarvis/tasks/schema.py b/jarvis/tasks/schema.pyindex 53e346bf2e..d060f2b7fb 100644--- a/jarvis/tasks/schema.py+++ b/jarvis/tasks/schema.py@@ -290,6 +290,14 @@ class AgentAction(BaseModel):prompt: str = Field(min_length=1, max_length=16_384)plugin_grants: tuple[PluginGrant, ...] = Field(default_factory=tuple)model_tier: Literal["fast", "deep", "auto"] = "auto"+ # Pinned model seat for a society routine (``provider`` empty = follow+ # the owning agent's live seat). Snapshot at creation so the routine+ # stays on the model the owner used then — never silently rerouted onto+ # an API-key chain — unless the person picks another seat for it.+ provider: str = Field(default="", max_length=64)+ model: str = Field(default="", max_length=256)+ effort: str = Field(default="", max_length=64)+ account_id: str = Field(default="", max_length=256)class WorkflowAction(BaseModel):diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.pyindex 432b51f15f..f01565969b 100644--- a/jarvis/ui/desktop_app.py+++ b/jarvis/ui/desktop_app.py@@ -35,6 +35,7 @@ from jarvis.core.instance import current_instancefrom jarvis.core.process_utils import ensure_standard_streamsif TYPE_CHECKING:+ from jarvis.ui.desktop_background import BackgroundStatusfrom jarvis.ui.web.server import WebServer# The main window's title doubles as its focus handle@@ -1483,6 +1484,11 @@ class DesktopApp:self._tray: Any = Noneself._user_requested_quit = Falseself._window_visible = False+ from jarvis.ui.desktop_background import BackgroundSession # noqa: PLC0415++ self._background = BackgroundSession()+ self._main_window_lock = threading.RLock()+ self._webview_persistent_profile = False# Voice stack (pipeline + orb overlay) — optional, can be disabled via# ENV JARVIS_VOICE=0. Defaults to on, so "Hey Jarvis" works# out-of-the-box when `run.bat` starts the desktop app.@@ -1508,6 +1514,168 @@ class DesktopApp:"""Return whether voice activation is allowed for the desktop UI."""return bool(self._window is not None and self._window_visible)+ def get_background_status(self) -> BackgroundStatus:+ """Report the current session's close policy without native GUI calls."""+ from jarvis.ui.desktop_background import native_background_reason # noqa: PLC0415++ state = getattr(self, "_background", None)+ window = getattr(self, "_window", None)+ window_open = window is not None or bool(getattr(self, "_detached_windows", {}))+ enabled = bool(state is not None and state.enabled and state.alive)+ stopped = getattr(self, "_shutdown_done", False)+ stopping = getattr(self, "_user_requested_quit", False)+ reason = None+ if stopped:+ reason = "stopped"+ elif stopping:+ reason = "stopping"+ elif getattr(self, "_main_window_closing", False):+ reason = "window_closing"+ elif not getattr(self, "_webview_persistent_profile", False):+ reason = "persistent_profile_unavailable"+ elif state is not None and state.backend_failed:+ reason = "backend_unavailable"+ elif not getattr(getattr(self, "_tray", None), "ready", False):+ reason = "tray_unavailable"+ else:+ native_window = window or (state.keeper if state is not None else None)+ if native_window is None:+ native_window = next(iter(getattr(self, "_detached_windows", {}).values()), None)+ reason = native_background_reason(native_window)+ return {+ "available": reason is None,+ "reason": reason,+ "enabled": enabled,+ "mode": (+ "stopped" if stopped else "stopping" if stopping+ else "background" if enabled and not window_open else "foreground"+ ),+ "window_open": window_open,+ }++ def set_background_mode(self, enabled: bool) -> BackgroundStatus:+ """Arm an explicit session opt-in; native work belongs off the async loop."""+ from jarvis.ui.desktop_background import BackgroundSession # noqa: PLC0415++ state = getattr(self, "_background", None)+ if state is None:+ state = self._background = BackgroundSession()+ if not state.transition.acquire(blocking=False):+ return {**self.get_background_status(), "reason": "transition_in_progress"}+ try:+ status = self.get_background_status()+ if enabled:+ if not status["available"] or status["enabled"]:+ return status+ if threading.current_thread() is threading.main_thread():+ return {**status, "reason": "worker_thread_required"}+ if state.keeper is not None:+ self._destroy_background_keeper()+ if state.keeper is not None:+ return {+ **status, "available": False,+ "reason": "hidden_window_cleanup_failed",+ }+ import webview # noqa: PLC0415 — optional desktop dependency++ keeper = webview.create_window(+ f"{WINDOW_TITLE} — Background",+ html="<!doctype html><html><head><title></title></head><body></body></html>",+ hidden=True, focus=False, width=1, height=1, min_size=(1, 1),+ frameless=True, resizable=False, confirm_close=False,+ )+ if keeper is None:+ return {**status, "available": False, "reason": "hidden_window_unavailable"}+ state.keeper = keeper+ keeper.events.closed += lambda: self._on_background_keeper_closed(keeper)+ # No app URL, session token, JS broker, or subscriptions enter+ # this window. The acknowledged native window only owns the GUI loop.+ if not keeper.events.shown.wait(timeout=2.0):+ self._destroy_background_keeper()+ return {**status, "available": False, "reason": "hidden_window_not_ready"}+ keeper.hide()+ if self._user_requested_quit or self._shutdown_done or not self._tray.ready:+ self._destroy_background_keeper()+ return self.get_background_status()+ state.enabled = True+ elif state.enabled:+ # Never remove the sole keeper before a real control surface+ # exists again: disabling background must not become an accidental quit.+ if getattr(self, "_main_window_closing", False):+ return {**status, "reason": "window_closing"}+ self._ensure_main_window()+ shown = getattr(getattr(self._window, "events", None), "shown", None)+ if self._window is None or shown is None or not shown.wait(timeout=2.0):+ return {**self.get_background_status(), "reason": "reopen_failed"}+ self._destroy_background_keeper()+ self._sync_background_tray()+ return self.get_background_status()+ except Exception: # noqa: BLE001+ logging.getLogger(__name__).warning("Background mode transition failed", exc_info=True)+ if not state.enabled:+ self._destroy_background_keeper()+ return {**self.get_background_status(), "reason": "background_transition_failed"}+ finally:+ state.transition.release()++ def _background_keeps_running(self) -> bool:+ state = getattr(self, "_background", None)+ return bool(+ state is not None and state.enabled and state.alive+ and not state.backend_failed+ and not getattr(self, "_user_requested_quit", False)+ and not getattr(self, "_shutdown_done", False)+ and getattr(getattr(self, "_tray", None), "ready", False)+ )++ def _destroy_background_keeper(self) -> None:+ state = getattr(self, "_background", None)+ if state is None:+ return+ if not state.keeper_lock.acquire(blocking=False):+ return+ try:+ state.enabled = False+ keeper, state.keeper = state.keeper, None+ if keeper is not None:+ try:+ keeper.destroy()+ except Exception: # noqa: BLE001+ # Retain ownership so an explicit quit retries the destroy.+ state.keeper = keeper+ logging.getLogger(__name__).warning(+ "Background keeper teardown failed", exc_info=True,+ )+ finally:+ state.keeper_lock.release()++ def _on_background_keeper_closed(self, keeper: Any) -> None:+ state = getattr(self, "_background", None)+ if state is not None and state.keeper is keeper:+ state.keeper = None+ state.enabled = False+ if self._window is None and not self._detached_windows:+ self._user_requested_quit = True+ self._sync_background_tray()++ def _sync_background_tray(self) -> None:+ tray = getattr(self, "_tray", None)+ update = getattr(tray, "set_background_mode", None)+ if callable(update):+ status = self.get_background_status()+ update(status["mode"] if status["enabled"] else None)++ def _background_control_lost(self) -> None:+ """Restore a real window after tray loss, or finish a bounded full quit."""+ state = getattr(self, "_background", None)+ if state is None or not state.enabled:+ return+ result = self.set_background_mode(False)+ if result["enabled"]:+ self._user_requested_quit = True+ self._arm_force_exit(after_s=20.0)+ self._destroy_all_windows()+# ---- Backend thread ------------------------------------------------------def _run_backend(self, *, prebound: tuple[Any, Any] | None = None) -> None:@@ -2912,6 +3080,26 @@ class DesktopApp:logger.debug("Backend loop ended as part of shutdown ({}).", reason)return+ background = getattr(self, "_background", None)+ if background is not None and background.keeper is not None:+ background.backend_failed = True+ tray = getattr(self, "_tray", None)+ if tray is not None:+ tray.set_error("Backend stopped")+ # Recovery already owns its restart budget. A keeper must not turn+ # the no-window failure branch into a permanent invisible process.+ if self._window is None and not self._detached_windows:+ logger.critical(+ "Backend stopped in background mode ({}); exiting the owned shell.", reason,+ )+ self._user_requested_quit = True+ self._arm_force_exit(after_s=20.0)+ threading.Thread(+ target=self._destroy_all_windows,+ name="jarvis-background-failed", daemon=True,+ ).start()+ return+started = getattr(self, "_backend_serving_since", None)served_s = 0.0 if started is None else time.monotonic() - startedlogger.critical(@@ -3380,6 +3568,7 @@ class DesktopApp:from loguru import loggerfrom jarvis.ui.relauncher import (+ desktop_launch_args,detached_creationflags,fresh_user_env,run_restart_quit_sequence,@@ -3387,7 +3576,9 @@ class DesktopApp:)window = getattr(self, "_window", None)- if window is None and not self._detached_windows:+ if window is None and not self._detached_windows and not getattr(+ getattr(self, "_background", None), "keeper", None+ ):return (False, "no desktop window to restart")try:import jarvis as _jarvis@@ -3399,6 +3590,7 @@ class DesktopApp:"jarvis.ui.relauncher",str(os.getpid()),repo_root,+ *desktop_launch_args(),]if drop_elevation:from jarvis.platform.deescalate import spawn_unelevated@@ -3464,7 +3656,9 @@ class DesktopApp:from jarvis.ui.relauncher import run_restart_quit_sequencewindow = getattr(self, "_window", None)- if window is None and not self._detached_windows:+ if window is None and not self._detached_windows and not getattr(+ getattr(self, "_background", None), "keeper", None+ ):return Falsedef _mark_quit() -> None:@@ -4409,7 +4603,7 @@ class DesktopApp:@app.post("/api/window/focus", include_in_schema=False)async def _focus() -> dict[str, Any]:desktop = getattr(app.state, "desktop_app", None)- if desktop is None or desktop._window is None:+ if desktop is None:return {"ok": False, "reason": "no_window"}try:# Off the event loop: pywebview window methods are thread-safe@@ -4432,7 +4626,10 @@ class DesktopApp:the off-loop contract without a running server."""if self._window is None:- return {"ok": False, "reason": "no_window"}+ if getattr(getattr(self, "_background", None), "keeper", None) is not None:+ self._ensure_main_window()+ if self._window is None:+ return {"ok": False, "reason": "no_window"}self._window.show()self._window.restore()self._window_visible = True@@ -4460,6 +4657,78 @@ class DesktopApp:return set_window_fullscreen(self._window, enabled)+ def window_chrome_snapshot(self) -> dict[str, Any]:+ """What the page should draw in the title-bar corner.++ ``frameless`` follows the live window. A shell that has not opened one+ yet reports no buttons, so a page never shows controls that cannot work.+ """+ from jarvis.ui.window_command import window_chrome++ info = window_chrome()+ window = self._window+ frameless = bool(getattr(window, "frameless", False)) if window is not None else False+ info["frameless"] = frameless+ if not frameless:+ info["controls"] = "none"+ return info++ def window_command(self, action: str, view: str | None) -> dict[str, Any]:+ """Minimize, maximize or close one live window. Worker-thread safe.++ A detached view targets that window. Anything else targets the main+ window. Maximize toggles, using the real zoomed state on Windows when+ the frame hook can read it.+ """+ from jarvis.ui.window_command import run_window_command++ window = self._detached_windows.get(view) if view else None+ if window is None:+ window = self._window+ maximized: bool | None = None+ if sys.platform == "win32" and window is not None:+ try:+ from jarvis.ui.window_frame import native_hwnd, window_is_maximized++ hwnd = native_hwnd(window)+ if hwnd:+ maximized = window_is_maximized(hwnd)+ except Exception: # noqa: BLE001+ from loguru import logger++ logger.exception("Could not read whether the window is maximized")+ return run_window_command(window, action, maximized=maximized)++ def _arm_window_frame(self, window: Any) -> None:+ """Let a frameless Windows window still be resized from its edges.++ Other platforms keep the resizable window mask pywebview already sets.+ A failure here leaves the window usable: the page's own buttons still+ minimize, maximize and close it. Logged, not swallowed silently.+ """+ if sys.platform != "win32" or window is None:+ return++ def _install(*_args: Any, **_kwargs: Any) -> None:+ try:+ from jarvis.ui.window_frame import install_resize_frame, native_hwnd++ hwnd = native_hwnd(window)+ if hwnd:+ install_resize_frame(hwnd)+ except Exception: # noqa: BLE001+ from loguru import logger++ logger.exception("The window edge resize was not installed")++ try:+ window.events.shown += _install+ except Exception: # noqa: BLE001+ from loguru import logger++ logger.exception("Could not subscribe the window frame hook")+ _install()+def _window_background(self) -> str:"""The theme-correct frame color, same derivation as the main window."""from jarvis.ui.theme import window_background@@ -4518,6 +4787,8 @@ class DesktopApp:height=750,min_size=(800, 520),resizable=True,+ frameless=True,+ easy_drag=False,confirm_close=False,background_color=self._window_background(),**TEXT_SELECTABLE,@@ -4535,6 +4806,7 @@ class DesktopApp:"fallback_url": fallback,}self._detached_windows[view] = window+ self._arm_window_frame(window)window.events.loaded += lambda w=window, v=view: self._inject_into_secondary(w, v)window.events.closed += lambda v=view: self._on_detached_closed(v)self._publish_detached_event_threadsafe(view, opened=True)@@ -4573,7 +4845,13 @@ class DesktopApp:self._detached_windows.pop(view, None)self._publish_detached_event_threadsafe(view, opened=False)if not self._detached_windows and self._window is None:- self._user_requested_quit = True+ if not self._background_keeps_running():+ self._user_requested_quit = True+ threading.Thread(+ target=self._destroy_background_keeper,+ name="jarvis-final-window-close", daemon=True,+ ).start()+ self._sync_background_tray()def _inject_into_secondary(self, window: Any, view: str) -> None:"""Prime a freshly loaded detached window — ``loaded`` hook.@@ -4667,6 +4945,7 @@ class DesktopApp:except Exception: # noqa: BLE001, S110# Teardown best-effort: the window may already be gone.pass+ self._destroy_background_keeper()def _main_window_kwargs(self) -> dict[str, Any]:"""The main window's ``create_window`` kwargs — one source of truth.@@ -4679,6 +4958,8 @@ class DesktopApp:"height": 800,"min_size": (900, 600),"resizable": True,+ "frameless": True,+ "easy_drag": False,"confirm_close": False,"background_color": self._window_background(),**TEXT_SELECTABLE,@@ -4692,6 +4973,7 @@ class DesktopApp:# A `loaded` hook, not `func`: pywebview forgets DOM handlers on every# page load, and the UI reloads itself after each frontend build.self._window.events.loaded += lambda w=self._window: self._register_native_drop(w)+ self._arm_window_frame(self._window)@staticmethoddef _register_native_drop(window: Any) -> None:@@ -4713,14 +4995,30 @@ class DesktopApp:"""self._window = Noneself._window_visible = False+ self._main_window_closing = False# getattr: this hook is also exercised against the minimal fakes the# window-lifecycle tests build, which carry only the attributes the# contract under test needs.watchdog = getattr(self, "_blank_watchdog", None)if watchdog is not None:watchdog.detach()+ self._sync_background_tray()def _ensure_main_window(self) -> None:+ """Serialize concurrent tray, focus-route, and background-mode reopen requests."""+ lock = getattr(self, "_main_window_lock", None)+ if lock is None:+ lock = self._main_window_lock = threading.RLock()+ with lock:+ if (+ getattr(self, "_user_requested_quit", False)+ or getattr(self, "_shutdown_done", False)+ ):+ return+ self._ensure_main_window_unlocked()+ self._sync_background_tray()++ def _ensure_main_window_unlocked(self) -> None:"""Show the main window, recreating it if it was closed — tray thread.With detached windows, closing main no longer quits; the tray "Open"@@ -4740,6 +5038,7 @@ class DesktopApp:WINDOW_TITLE, self._url(), **self._main_window_kwargs())self._hook_main_window_lifecycle()+ self._window.events.loaded += lambda w=self._window: self._inject_reopened_main(w)self._window_visible = True# A window reopened from the tray can arrive blank for exactly the# same reasons as the boot one, so it gets the same guard.@@ -4762,6 +5061,19 @@ class DesktopApp:# ---- WebView hooks -------------------------------------------------------+ def _inject_reopened_main(self, window: Any) -> None:+ """Reopen with the shared cookie, without replaying the consumed boot token."""+ broker_token = json.dumps(self.realtime_transport_broker_token)+ try:+ window.evaluate_js(+ "window.__JARVIS_EMBEDDED_DESKTOP = true;"+ "Object.defineProperty(window, '__JARVIS_REALTIME_BROKER_TOKEN', {"+ f"value: {broker_token}, configurable: true, writable: false"+ "});window.dispatchEvent(new Event('jarvis-token-ready'));"+ )+ except Exception: # noqa: BLE001+ logging.getLogger(__name__).warning("Reopened window bridge unavailable", exc_info=True)+def _inject_token(self, window: Any) -> None:"""Offer the one-time process token to the UI session exchange.@@ -5244,6 +5556,9 @@ class DesktopApp:# it away with the process. Only when no directory can be written does# the shell fall back to that private mode, and says so.storage_dir = webview_storage_dir()+ # Private WebViews clear shared cookies when another window is created.+ # Background mode must not strand an authenticated user after reopening.+ self._webview_persistent_profile = storage_dir is not Noneif storage_dir is None:from loguru import logger as _profile_logger@@ -5475,6 +5790,9 @@ class DesktopApp:thread-safe, but a dedicated bridge thread makes the ownershipexplicit and allows for back-pressure/debounce later."""+ bridge = getattr(self, "_tray_bridge_thread", None)+ if bridge is not None and bridge.is_alive():+ returnfrom jarvis.ui.tray import JarvisState, JarvisTraytray = JarvisTray()@@ -5489,8 +5807,12 @@ class DesktopApp:try:cmd = cmd_queue.get(timeout=0.5)except queue.Empty:- # The idle case of a polling loop, not a failure: no command- # arrived within the tick, so check the shutdown flag again.+ # With every client closed, this bridge is the remaining+ # observer of tray loss. Reuse its idle tick so a keeper+ # cannot strand execution without an Open/Quit surface.+ background = getattr(self, "_background", None)+ if background is not None and background.enabled and not tray.ready:+ self._background_control_lost()continueaction = cmd.actionif action == "open_ui":@@ -5508,13 +5830,19 @@ class DesktopApp:self._publish_kill_requested_threadsafe()elif action == "quit":self._user_requested_quit = True+ self._arm_force_exit(after_s=20.0)# Detached windows too: webview.start() returns only once# the LAST window closes, so a survivor would keep a# quit-flagged process running headless.self._destroy_all_windows()return+ elif action == "tray_unavailable":+ self._background_control_lost()- threading.Thread(target=_bridge_loop, name="jarvis-tray-bridge", daemon=True).start()+ self._tray_bridge_thread = threading.Thread(+ target=_bridge_loop, name="jarvis-tray-bridge", daemon=True,+ )+ self._tray_bridge_thread.start()def _publish_kill_requested_threadsafe(self) -> None:"""Publish ``KillRequested(source="tray")`` from a non-async thread.@@ -5562,6 +5890,8 @@ class DesktopApp:def _safe_window_show(self) -> None:if self._window is None:+ if getattr(getattr(self, "_background", None), "keeper", None) is not None:+ self._ensure_main_window()returntry:self._window.show()@@ -5613,35 +5943,26 @@ class DesktopApp:# the user sees an error page that never refreshes.logger.warning("Could not reload the stale window: {}", exc)- # ---- Window close (X) = minimise to tray + clear overlay ---------------+ # ---- Window close: explicit quit unless the session opted into background ----def _on_window_closing(self) -> bool:- """pywebview ``closing`` callback: the X (close) fully QUITS Jarvis.-- User mandate (2026-07-01): closing the desktop window must tear- EVERYTHING down — tray icon, JarvisBar overlay, voice pipeline, backend- server, child subprocesses and the process itself — not merely hide to- tray. To keep Jarvis running in the background (so "Hey Jarvis" stays- live) the user MINIMISES the window instead of closing it.-- ONE exception (detachable views, 2026-08-07): while a detached solo- window is open, the X closes ONLY the main window — the user split that- view off precisely to keep using it without the main app. The mandate's- real content ("nothing lingers once the user is done") moves to the- LAST window: ``webview.start()`` returns only when every window is- gone, and ``_on_detached_closed`` sets the quit flag when the final one- goes. With no detached windows this method is byte-identical to before.-- We mark the quit and return ``True`` so pywebview destroys the window;- ``webview.start()`` then returns and :meth:`run_window_only` runs- :meth:`shutdown` (stops every surface) followed by a hard-exit backstop- that guarantees the process actually dies even if a native thread- (WebView2/Tk teardown, a wedged ctranslate2 transcribe — AP-24) would- otherwise keep it — and its tray icon — alive (forensic 2026-06-27: a- hung shutdown kept the old process ~30 min).+ """Destroy the actual client window, preserving only an explicit opt-in.++ Default close still quits once the last real window closes. A session+ that deliberately armed background mode keeps only its blank native+ keeper and verified tray; the closed client's canvas and subscriptions+ are released. Explicit Quit always overrides the background preference."""- if not self._detached_windows:+ self._main_window_closing = True+ if not self._detached_windows and not self._background_keeps_running():self._user_requested_quit = True+ if getattr(getattr(self, "_background", None), "keeper", None) is not None:+ # The closing event waits for us; native destruction must run+ # after this callback releases the GUI thread.+ threading.Thread(+ target=self._destroy_background_keeper,+ name="jarvis-background-close", daemon=True,+ ).start()return Truedef _suppress_overlay_for_hidden_window(self) -> None:@@ -5737,6 +6058,7 @@ class DesktopApp:return 0self._shutdown_done = Trueself._window_visible = False+ self._destroy_background_keeper()# A shutting-down backend fails every health probe by design; without# this the guard would read the teardown as a blank-window incident and@@ -5966,6 +6288,14 @@ class DesktopApp:_logger.warning("Tray icon did not stop cleanly: {}", exc)self._tray = None+ bridge = getattr(self, "_tray_bridge_thread", None)+ if bridge is not None and bridge is not threading.current_thread():+ bridge.join(timeout=2.0)+ if bridge.is_alive():+ logging.getLogger(__name__).warning(+ "Tray command bridge did not stop within two seconds",+ )+try:META_FILE_PATH.unlink(missing_ok=True)except Exception as exc: # noqa: BLE001diff --git a/jarvis/ui/desktop_background.py b/jarvis/ui/desktop_background.pynew file mode 100644index 0000000000..66f59bb14d--- /dev/null+++ b/jarvis/ui/desktop_background.py@@ -0,0 +1,171 @@+"""Session-only state for the desktop shell's explicit background lifecycle."""++from __future__ import annotations++import logging+import os+import threading+from collections.abc import Callable+from functools import lru_cache+from typing import Any, Literal, TypedDict+++class BackgroundStatus(TypedDict):+ available: bool+ reason: str | None+ enabled: bool+ mode: Literal["foreground", "background", "stopping", "stopped"]+ window_open: bool+++class BackgroundSession:+ """Own only the blank GUI keeper; never own execution or its subscriptions."""++ def __init__(self) -> None:+ self.enabled = False+ self.keeper: Any = None+ self.backend_failed = False+ self.transition = threading.Lock()+ self.keeper_lock = threading.Lock()++ @property+ def alive(self) -> bool:+ keeper = self.keeper+ return keeper is not None and not keeper.events.closed.is_set()+++def _query_notification_icon_rect(hwnd: int, icon_id: int, shell32: Any) -> bool:+ """Marshal the documented shell API; the injected DLL keeps CI native-free."""+ import ctypes # noqa: PLC0415++ class Identifier(ctypes.Structure):+ _fields_ = [+ ("cbSize", ctypes.c_uint32),+ ("hWnd", ctypes.c_void_p),+ ("uID", ctypes.c_uint32),+ ("guidItem", ctypes.c_ubyte * 16),+ ]++ class Rect(ctypes.Structure):+ _fields_ = [+ ("left", ctypes.c_int32), ("top", ctypes.c_int32),+ ("right", ctypes.c_int32), ("bottom", ctypes.c_int32),+ ]++ query = shell32.Shell_NotifyIconGetRect+ # Stable pointer argtypes also allow two independently owned tray probes+ # to share the cached DLL without replacing each other's local struct types.+ query.argtypes = [ctypes.c_void_p, ctypes.c_void_p]+ query.restype = ctypes.c_int32+ identifier = Identifier(cbSize=ctypes.sizeof(Identifier), hWnd=hwnd, uID=icon_id)+ rect = Rect()+ return (+ query(ctypes.byref(identifier), ctypes.byref(rect)) == 0+ and rect.right > rect.left and rect.bottom > rect.top+ )+++@lru_cache(maxsize=1)+def _native_shell32() -> Any:+ if os.name != "nt":+ return None+ import ctypes # noqa: PLC0415++ return ctypes.WinDLL("shell32", use_last_error=True)+++def native_tray_present(icon: Any) -> bool:+ """Require a shell-owned rectangle, not pystray's optimistic visible flag.++ Windows borrows the tray's HWND; no hook or native handle is allocated.+ Other OSes keep their ordinary tray but decline background ownership until+ an equivalent native registration/presence acknowledgment is implemented.+ """+ if os.name != "nt":+ return False+ hwnd = getattr(icon, "_hwnd", None)+ if not hwnd:+ return False+ try:+ shell32 = _native_shell32()+ # pystray 0.19 uses uID=0; accept the object ID spelling used by some+ # backend variants too, always under this icon's own callback HWND.+ return any(+ _query_notification_icon_rect(int(hwnd), icon_id, shell32)+ for icon_id in (0, id(icon) & 0xFFFFFFFF)+ )+ except (AttributeError, OSError, TypeError, ValueError):+ logging.getLogger(__name__).debug("Native tray presence unavailable", exc_info=True)+ return False+++class TrayPresenceProbe:+ """At most one native query in flight, with a bounded caller wait and stop."""++ def __init__(self, query: Callable[[Any], bool] = native_tray_present) -> None:+ self._query = query+ self._lock = threading.Lock()+ self._thread: threading.Thread | None = None+ self._result: list[bool] = []+ self._icon: Any = None+ self._stopped = False++ def check(self, icon: Any, *, timeout: float = 0.25) -> bool:+ with self._lock:+ if self._stopped:+ return False+ thread = self._thread+ if thread is not None and thread.is_alive() and self._icon is not icon:+ return False+ if thread is None or not thread.is_alive():+ result: list[bool] = []++ def _query() -> None:+ try:+ result.append(bool(self._query(icon)))+ except Exception: # noqa: BLE001+ logging.getLogger(__name__).warning(+ "Tray presence query failed", exc_info=True,+ )+ result.append(False)++ thread = threading.Thread(target=_query, name="jarvis-tray-presence", daemon=True)+ self._thread = thread+ self._result = result+ self._icon = icon+ thread.start()+ result = self._result+ thread.join(timeout=timeout)+ return not self._stopped and not thread.is_alive() and result == [True]++ def stop(self) -> None:+ with self._lock:+ self._stopped = True+ thread = self._thread+ if thread is not None and thread is not threading.current_thread():+ thread.join(timeout=2.0)+ if thread.is_alive():+ logging.getLogger(__name__).warning(+ "Native tray query did not stop within two seconds",+ )++ def resume(self) -> None:+ """Never abandon a hung native query in order to start another one."""+ with self._lock:+ if self._thread is None or not self._thread.is_alive():+ self._stopped = False+++def native_background_reason(window: Any) -> str | None:+ """Probe the running GUI, not merely whether pywebview can be imported."""+ if window is None or getattr(window, "gui", None) is None:+ return "native_window_unavailable"+ # GTK's runtime show() ignores hidden=True once its main loop is running.+ # Keep the ordinary window/headless paths usable until that backend has a+ # verified invisible-keeper lifecycle; do not flash a window as a workaround.+ if getattr(window.gui, "renderer", None) == "gtkwebkit2":+ return "hidden_window_unavailable"+ shown = getattr(getattr(window, "events", None), "shown", None)+ if shown is None or not shown.is_set():+ return "native_window_not_ready"+ return Nonediff --git a/jarvis/ui/jarvisbar/overlay.py b/jarvis/ui/jarvisbar/overlay.pyindex c3d88b97fe..06f3dfbc25 100644--- a/jarvis/ui/jarvisbar/overlay.py+++ b/jarvis/ui/jarvisbar/overlay.py@@ -744,6 +744,9 @@ class JarvisBarOverlay:def start(self) -> None:import tkinter as tk+ from jarvis.ui.tk_runtime import prepare_tk_runtime++ prepare_tk_runtime()from PIL import ImageTk # noqa: F401 — fail fast here if Pillow missing# DPI strategy (two steps, order matters — both no-ops off Windows):diff --git a/jarvis/ui/relauncher.py b/jarvis/ui/relauncher.pyindex e0173c067d..48b392ab51 100644--- a/jarvis/ui/relauncher.py+++ b/jarvis/ui/relauncher.py@@ -52,9 +52,43 @@ _DEFAULT_ADMIN_PORT = 47821#: from a process inside a Windows Job Object dies with its parent — the#: window closes and nothing comes back (BUG-181)._CREATE_BREAKAWAY_FROM_JOB = 0x01000000+_desktop_launch_args: tuple[str, ...] = ()-def build_launch_command(executable: str) -> list[str]:+def remember_desktop_launch_args(+ *,+ port: int | None,+ dev: bool,+ no_lock: bool,+) -> None:+ """Retain parsed session overrides without persisting them into user config."""+ global _desktop_launch_args+ _desktop_launch_args = _desktop_overrides(port=port, dev=dev, no_lock=no_lock)+++def desktop_launch_args() -> tuple[str, ...]:+ """Return the current desktop's overrides from the canonical helper module."""+ return _desktop_launch_args+++def _desktop_overrides(*, port: int | None, dev: bool, no_lock: bool) -> tuple[str, ...]:+ args: list[str] = []+ if port is not None:+ if not 1 <= port <= 65535:+ raise ValueError("Desktop port must be between 1 and 65535")+ args.extend(("--port", str(port)))+ if dev:+ args.append("--dev")+ if no_lock:+ args.append("--no-lock")+ return tuple(args)+++def build_launch_command(+ executable: str,+ *,+ launcher_args: tuple[str, ...] = (),+) -> list[str]:"""Argv that boots a fresh desktop app through its stable OS identity.A macOS desktop restart always re-enters through LaunchServices so it can@@ -65,7 +99,8 @@ def build_launch_command(executable: str) -> list[str]:from jarvis.core.instance import current_instanceidentity = current_instance()- fallback = [executable, "-m", LAUNCHER_MODULE, *identity.launcher_args]+ args = (*identity.launcher_args, *launcher_args)+ fallback = [executable, "-m", LAUNCHER_MODULE, *args]if sys.platform == "darwin" and not identity.is_default:# The bundle is the DEFAULT app's stable identity and LaunchServices# does not carry ``JARVIS_INSTANCE`` into it — re-entering through it@@ -87,12 +122,12 @@ def build_launch_command(executable: str) -> list[str]:logging.getLogger(__name__).error("macOS restart target is missing or invalid: %s", bundle)- return macos_launch_services_command(bundle, wait_for_exit=True)+ return macos_launch_services_command(bundle, wait_for_exit=True, arguments=args)except Exception: # noqa: BLE001 - preserve stable identity fail-closedlogging.getLogger(__name__).exception("Could not validate the macOS restart bundle; using its canonical path")- return ["/usr/bin/open", "-W", "-a", str(bundle)]+ return ["/usr/bin/open", "-W", "-a", str(bundle), *(["--args", *args] if args else [])]if sys.platform == "win32":branded = _existing_branded_launcher()if branded is not None:@@ -100,7 +135,7 @@ def build_launch_command(executable: str) -> list[str]:# process. Spawning ``python -m launcher`` used to re-exec through# this copy and exit; the helper treated that exit as a bounce and# started two more copies that raced the first (BUG-181).- return [str(branded), "-m", LAUNCHER_MODULE, *identity.launcher_args]+ return [str(branded), "-m", LAUNCHER_MODULE, *args]return fallback@@ -327,6 +362,7 @@ def _desktop_is_serving(cwd: str | Path | None = None,host: str = "127.0.0.1",timeout: float = 0.25,+ port: int | None = None,_connect=None,) -> bool:"""True when something is already accepting on this instance's admin port.@@ -339,7 +375,7 @@ def _desktop_is_serving(import socketconnect = _connect or socket.create_connection- port = _restart_admin_port(cwd)+ port = port if port is not None else _restart_admin_port(cwd)try:with connect((host, port), timeout=timeout):return True@@ -779,8 +815,30 @@ def main(except ValueError:return 2cwd = argv[1]+ # Only supported desktop overrides cross this process boundary. The+ # instance identity still comes from the inherited instance environment.+ import argparse # noqa: PLC0415++ parser = argparse.ArgumentParser(add_help=False, allow_abbrev=False)+ parser.add_argument("--port", type=int)+ parser.add_argument("--dev", action="store_true")+ parser.add_argument("--no-lock", action="store_true")+ try:+ options = parser.parse_args(argv[2:])+ launcher_args = _desktop_overrides(+ port=options.port,+ dev=options.dev,+ no_lock=options.no_lock,+ )+ except (SystemExit, ValueError):+ logging.getLogger(__name__).error("Invalid desktop restart overrides")+ return 2_report = _report or _report_restart_failure- serving = _serving if _serving is not None else (lambda: _desktop_is_serving(cwd=cwd))+ serving = (+ _serving+ if _serving is not None+ else (lambda: _desktop_is_serving(cwd=cwd, port=options.port))+ )try:from jarvis.ui.desktop_log import _install_desktop_log_sink, desktop_log_path@@ -790,7 +848,7 @@ def main(except Exception: # noqa: BLE001, S110 — a mute helper is what we had beforepass- cmd = build_launch_command(sys.executable)+ cmd = build_launch_command(sys.executable, launcher_args=launcher_args)env = _apply_branded_launch_env(fresh_user_env(), cmd)update_finalized = Falsediff --git a/jarvis/ui/tk_runtime.py b/jarvis/ui/tk_runtime.pynew file mode 100644index 0000000000..b6d2a6dec7--- /dev/null+++ b/jarvis/ui/tk_runtime.py@@ -0,0 +1,43 @@+"""Locate Tcl/Tk data for Windows launchers copied away from their interpreter."""++from __future__ import annotations++import os+import sys+from pathlib import Path+++def prepare_tk_runtime() -> None:+ """Keep Tk initialization tied to the Python runtime, not the launcher.++ A per-user branded pythonw copy can load Python and _tkinter while Tcl+ searches beside that copy for init.tcl. Use existing data from the loaded+ extension's installation. Explicit environment overrides remain intact.+ This creates no interpreter/window and is only called when opening a Tk+ surface; macOS, Linux and headless imports keep their native discovery.+ """+ if sys.platform != "win32":+ return++ import _tkinter++ roots = []+ extension_file = getattr(_tkinter, "__file__", None)+ if extension_file:+ roots.append(Path(extension_file).resolve().parent.parent)+ roots.append(Path(sys.base_prefix))+ for variable, library, version, marker in (+ ("TCL_LIBRARY", "tcl", _tkinter.TCL_VERSION, "init.tcl"),+ ("TK_LIBRARY", "tk", _tkinter.TK_VERSION, "tk.tcl"),+ ):+ if os.environ.get(variable):+ continue+ candidates = (+ root / folder / f"{library}{version}"+ for root in roots+ for folder in ("tcl", "lib")+ )+ for candidate in candidates:+ if (candidate / marker).is_file():+ os.environ[variable] = str(candidate)+ breakdiff --git a/jarvis/ui/tray.py b/jarvis/ui/tray.pyindex 903e9ea520..11c5d1c19a 100644--- a/jarvis/ui/tray.py+++ b/jarvis/ui/tray.py@@ -100,7 +100,17 @@ class JarvisTray:tray.stop()"""- def __init__(self, on_command: Callable[[TrayCommand], None] | None = None) -> None:+ def __init__(+ self,+ on_command: Callable[[TrayCommand], None] | None = None,+ *,+ native_presence: Callable[[Any], bool] | None = None,+ ) -> None:+ from jarvis.ui.desktop_background import ( # noqa: PLC0415+ TrayPresenceProbe,+ native_tray_present,+ )+self._on_command = on_command or (lambda _: None)self._state = JarvisState.IDLEself._icon: Any = None@@ -109,6 +119,70 @@ class JarvisTray:# True when the darwin icon runs detached on the AppKit main thread;# icon mutations must then be marshaled via _call_on_main (BUG-056).self._darwin_detached = False+ self._ready = threading.Event()+ self._setup_complete = threading.Event()+ self._presence_query = native_presence or native_tray_present+ self._presence = TrayPresenceProbe(self._presence_query)+ self._stopping = threading.Event()+ self._background_mode: str | None = None++ @property+ def ready(self) -> bool:+ """The visible icon has a working menu, including Open and Quit."""+ if not self._setup_complete.is_set() or self._stopping.is_set():+ return False+ if not self._presence.check(self._icon) or self._stopping.is_set():+ self._notify_unavailable()+ return False+ self._ready.set()+ return True++ def _setup_icon(self, icon: Any) -> None:+ # pystray invokes setup only after its native message loop is ready.+ # AppKit mutations still belong on its main thread, including this one.+ def _show() -> None:+ if self._stopping.is_set() or self._icon is not icon:+ return+ try:+ icon.visible = True+ if icon.visible and getattr(icon, "HAS_MENU", False):+ self._setup_complete.set()+ if self.ready:+ self._ready.set()+ except Exception: # noqa: BLE001+ log.warning("Tray visibility setup failed", exc_info=True)+ self._notify_unavailable()++ self._call_on_main(_show)++ def _notify_unavailable(self) -> None:+ was_ready = self._ready.is_set()+ self._ready.clear()+ if was_ready and not self._stopping.is_set():+ self._command_queue.put(TrayCommand(action="tray_unavailable"))++ def set_background_mode(self, mode: str | None) -> None:+ """Expose lifecycle independently of the voice activity indicator."""+ self._background_mode = mode+ icon = self._icon+ if icon is None:+ return++ def _apply() -> None:+ try:+ icon.title = self._tooltip()+ icon.update_menu()+ except Exception: # noqa: BLE001+ log.warning("Tray lifecycle status update failed", exc_info=True)+ self._notify_unavailable()++ self._call_on_main(_apply)++ def _tooltip(self) -> str:+ state = self._state.value+ if self._background_mode:+ state = f"{self._background_mode}; {state}"+ return f"{_TRAY_NAME} — {state}"def _build_menu(self) -> Any:from pystray import Menu, MenuItem # type: ignore[import-untyped]@@ -128,6 +202,10 @@ class JarvisTray:MenuItem("Open", _emit("open_ui"), default=True),Menu.SEPARATOR,MenuItem(lambda _: f"Status: {self._state.value}", None, enabled=False),+ MenuItem(+ lambda _: f"Application: {self._background_mode}", None,+ enabled=False, visible=lambda _: self._background_mode is not None,+ ),Menu.SEPARATOR,MenuItem("Pause", _emit("pause"),checked=lambda _: self._state == JarvisState.PAUSED),@@ -157,7 +235,7 @@ class JarvisTray:title=f"{_TRAY_NAME} — idle",menu=self._build_menu(),)- self._icon.run()+ self._icon.run(setup=self._setup_icon)except ModuleNotFoundError as exc:log.warning("Tray not started: optional desktop dependency %r is unavailable. "@@ -166,6 +244,7 @@ class JarvisTray:exc.name or "unknown",)self._icon = None+except Exception: # noqa: BLE001 — a missing tray host must not die silently (AD-6)log.warning("Tray icon could not start (no notification-area / AppIndicator "@@ -174,10 +253,16 @@ class JarvisTray:)# The thread exits normally after this; a later start() can re-arm.self._icon = None+ finally:+ self._notify_unavailable()+ self._setup_complete.clear()def start(self) -> None:if self._thread is not None and self._thread.is_alive():return+ if self._stopping.is_set():+ self._presence.resume()+ self._stopping.clear()if sys.platform == "darwin":# pystray's darwin backend builds an NSStatusItem in Icon.__init__;# AppKit allows UI objects on the MAIN thread only. Created from a@@ -211,8 +296,8 @@ class JarvisTray:menu=self._build_menu(),darwin_nsapplication=nsapp,)- self._icon.run_detached()self._darwin_detached = True+ self._icon.run_detached(setup=self._setup_icon)except Exception: # noqa: BLE001 — a broken menu-bar host must not crash boot (AD-6)log.warning("Tray not started: macOS menu-bar icon could not be "@@ -240,8 +325,8 @@ class JarvisTray:macOS drives the NSStatusItem behind the icon on the main thread only(BUG-056), so mutations from worker threads are marshaled through- PyObjCTools.AppHelper.callAfter. Everywhere else (and as a last- resort when the marshal itself is unavailable) fn runs directly.+ PyObjCTools.AppHelper.callAfter. Other backends run directly; a failed+ AppKit marshal loses the tray capability instead of risking a native abort."""if not self._darwin_detached:fn()@@ -250,10 +335,15 @@ class JarvisTray:from PyObjCTools import AppHelper # type: ignore[import-not-found]AppHelper.callAfter(fn)- except Exception: # noqa: BLE001 — AD-6: degrade to a direct call- fn()+ except Exception: # noqa: BLE001+ log.warning("Tray main-thread dispatch unavailable", exc_info=True)+ self._notify_unavailable()def stop(self) -> None:+ self._stopping.set()+ self._ready.clear()+ self._setup_complete.clear()+ self._presence.stop()if self._icon is not None:icon = self._icon@@ -261,11 +351,18 @@ class JarvisTray:try:icon.stop()except Exception: # noqa: BLE001- pass+ log.warning("Tray stop failed", exc_info=True)self._call_on_main(_do_stop)self._icon = Noneself._darwin_detached = False+ thread = self._thread+ if thread is not None and thread is not threading.current_thread():+ thread.join(timeout=2.0)+ if thread.is_alive():+ log.warning("Tray thread did not stop within two seconds")+ else:+ self._thread = Nonedef set_state(self, state: JarvisState) -> None:"""Thread-safe state update — re-renders the icon and tooltip."""@@ -279,7 +376,7 @@ class JarvisTray:def _apply() -> None:try:icon.icon = _make_icon(state)- icon.title = f"{_TRAY_NAME} — {state.value}"+ icon.title = self._tooltip()except Exception: # noqa: BLE001passdiff --git a/jarvis/ui/web/agent_chat_routes.py b/jarvis/ui/web/agent_chat_routes.pyindex f1d1077771..b21fdeaac6 100644--- a/jarvis/ui/web/agent_chat_routes.py+++ b/jarvis/ui/web/agent_chat_routes.py@@ -236,7 +236,13 @@ def _validate_cwd(raw: str | None) -> str | None:@router.get("/catalog")-async def get_catalog(request: Request, surface: SurfaceName = "agent") -> dict[str, Any]:+async def get_catalog(+ request: Request,+ surface: SurfaceName = "agent",+ account_id: str = "",+ session_id: str = "",+ cwd: str | None = None,+) -> dict[str, Any]:"""Provider rows for the composer's picker.Static shape from ``jarvis.agent_chat.catalog`` plus two live facts per@@ -253,7 +259,26 @@ async def get_catalog(request: Request, surface: SurfaceName = "agent") -> dict[svc = _service(request)rows: list[dict[str, Any]] = []cli_seats = kit_for(surface).cli_seats- live_models = await _live_cli_models() if cli_seats else {}+ from jarvis.agent_chat.runner_cli import cli_catalog_scope++ if session_id:+ session = svc.store.get_session(session_id)+ if session is None or session.surface != surface:+ raise HTTPException(status_code=404, detail="Chat session not found")+ account_id = session.account_id+ cwd = session.cwd+ if account_id:+ from jarvis import agent_accounts++ if agent_accounts.resolve(account_id) is None:+ raise HTTPException(status_code=400, detail="Unknown subscription account")+ folder = _validate_cwd(cwd)+ with cli_catalog_scope(+ account_id=account_id,+ cwd=Path(folder) if folder else None,+ ignore_user_config=kit_for(surface).brain_runner and cli_seats,+ ):+ live_models = await _live_cli_models() if cli_seats else {}for row in rows_for(surface):d = row.to_dict()runner = resolve_runner(row.id, surface=surface)@@ -261,7 +286,7 @@ async def get_catalog(request: Request, surface: SurfaceName = "agent") -> dict[d["cli_installed"] = _cli_installed(runner) if runner not in ("api", "brain") else None# A CLI that publishes its own model list (agy, Codex) overrides the# curated fallback with what THIS account can actually pick.- if d["cli_installed"] and runner in live_models and live_models[runner]:+ if d["cli_installed"] and runner in live_models:d["curated_models"] = live_models[runner]# The dual row: Claude Code takes its own ids and aliases; with only# an API key — and on a surface with no CLI seats, always — the@@ -793,11 +818,16 @@ async def cancel_turn(session_id: str, request: Request) -> dict[str, Any]:svc = _service(request)if svc.store.get_session(session_id) is None:raise HTTPException(status_code=404, detail="session not found")+ session = svc.store.get_session(session_id)cancelled = svc.is_running(session_id)- if svc.store.get_session(session_id).surface in ("jarvis", "society"):+ if session.surface in ("jarvis", "society"):await svc.controls.pause(session_id, "Stopped by the user")else:cancelled = await svc.cancel(session_id)+ # The runner can already be gone while the transcript still shows Working.+ # Closing that turn is what makes the stop button leave the chat.+ if not svc.is_running(session_id):+ cancelled = await svc.seal_stopped_turn(session_id) or cancelledreturn {"cancelled": cancelled, "session_id": session_id}diff --git a/jarvis/ui/web/chats_routes.py b/jarvis/ui/web/chats_routes.pyindex 2e791adc72..5e92d96a66 100644--- a/jarvis/ui/web/chats_routes.py+++ b/jarvis/ui/web/chats_routes.py@@ -204,6 +204,21 @@ def _normalized_messages(return Noneturns = session_store.get_turns(cid)events = _voice_events(session_store, cid)+ live_messages = _live_voice_messages(events)+ if live_messages:+ return live_messages+ # Older GPT-Live sessions retained every fragment even while the chat+ # rendered only the current caption. Recover them without a migration.+ from jarvis.core.paths import user_data_dir+ from jarvis.live.transcript import read_legacy_transcript++ legacy = read_legacy_transcript(user_data_dir() / "live.sqlite3", cid)+ if legacy:+ origin = legacy[0].start_ms+ return [ChatTurn(+ role=caption.role, text=caption.text,+ ts_ms=int(session.started_ms) + caption.start_ms - origin,+ ) for caption in legacy]out: list[ChatTurn] = []for turn in turns:if getattr(turn, "user_text", ""):@@ -246,6 +261,42 @@ def _voice_events(session_store: Any, session_id: str) -> list[Any]:return []+def _live_voice_messages(events: list[Any]) -> list[ChatTurn]:+ """Replay continuous speaker snapshots without collapsing a whole call."""+ segments: dict[str, dict[str, Any]] = {}+ for event in events:+ if event.kind != "VoiceTranscriptUpdated":+ continue+ payload = event.payload+ segment_id = str(payload.get("segment_id", ""))+ role = payload.get("role")+ if not segment_id or role not in {"user", "assistant"}:+ continue+ previous = segments.get(segment_id)+ revision = int(payload.get("revision", 0))+ if previous and revision <= previous["revision"]:+ continue+ segments[segment_id] = {+ "role": role, "text": str(payload.get("text", "")), "revision": revision,+ "start": previous["start"] if previous else event.ts_ms,+ "end": event.ts_ms, "audio_start": int(payload.get("start_ms", 0)),+ }+ ordered = sorted(segments.values(), key=lambda item: (item["audio_start"], item["start"]))+ messages = []+ trace_start = min((item["start"] for item in ordered), default=0)+ for item in ordered:+ if not item["text"].strip():+ continue+ trace = None+ if item["role"] == "assistant":+ trace = trace_from_events(events, since_ms=trace_start, until_ms=item["end"])+ trace_start = item["end"] + 1+ messages.append(ChatTurn(+ role=item["role"], text=item["text"], ts_ms=item["start"], trace=trace,+ ))+ return messages++def _voice_turn_trace(turn: Any, events: list[Any]) -> dict[str, Any] | None:"""The reasoning trace of one voice turn, from the session recorder's rows.diff --git a/jarvis/ui/web/desktop_routes.py b/jarvis/ui/web/desktop_routes.pyindex 8578809203..45fefa676a 100644--- a/jarvis/ui/web/desktop_routes.py+++ b/jarvis/ui/web/desktop_routes.py@@ -29,7 +29,7 @@ from __future__ import annotationsimport asyncioimport logging-from typing import Any+from typing import Any, Literalfrom fastapi import APIRouter, Requestfrom pydantic import BaseModel, Field@@ -43,6 +43,33 @@ class DetachBody(BaseModel):view: str = Field(min_length=1, max_length=64)+class BackgroundBody(BaseModel):+ enabled: bool = Field(strict=True)++[email protected]("/background", operation_id="background_status")+async def window_background_status(request: Request) -> dict[str, Any]:+ """Read the explicit window-close background policy and native availability."""+ desktop = getattr(request.app.state, "desktop_app", None)+ getter = getattr(desktop, "get_background_status", None)+ if not callable(getter):+ return {+ "available": False, "reason": "headless_host", "enabled": True,+ "mode": "background", "window_open": False,+ }+ return await asyncio.to_thread(getter)++[email protected]("/background", operation_id="background_set")+async def window_background_set(body: BackgroundBody, request: Request) -> dict[str, Any]:+ """Opt into background work for this session; explicit Quit still stops the app."""+ desktop = getattr(request.app.state, "desktop_app", None)+ setter = getattr(desktop, "set_background_mode", None)+ if not callable(setter):+ return await window_background_status(request)+ return await asyncio.to_thread(setter, body.enabled)++def _solo_url_path(view: str) -> str:"""Relative solo URL for a view — the SPA catch-all serves it anywhere."""return f"/?view={view}&solo=1"@@ -124,6 +151,48 @@ class FullscreenBody(BaseModel):enabled: bool+class WindowCommandBody(BaseModel):+ action: Literal["minimize", "maximize", "close"]+ view: str | None = Field(default=None, max_length=64)++[email protected]("/chrome", operation_id="chrome")+async def window_chrome(request: Request) -> dict[str, Any]:+ """Whether this window draws its own minimize, maximize and close.++ A browser tab and a headless server answer ``frameless: false`` so the+ page does not invent window buttons that do nothing. The desktop shell+ answers from the live window.+ """+ desktop = getattr(request.app.state, "desktop_app", None)+ fn = getattr(desktop, "window_chrome_snapshot", None)+ if not callable(fn):+ return {"ok": True, "frameless": False, "platform": "headless", "controls": "none"}+ try:+ return await asyncio.to_thread(fn)+ except Exception as exc: # noqa: BLE001+ log.warning("window chrome failed: %s: %s", type(exc).__name__, exc)+ return {"ok": False, "frameless": False, "controls": "none", "reason": type(exc).__name__}++[email protected]("/command", operation_id="command")+async def window_command(body: WindowCommandBody, request: Request) -> dict[str, Any]:+ """Minimize, maximize or close the window the page is showing.++ ``view`` names a detached window. Omitted, the main window is used.+ Closing follows the same path as the window's own close button.+ """+ desktop = getattr(request.app.state, "desktop_app", None)+ fn = getattr(desktop, "window_command", None)+ if not callable(fn):+ return {"ok": False, "reason": "no_desktop_shell"}+ try:+ return await asyncio.to_thread(fn, body.action, body.view or None)+ except Exception as exc: # noqa: BLE001+ log.warning("window command failed: %s: %s", type(exc).__name__, exc)+ return {"ok": False, "reason": f"{type(exc).__name__}: {exc}"}++@router.post("/fullscreen", operation_id="fullscreen")async def window_fullscreen(body: FullscreenBody, request: Request) -> dict[str, Any]:"""Enter or leave native desktop fullscreen."""diff --git a/jarvis/ui/web/frontend/public/THIRD_PARTY_NOTICES.txt b/jarvis/ui/web/frontend/public/THIRD_PARTY_NOTICES.txtindex 1a9ca35f9f..ed59ae616a 100644--- a/jarvis/ui/web/frontend/public/THIRD_PARTY_NOTICES.txt+++ b/jarvis/ui/web/frontend/public/THIRD_PARTY_NOTICES.txt@@ -44,3 +44,32 @@ licence text and a FAQ are available at https://openfontlicense.org. Thefonts may be used, studied, modified and redistributed freely as long asthey are not sold by themselves; the reserved font names may not be usedfor modified versions.+++----------------------------------------------------------------------++Hermes Agent bot avatar geometry and eye placement+https://github.com/NousResearch/hermes-agent/blob/4a2bd7406ee3e09bd30a42cf9a7b970aac6edf9e/apps/desktop/src/plugins/hermes-bots/avatar.tsx+Adapted in src/components/society/AgentSymbol.tsx.++MIT License++Copyright (c) 2025 Nous Research++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/jarvis/ui/web/frontend/scripts/check-realtime-worklet.mjs b/jarvis/ui/web/frontend/scripts/check-realtime-worklet.mjsindex 23382f6bbd..1ac3db664a 100644--- a/jarvis/ui/web/frontend/scripts/check-realtime-worklet.mjs+++ b/jarvis/ui/web/frontend/scripts/check-realtime-worklet.mjs@@ -13,7 +13,7 @@ if (worklets.length !== 1) {}const source = await readFile(new URL(worklets[0], assetsUrl), "utf8");-for (const processor of ["pcm-capture", "pcm-playback"]) {+for (const processor of ["pcm-capture", "pcm-playback", "pcm-level", "pcm-startup"]) {if (!source.includes(`registerProcessor("${processor}"`)) {throw new Error(`Compiled PCM AudioWorklet is missing ${processor}`);}diff --git a/jarvis/ui/web/frontend/src/App.detached.test.tsx b/jarvis/ui/web/frontend/src/App.detached.test.tsxindex 5418df8663..104a8fb9e0 100644--- a/jarvis/ui/web/frontend/src/App.detached.test.tsx+++ b/jarvis/ui/web/frontend/src/App.detached.test.tsx@@ -1,4 +1,4 @@-import { cleanup, render, screen } from "@testing-library/react";+import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import App from "@/App";@@ -28,6 +28,7 @@ vi.mock("@/lib/dictationTarget", () => ({vi.mock("@/components/layout/Sidebar", () => ({SIDEBAR_DEFAULT_WIDTH: 280,SIDEBAR_RAIL_WIDTH: 56,+ SIDEBAR_RAIL_AT_WIDTH: 168,// App.tsx remembers the sidebar width under this key, so the mock has to// carry it too or the shell throws before it renders anything.SIDEBAR_WIDTH_STORAGE_KEY: "jarvis.sidebar.width.v3",@@ -37,7 +38,12 @@ vi.mock("@/components/layout/PaneResizer", () => ({PaneResizer: () => <div data-testid="sidebar-resizer" />,}));vi.mock("@/components/layout/TopBar", () => ({- TopBar: () => <div data-testid="topbar" />,+ TopBar: ({ settingsNavigation }: { settingsNavigation?: { open: boolean; onToggle: () => void } }) => (+ <div data-testid="topbar">+ {settingsNavigation && <button data-testid="settings-sidebar-toggle" onClick={settingsNavigation.onToggle}+ aria-expanded={settingsNavigation.open}>Toggle navigation</button>}+ </div>+ ),}));vi.mock("@/components/layout/MainView", () => ({MainView: () => <div data-testid="main-view" />,@@ -54,6 +60,10 @@ vi.mock("@/components/layout/VoiceWarmingBanner", () => ({vi.mock("@/components/voice/SubscriptionRealtimeTransportBroker", () => ({SubscriptionRealtimeTransportBroker: () => null,}));+vi.mock("@/components/voice/BrowserRealtimeControl", () => ({+ BrowserRealtimeControl: () => null,+ hasEmbeddedDesktopBridge: () => false,+}));vi.mock("@/components/ToastLayer", () => ({ ToastLayer: () => null }));vi.mock("@/components/EditContextMenu", () => ({ EditContextMenu: () => null }));vi.mock("@/components/JarvisDock", () => ({ JarvisDock: () => null }));@@ -81,6 +91,27 @@ afterEach(() => {});describe("App shell around detached coding views", () => {+ it("hides the main sidebar on each Settings visit and lets it be reopened", () => {+ render(<App />);+ expect(screen.getByTestId("sidebar")).toBeTruthy();++ act(() => useEventStore.setState({ activeSection: "profile" }));+ expect(screen.queryByTestId("sidebar")).toBeNull();+ expect(screen.queryByTestId("sidebar-resizer")).toBeNull();+ const toggle = screen.getByTestId("settings-sidebar-toggle");+ expect(toggle.getAttribute("aria-expanded")).toBe("false");++ fireEvent.click(toggle);+ expect(screen.getByTestId("sidebar")).toBeTruthy();+ expect(toggle.getAttribute("aria-expanded")).toBe("true");+ act(() => useEventStore.setState({ activeSection: "apikeys" }));+ expect(screen.getByTestId("sidebar")).toBeTruthy();++ act(() => useEventStore.setState({ activeSection: "tasks" }));+ act(() => useEventStore.setState({ activeSection: "profile" }));+ expect(screen.queryByTestId("sidebar")).toBeNull();+ });+it("renders the desktop wallpaper behind normal app sections", () => {render(<App />);@@ -147,7 +178,7 @@ describe("App shell around detached coding views", () => {).toBe(true);});- it("keeps a detached solo window chrome-free", () => {+ it("keeps a detached solo window free of the app navigation", () => {useEventStore.setState({activeSection: "agentic-ide",solo: true,@@ -157,7 +188,8 @@ describe("App shell around detached coding views", () => {render(<App />);expect(screen.queryByTestId("sidebar")).toBeNull();- expect(screen.queryByTestId("topbar")).toBeNull();+ // The caption stays: it is that window's title bar.+ expect(screen.getByTestId("topbar")).toBeTruthy();expect(screen.getByTestId("jarvis-desktop-wallpaper")).toBeTruthy();expect(screen.getByTestId("main-view").parentElement?.classList.contains("jarvis-section-stage"),diff --git a/jarvis/ui/web/frontend/src/App.tsx b/jarvis/ui/web/frontend/src/App.tsxindex ce56420a59..54b09f4e12 100644--- a/jarvis/ui/web/frontend/src/App.tsx+++ b/jarvis/ui/web/frontend/src/App.tsx@@ -13,10 +13,12 @@ import { useSectionUrlMemory } from "@/hooks/useSectionUrlMemory";import {Sidebar,SIDEBAR_DEFAULT_WIDTH,+ SIDEBAR_RAIL_AT_WIDTH,SIDEBAR_RAIL_WIDTH,SIDEBAR_WIDTH_STORAGE_KEY,} from "@/components/layout/Sidebar";import { PaneResizer } from "@/components/layout/PaneResizer";+import { SETTINGS_HUB_IDS } from "@/components/layout/navGroups";import { useResizablePane } from "@/hooks/useResizablePane";import { TopBar } from "@/components/layout/TopBar";import { PermissionsAlertBanner } from "@/components/layout/PermissionsAlertBanner";@@ -276,9 +278,39 @@ export default function App() {const activeSection = useEventStore((s) => s.activeSection);const agentsNavOpen = useSocietyShell((s) => s.navigationOpen);const toggleAgentsNav = useSocietyShell((s) => s.toggleNavigation);- const hideNavigation = activeSection === "agents" && !agentsNavOpen;+ const settingsHubActive = SETTINGS_HUB_IDS.includes(activeSection);+ const [settingsSidebarOpen, setSettingsSidebarOpen] = useState(false);+ // Each visit to the Settings hub starts with its own navigation as the only+ // left column. Switching tabs inside the hub preserves a deliberate reveal.+ useEffect(() => {+ if (!settingsHubActive) setSettingsSidebarOpen(false);+ }, [settingsHubActive]);+ const hideNavigation =+ (activeSection === "agents" && !agentsNavOpen) ||+ (settingsHubActive && !settingsSidebarOpen);const solo = useEventStore((s) => s.solo);const detachedViews = useEventStore((s) => s.detachedViews);+ /*+ * The caption's leading navigation (sidebar toggle beside back/forward).+ *+ * The toggle moved here from the sidebar header, so the stranded handlers+ * move with it: the agents section folds its own navigation, every other+ * section folds the main column. The settings hub brings its own toggle+ * (TopBar maps it onto the same button), so it needs nothing here. The+ * collapsed flag mirrors the rail the sidebar itself reports — a dragged+ * narrow column reads as collapsed even before the toggle was touched.+ */+ const navToggle = settingsHubActive+ ? undefined+ : activeSection === "agents"+ ? {+ collapsed: !agentsNavOpen || sidebar.size < SIDEBAR_RAIL_AT_WIDTH,+ onToggle: toggleAgentsNav,+ }+ : {+ collapsed: navCollapsed || sidebar.size < SIDEBAR_RAIL_AT_WIDTH,+ onToggle: toggleNav,+ };/** The realtime broker must exist exactly ONCE across all windows: it@@ -299,23 +331,30 @@ export default function App() {/** A detached solo window is one section in its own desktop window: the- * section IS the window, so the app chrome around it — nav, top bar,- * onboarding, dock — has no job here and is omitted rather than hidden.+ * section IS the window, so the app chrome around it — nav, onboarding,+ * dock — has no job here and is omitted rather than hidden. The caption+ * strip stays: it is the title bar of that window.* What stays is what any surface needs to function: toasts (many components* report through them) and the right-click edit menu (the desktop WebView* has no native context menu, so this is the only mouse-driven paste).*/if (solo) {return (- <div className="relative isolate flex h-screen w-screen overflow-hidden bg-background text-foreground">+ <div className="jarvis-nav-surface relative isolate flex h-screen w-screen overflow-hidden text-foreground"><DesktopWallpaper />{brokerMounted && <SubscriptionRealtimeTransportBroker />}<BrowserRealtimeControl controlOnly />+ {/* The caption paints nothing: the window ground is the sidebar gray,+ and the content panel below it rounds away from that gray. */}+ <TopBar />{/* No z-index on the stage column — see the shell below. */}<main className="relative flex min-w-0 flex-1 flex-col">+ <div className="h-8 shrink-0" />+ <div className="jarvis-sheet flex min-h-0 min-w-0 flex-1 flex-col"><SectionStage visualization={visualizationActive}><MainView /></SectionStage>+ </div></main><ToastLayer /><CommandActivityLayer />@@ -330,7 +369,7 @@ export default function App() {}return (- <div className="relative isolate flex h-screen w-screen overflow-hidden bg-background text-foreground">+ <div className="jarvis-nav-surface relative isolate flex h-screen w-screen overflow-hidden text-foreground">{brokerMounted && <SubscriptionRealtimeTransportBroker />}<BrowserRealtimeControl controlOnly /><DesktopWallpaper />@@ -338,11 +377,11 @@ export default function App() {{!hideNavigation && <><Sidebarwidth={sidebar.size}- collapsed={activeSection === "agents" ? false : navCollapsed}- onToggleCollapsed={activeSection === "agents" ? toggleAgentsNav : toggleNav}+ collapsed={activeSection === "agents" || settingsHubActive ? false : navCollapsed}/><PaneResizer+ showLine={false}orientation="vertical"onPointerDown={startSidebarResize}onDoubleClick={sidebar.reset}@@ -369,6 +408,10 @@ export default function App() {components/layout/overlay-stacking.test.ts.*/}<main className="relative flex min-w-0 flex-1 flex-col">+ {/* Gray, like the sidebar. The content panel below rounds its+ top-left corner so this gray shows in the curve. */}+ <div className="h-8 shrink-0" data-testid="caption-rule" />+ <div className={activeSection === "agents" || settingsHubActive ? "flex min-h-0 min-w-0 flex-1 flex-col" : "jarvis-sheet flex min-h-0 min-w-0 flex-1 flex-col"}>{/* App-wide macOS permission alert — topmost so a missing grant isimpossible to miss on any view. No-op on other platforms. */}<PermissionsAlertBanner />@@ -377,7 +420,10 @@ export default function App() {it is the same class of problem: an OS-level gate the user must betold about, since nothing else reports it. */}<InputIsolationBanner />- <TopBar />+ <TopBar navToggle={navToggle} settingsNavigation={settingsHubActive ? {+ open: settingsSidebarOpen,+ onToggle: () => setSettingsSidebarOpen((open) => !open),+ } : undefined} /><VoiceWarmingBanner />{/* The one-time "all lights green" note — the first time everysection of the active voice mode answers. Never again after. */}@@ -385,6 +431,7 @@ export default function App() {<SectionStage visualization={visualizationActive}><MainView /></SectionStage>+ </div></main><ToastLayer />diff --git a/jarvis/ui/web/frontend/src/__tests__/topbarUpdateButton.test.tsx b/jarvis/ui/web/frontend/src/__tests__/topbarUpdateButton.test.tsxindex 493a54205e..894fdb04be 100644--- a/jarvis/ui/web/frontend/src/__tests__/topbarUpdateButton.test.tsx+++ b/jarvis/ui/web/frontend/src/__tests__/topbarUpdateButton.test.tsx@@ -62,7 +62,7 @@ describe("TopBar update button", () => {});render(<TopBar />);// The restart button always renders; the update button must not.- await waitFor(() => expect(screen.getByText("Restart")).toBeTruthy());+ await waitFor(() => expect(screen.getByRole("button", { name: "Restart" })).toBeTruthy());expect(screen.queryByText("Update available")).toBeNull();});@@ -76,7 +76,7 @@ describe("TopBar update button", () => {published_at: null,});render(<TopBar />);- await waitFor(() => expect(screen.getByText("Restart")).toBeTruthy());+ await waitFor(() => expect(screen.getByRole("button", { name: "Restart" })).toBeTruthy());expect(screen.queryByText("Update available")).toBeNull();});diff --git a/jarvis/ui/web/frontend/src/assets/gigi-companion-avatar.png b/jarvis/ui/web/frontend/src/assets/gigi-companion-avatar.pngnew file mode 100644index 0000000000..5dd2e446c7Binary files /dev/null and b/jarvis/ui/web/frontend/src/assets/gigi-companion-avatar.png differdiff --git a/jarvis/ui/web/frontend/src/assets/gigi-companion-mark.svg b/jarvis/ui/web/frontend/src/assets/gigi-companion-mark.svgnew file mode 100644index 0000000000..32227f96d1--- /dev/null+++ b/jarvis/ui/web/frontend/src/assets/gigi-companion-mark.svg@@ -0,0 +1,23 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128" role="img" aria-label="Gigi companion mark proposal">+ <g stroke="#ffc83d" stroke-width="2.5" stroke-linejoin="round">+ <ellipse cx="22" cy="58" rx="8" ry="13" fill="#292c32"/>+ <ellipse cx="106" cy="58" rx="8" ry="13" fill="#292c32"/>+ <path d="M25 51C25 0 103 0 103 51V108L90 117L77 106L64 117L51 106L38 117L25 108Z" fill="#20242b"/>+ </g>+ <path d="M29 53C29 7 99 7 99 53V68H29Z" fill="#0d1118"/>+ <path d="M27 72H101" stroke="#c49938" stroke-width="1.5"/>+ <g fill="#ffcf45">+ <ellipse cx="48" cy="53" rx="9" ry="13"/>+ <ellipse cx="80" cy="53" rx="9" ry="13"/>+ <rect x="17" y="51" width="3" height="14" rx="1.5"/>+ <rect x="108" y="51" width="3" height="14" rx="1.5"/>+ <path d="M24 79Q13 92 20 100Q25 100 27 86Z"/>+ <path d="M104 79Q115 92 108 100Q103 100 101 86Z"/>+ </g>+ <g fill="#070a10">+ <ellipse cx="49" cy="56" rx="4" ry="8"/>+ <ellipse cx="81" cy="56" rx="4" ry="8"/>+ </g>+ <g fill="#fff7dd"><circle cx="51" cy="46" r="2.3"/><circle cx="83" cy="46" r="2.3"/></g>+ <ellipse cx="64" cy="84" rx="4" ry="6" fill="none" stroke="#ffcf45" stroke-width="2"/>+</svg>diff --git a/jarvis/ui/web/frontend/src/assets/society/companions/companions.glb b/jarvis/ui/web/frontend/src/assets/society/companions/companions.glbnew file mode 100644index 0000000000..2cbd01136eBinary files /dev/null and b/jarvis/ui/web/frontend/src/assets/society/companions/companions.glb differdiff --git a/jarvis/ui/web/frontend/src/assets/society/companions/gigi.glb b/jarvis/ui/web/frontend/src/assets/society/companions/gigi.glbnew file mode 100644index 0000000000..ae096d4ce1Binary files /dev/null and b/jarvis/ui/web/frontend/src/assets/society/companions/gigi.glb differdiff --git a/jarvis/ui/web/frontend/src/components/ApiKeyForm.tsx b/jarvis/ui/web/frontend/src/components/ApiKeyForm.tsxindex 8eb5b43a4f..c38566553b 100644--- a/jarvis/ui/web/frontend/src/components/ApiKeyForm.tsx+++ b/jarvis/ui/web/frontend/src/components/ApiKeyForm.tsx@@ -40,6 +40,8 @@ interface ApiKeyFormProps {* already answered.*/coveredNote?: string | null;+ /** A shared family slot may be the primary credential, not a dedicated override. */+ coveredEditLabel?: string;/*** Labels of the OTHER provider surfaces that read this same slot at* runtime. Non-empty ⇒ deleting asks for confirmation, because the delete@@ -86,7 +88,7 @@ function announceSecretChange(secretKey: string, action: "set" | "delete") {* existing value. Writes directly to POST /api/secrets/{key}; the value* never leaves the frontend again after submit (read-only flag in the backend).*/-export function ApiKeyForm({ secretKey, dashboardUrl, configured, credentialHelp, effectiveConfigured, coveredNote, sharedWith, testAfterSave, onChanged, onSavedActivate }: ApiKeyFormProps) {+export function ApiKeyForm({ secretKey, dashboardUrl, configured, credentialHelp, effectiveConfigured, coveredNote, coveredEditLabel, sharedWith, testAfterSave, onChanged, onSavedActivate }: ApiKeyFormProps) {const t = useT();const [value, setValue] = useState("");const [pending, setPending] = useState(false);@@ -344,7 +346,7 @@ export function ApiKeyForm({ secretKey, dashboardUrl, configured, credentialHelp{coveredNote || t("apikeys_view.shared_key_covered")}</p><Button size="sm" variant="ghost" onClick={() => setEditing(true)}>- {t("apikeys_view.add_dedicated_key")}+ {coveredEditLabel || t("apikeys_view.add_dedicated_key")}</Button>{dashboardLink}</div>diff --git a/jarvis/ui/web/frontend/src/components/ToastLayer.tsx b/jarvis/ui/web/frontend/src/components/ToastLayer.tsxindex 9dcd9b9671..29a4e7ed14 100644--- a/jarvis/ui/web/frontend/src/components/ToastLayer.tsx+++ b/jarvis/ui/web/frontend/src/components/ToastLayer.tsx@@ -44,10 +44,9 @@ export function ToastLayer() {// z-[60]: the onboarding gate overlays the whole app at z-50 and renders// later in the DOM; toasts (e.g. failed permission requests during// first-run setup) must stay visible above it.- // top-14: below the TopBar (h-10 + margin) — at top-4 a toast covered the- // very Update/Restart buttons whose outcome it reports, so an "Update- // failed" toast hid the half-rounded update pill behind it.- <div className="pointer-events-none fixed right-4 top-14 z-[60] flex w-[320px] flex-col gap-2">+ // top-12: below the caption strip — at the top edge a toast covered the+ // restart and window buttons whose outcome it reports.+ <div className="pointer-events-none fixed right-4 top-12 z-[60] flex w-[320px] flex-col gap-2">{toasts.map((toast) => {const Icon = ICON_FOR_KIND[toast.kind];// A saved-file toast in the desktop shell is a native drag handle: pressdiff --git a/jarvis/ui/web/frontend/src/components/agentchat/toolIdentity.test.tsx b/jarvis/ui/web/frontend/src/components/agentchat/toolIdentity.test.tsxindex 6bb951d138..57cc2031e6 100644--- a/jarvis/ui/web/frontend/src/components/agentchat/toolIdentity.test.tsx+++ b/jarvis/ui/web/frontend/src/components/agentchat/toolIdentity.test.tsx@@ -102,6 +102,22 @@ describe("tool visual identities", () => {},);+ it("uses the Artifacts section mark for the artifact pin", async () => {+ const artifact = toolIdentity(+ row({+ id: "tool:create_artifact",+ label: "Artifact / Artefakt",+ brand: "artifact",+ group: "Artifact",+ category: "system",+ }),+ );+ expect(artifact.key).toBe("artifact");+ expect(artifact.logo).toBeUndefined();+ const { Shapes } = await import("lucide-react");+ expect(artifact.Glyph).toBe(Shapes);+ });+it("uses distinct glyphs for unbranded documents and memory", () => {const pdf = toolIdentity(row({ id: "skill:pdf", label: "PDF", brand: "", group: "skills", category: "skills" }),diff --git a/jarvis/ui/web/frontend/src/components/agentchat/toolIdentity.ts b/jarvis/ui/web/frontend/src/components/agentchat/toolIdentity.tsindex a06d0a51f3..db0c658cd3 100644--- a/jarvis/ui/web/frontend/src/components/agentchat/toolIdentity.ts+++ b/jarvis/ui/web/frontend/src/components/agentchat/toolIdentity.ts@@ -19,6 +19,7 @@ import {Plug,Presentation,Search,+ Shapes,ShieldCheck,Sparkles,Terminal,@@ -193,6 +194,7 @@ const CATEGORY_PALETTES: Record<ToolCategory, Palette> = {};const DETAIL_ICONS = [+ [/\b(artifact|artefakt|artefact)\b/, Shapes],[/\b(wiki|recall|knowledge)\b/, BookOpen],[/\b(pdf|document|docs|word|read)\b/, FileText],[/\b(slides|presentation|powerpoint)\b/, Presentation],@@ -213,7 +215,29 @@ const DETAIL_ICONS = [[/\b(navigate)\b/, Compass],] as const;+/** The Artifacts section mark — shared by the section and the Add-menu pin. */+export const ARTIFACT_GLYPH = Shapes;+const ARTIFACT_PALETTE: Palette = VIOLET;++function isArtifactRow(row: ToolChoice): boolean {+ const hay = `${row.id} ${row.brand} ${row.group} ${row.label}`.toLowerCase();+ return (+ row.id === "tool:create_artifact" ||+ row.brand.toLowerCase() === "artifact" ||+ /\bartefakt|\bartifact|\bartefact/.test(hay)+ );+}+export function toolIdentity(row: ToolChoice) {+ if (isArtifactRow(row)) {+ return {+ key: "artifact",+ logo: undefined,+ mark: "colour" as const,+ palette: ARTIFACT_PALETTE,+ Glyph: ARTIFACT_GLYPH,+ };+ }const cliName = [row.brand, row.label, row.id.replace(/^(cli:|tool:|plugin:)/, "")].map((value) => cliVendor(value || "")).find(Boolean);diff --git a/jarvis/ui/web/frontend/src/components/home/RecentChats.test.tsx b/jarvis/ui/web/frontend/src/components/home/RecentChats.test.tsxindex b91cf001c9..5b300de0af 100644--- a/jarvis/ui/web/frontend/src/components/home/RecentChats.test.tsx+++ b/jarvis/ui/web/frontend/src/components/home/RecentChats.test.tsx@@ -167,11 +167,9 @@ describe("RecentChats", () => {});describe("compact chat labels", () => {- it("leaves a short title readable and bounds long prompt-like titles", () => {+ it("keeps the whole title so a wider sidebar can show more of it", () => {expect(compactChatTitle("Review agent routines")).toBe("Review agent routines");- const compact = compactChatTitle("Verify the GitHub marketplace plugin with one read-only request and report the results");- expect(Array.from(compact).length).toBeLessThanOrEqual(43);- expect(compact.endsWith("…")).toBe(true);- expect(compact.split(" ").length).toBeLessThanOrEqual(6);+ const title = "Verify the GitHub marketplace plugin with one read-only request and report the results";+ expect(compactChatTitle(` ${title} `)).toBe(title);});});diff --git a/jarvis/ui/web/frontend/src/components/home/RecentChats.tsx b/jarvis/ui/web/frontend/src/components/home/RecentChats.tsxindex d47a038833..1eeb244706 100644--- a/jarvis/ui/web/frontend/src/components/home/RecentChats.tsx+++ b/jarvis/ui/web/frontend/src/components/home/RecentChats.tsx@@ -130,18 +130,9 @@ function Count({ n }: { n: number }) {);}-/** Keep the full title for hover and accessibility; only shorten the visible label. */+/** One line of the title. The row truncates it to the sidebar's real width. */export function compactChatTitle(title: string): string {- const normalized = title.trim().replace(/\s+/g, " ");- const words = normalized.split(" ");- const candidate = words.slice(0, 6).join(" ");- const characters = Array.from(candidate);- if (characters.length <= 42 && words.length <= 6) return normalized;- let short = characters.slice(0, 42).join("");- if (characters.length > 42 && short.lastIndexOf(" ") >= 20) {- short = short.slice(0, short.lastIndexOf(" "));- }- return `${short.trimEnd()}…`;+ return title.trim().replace(/\s+/g, " ");}function ChatRowItem({diff --git a/jarvis/ui/web/frontend/src/components/layout/PaneResizer.tsx b/jarvis/ui/web/frontend/src/components/layout/PaneResizer.tsxindex 890d7d6f3f..6e4bfe4bc1 100644--- a/jarvis/ui/web/frontend/src/components/layout/PaneResizer.tsx+++ b/jarvis/ui/web/frontend/src/components/layout/PaneResizer.tsx@@ -56,6 +56,8 @@ export interface PaneResizerProps {className?: string;/** Overrides the default test id, for screens that render several seams. */testId?: string;+ /** False when a neighbouring edge already draws the line, as a rounded sheet does. */+ showLine?: boolean;}/** How far one arrow-key press moves the seam. */@@ -86,6 +88,7 @@ export const PaneResizer = forwardRef<HTMLDivElement, PaneResizerProps>(functionstyle,className,testId,+ showLine = true,},ref,) {@@ -141,6 +144,7 @@ export const PaneResizer = forwardRef<HTMLDivElement, PaneResizerProps>(function// Rim → strong rim → fill. Three named steps rather than three// opacities: a seam has to read on the page's own ground in both// themes, and an alpha of the ink lands differently in each.+ !showLine && "hidden",active? "bg-primary": "bg-border group-hover:bg-border-strong group-focus-visible:bg-border-strong",@@ -152,6 +156,7 @@ export const PaneResizer = forwardRef<HTMLDivElement, PaneResizerProps>(functionaria-hiddenclassName={cn("pointer-events-none absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 rounded-full transition-colors",+ !showLine && "hidden",vertical ? "h-8 w-[3px]" : "h-[3px] w-8",active? "bg-primary"diff --git a/jarvis/ui/web/frontend/src/components/layout/SectionNavButtons.test.tsx b/jarvis/ui/web/frontend/src/components/layout/SectionNavButtons.test.tsxnew file mode 100644index 0000000000..108733cc62--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/layout/SectionNavButtons.test.tsx@@ -0,0 +1,114 @@+import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { SectionNavButtons } from "./SectionNavButtons";+import { resetSectionHistory } from "@/hooks/useSectionHistory";+import { useEventStore } from "@/store/events";++function backButton(): HTMLButtonElement {+ return screen.getByTestId("section-nav-back") as HTMLButtonElement;+}++function forwardButton(): HTMLButtonElement {+ return screen.getByTestId("section-nav-forward") as HTMLButtonElement;+}++beforeEach(() => {+ resetSectionHistory();+ useEventStore.setState({ activeSection: "chats", solo: false });+});++afterEach(() => cleanup());++describe("SectionNavButtons", () => {+ it("renders back and forward with no sidebar toggle unless one is offered", () => {+ render(<SectionNavButtons />);++ expect(screen.getByTestId("section-nav-buttons")).toBeTruthy();+ expect(backButton()).toBeTruthy();+ expect(forwardButton()).toBeTruthy();+ expect(screen.queryByTestId("section-nav-sidebar")).toBeNull();+ });++ it("starts with both directions disabled and honest tooltips", () => {+ render(<SectionNavButtons />);++ expect(backButton().disabled).toBe(true);+ expect(forwardButton().disabled).toBe(true);+ // WHAT the tooltip says is the locale's business; that each button names+ // itself is not — a forward button that cannot explain itself (including+ // while disabled) teaches nothing.+ for (const button of [backButton(), forwardButton()]) {+ expect(button.getAttribute("aria-label")).toBeTruthy();+ expect(button.getAttribute("title")).toBe(button.getAttribute("aria-label"));+ }+ });++ it("walks back to the last visited section on every section", () => {+ render(<SectionNavButtons />);++ // The history is section-driven, not view-driven: whatever put the voice+ // section on screen (sidebar, voice command, deck jump) lands here too.+ act(() => useEventStore.getState().setActiveSection("agents"));+ act(() => useEventStore.getState().setActiveSection("dictation"));++ expect(backButton().disabled).toBe(false);+ fireEvent.click(backButton());+ expect(useEventStore.getState().activeSection).toBe("agents");+ });++ it("enables forward only after going back, and only for visited sections", () => {+ render(<SectionNavButtons />);++ act(() => useEventStore.getState().setActiveSection("agents"));+ act(() => useEventStore.getState().setActiveSection("dictation"));++ expect(forwardButton().disabled).toBe(true);++ fireEvent.click(backButton());+ expect(forwardButton().disabled).toBe(false);++ fireEvent.click(forwardButton());+ expect(useEventStore.getState().activeSection).toBe("dictation");+ expect(forwardButton().disabled).toBe(true);+ });++ it("offers the sidebar toggle with its state and hands the click to the shell", () => {+ const onToggle = vi.fn();+ const { rerender } = render(+ <SectionNavButtons sidebarToggle={{ collapsed: false, onToggle }} />,+ );++ const toggle = screen.getByTestId("section-nav-sidebar");+ expect(toggle.getAttribute("aria-expanded")).toBe("true");+ expect(toggle.getAttribute("aria-label")).toBeTruthy();+ fireEvent.click(toggle);+ expect(onToggle).toHaveBeenCalledTimes(1);++ rerender(+ <SectionNavButtons sidebarToggle={{ collapsed: true, onToggle }} />,+ );+ expect(+ screen.getByTestId("section-nav-sidebar").getAttribute("aria-expanded"),+ ).toBe("false");+ });++ it("keeps a caller-provided test id for the sidebar toggle", () => {+ render(+ <SectionNavButtons+ sidebarToggle={{ collapsed: true, onToggle: () => {}, testId: "settings-sidebar-toggle" }}+ />,+ );++ expect(screen.getByTestId("settings-sidebar-toggle")).toBeTruthy();+ });++ it("stays out of a detached solo window", () => {+ useEventStore.setState({ solo: true });+ render(<SectionNavButtons />);++ // A solo window is pinned to its one view: back/forward would walk an+ // audience of one, and there is no sidebar to toggle.+ expect(screen.queryByTestId("section-nav-buttons")).toBeNull();+ });+});diff --git a/jarvis/ui/web/frontend/src/components/layout/SectionNavButtons.tsx b/jarvis/ui/web/frontend/src/components/layout/SectionNavButtons.tsxnew file mode 100644index 0000000000..cd50abda1d--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/layout/SectionNavButtons.tsx@@ -0,0 +1,100 @@+import { ArrowLeft, ArrowRight, PanelLeftClose, PanelLeftOpen } from "lucide-react";++import { useT } from "@/i18n";+import { useEventStore } from "@/store/events";+import { useSectionHistory } from "@/hooks/useSectionHistory";++/** The sidebar toggle the caption owns — state lives in the shell (App.tsx). */+export interface SidebarToggleState {+ collapsed: boolean;+ onToggle: () => void;+ /** Test id for the button. Defaults to `section-nav-sidebar`. */+ testId?: string;+}++/**+ * One shape for every caption control in this group.+ *+ * Theme tokens only, so the buttons read in light and dark mode alike. A+ * disabled direction goes quiet (no hover lift, low opacity) but keeps its+ * tooltip — a forward button that cannot explain itself teaches nothing.+ */+const NAV_BUTTON =+ "inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-md text-muted-foreground " ++ "transition-colors hover:bg-secondary hover:text-foreground " ++ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring " ++ "disabled:cursor-default disabled:opacity-40 disabled:hover:bg-transparent disabled:hover:text-muted-foreground";++/**+ * The caption's leading navigation: sidebar toggle, back, forward.+ *+ * Rendered at the far left of the window caption (see TopBar), so it is on+ * screen for EVERY section — chat, agents, voice, settings — with no second+ * bar per view. Back/forward walk the visited-section history+ * (`useSectionHistory`): back returns to the previously visited section, and+ * forward only re-applies an undone step, staying disabled until one exists.+ * A detached solo window is pinned to one view, so the group stays out of it.+ */+export function SectionNavButtons({+ sidebarToggle,+}: {+ sidebarToggle?: SidebarToggleState;+} = {}) {+ const t = useT();+ const solo = useEventStore((s) => s.solo);+ const { canGoBack, canGoForward, goBack, goForward } = useSectionHistory();++ if (solo) return null;++ const backLabel = t("topbar.nav_back");+ const forwardLabel = t("topbar.nav_forward");++ return (+ <div+ className="flex shrink-0 items-center"+ data-testid="section-nav-buttons"+ role="group"+ aria-label={t("sidebar.sections")}+ >+ {sidebarToggle && (+ <button+ type="button"+ data-testid={sidebarToggle.testId ?? "section-nav-sidebar"}+ onClick={sidebarToggle.onToggle}+ aria-expanded={!sidebarToggle.collapsed}+ aria-label={t(sidebarToggle.collapsed ? "sidebar.expand" : "sidebar.collapse")}+ title={t(sidebarToggle.collapsed ? "sidebar.expand" : "sidebar.collapse")}+ className={NAV_BUTTON}+ >+ {sidebarToggle.collapsed ? (+ <PanelLeftOpen className="h-4 w-4" aria-hidden />+ ) : (+ <PanelLeftClose className="h-4 w-4" aria-hidden />+ )}+ </button>+ )}+ <button+ type="button"+ data-testid="section-nav-back"+ onClick={() => goBack()}+ disabled={!canGoBack}+ aria-label={backLabel}+ title={backLabel}+ className={NAV_BUTTON}+ >+ <ArrowLeft className="h-4 w-4" aria-hidden />+ </button>+ <button+ type="button"+ data-testid="section-nav-forward"+ onClick={() => goForward()}+ disabled={!canGoForward}+ aria-label={forwardLabel}+ title={forwardLabel}+ className={NAV_BUTTON}+ >+ <ArrowRight className="h-4 w-4" aria-hidden />+ </button>+ </div>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/layout/Sidebar.test.tsx b/jarvis/ui/web/frontend/src/components/layout/Sidebar.test.tsxindex 08f0dd4b76..05800ec41e 100644--- a/jarvis/ui/web/frontend/src/components/layout/Sidebar.test.tsx+++ b/jarvis/ui/web/frontend/src/components/layout/Sidebar.test.tsx@@ -538,21 +538,22 @@ describe("Sidebar icon rail", () => {});/**- * The explicit collapse toggle.+ * The collapse state (the toggle itself moved to the window caption).*- * The rail used to be reachable only by dragging the seam far enough — a- * gesture nobody discovers, on a seam one pixel wide. The button says the same- * thing out loud, and it is what the app opens in (see `App.tsx`); the drag- * stays as the second, finer way in.+ * The sidebar header no longer carries its own button — it lives in the+ * caption's leading navigation (SectionNavButtons, owned by TopBar), beside+ * back/forward, so the controls sit in the empty caption corner on every+ * section. The collapsed STATE still belongs to the sidebar: the rail wins+ * while it holds, and the drag stays as the finer way in.*/-describe("Sidebar collapse toggle", () => {+describe("Sidebar collapse state", () => {beforeEach(() => {useEventStore.setState({ activeSection: "chats", connected: true });});afterEach(() => cleanup());- function renderWithToggle(collapsed: boolean, onToggle = () => {}) {+ function renderCollapsed(collapsed: boolean) {const client = new QueryClient({defaultOptions: { queries: { retry: false }, mutations: { retry: false } },});@@ -561,14 +562,13 @@ describe("Sidebar collapse toggle", () => {<Sidebarwidth={SIDEBAR_DEFAULT_WIDTH}collapsed={collapsed}- onToggleCollapsed={onToggle}/></QueryClientProvider>,);}test("collapses to the rail even at a wide dragged width", () => {- renderWithToggle(true);+ renderCollapsed(true);const aside = screen.getByTestId("sidebar");// The collapse is a STATE, not a width: the dragged 280 px is remembered@@ -577,13 +577,9 @@ describe("Sidebar collapse toggle", () => {expect(aside.style.width).toBe(`${SIDEBAR_RAIL_WIDTH}px`);});- test("reports its state and names itself in both directions", () => {- const { rerender } = renderWithToggle(true);-- const collapsedButton = screen.getByTestId("sidebar-collapse-toggle");- expect(collapsedButton.getAttribute("aria-expanded")).toBe("false");- // WHAT it says is the locale's business; that it says something is not.- expect(collapsedButton.getAttribute("aria-label")).toBeTruthy();+ test("expands to the dragged width once the state lifts", () => {+ const { rerender } = renderCollapsed(true);+ expect(screen.getByTestId("sidebar").dataset.railed).toBe("true");const client = new QueryClient({defaultOptions: { queries: { retry: false }, mutations: { retry: false } },@@ -593,35 +589,21 @@ describe("Sidebar collapse toggle", () => {<Sidebarwidth={SIDEBAR_DEFAULT_WIDTH}collapsed={false}- onToggleCollapsed={() => {}}/></QueryClientProvider>,);- expect(- screen.getByTestId("sidebar-collapse-toggle").getAttribute("aria-expanded"),- ).toBe("true");- });-- test("asks the shell to toggle rather than deciding for itself", () => {- // The width and the collapsed flag live together in the shell — a sidebar- // that flipped its own state would drift from the seam beside it.- const onToggle = vi.fn();- renderWithToggle(true, onToggle);-- act(() => {- screen.getByTestId("sidebar-collapse-toggle").click();- });-- expect(onToggle).toHaveBeenCalledTimes(1);+ expect(screen.getByTestId("sidebar").dataset.railed).toBe("false");});- test("is simply absent when the shell offers no toggle", () => {- // Standalone renders (tests, any future embedding) must not grow a button- // that cannot do anything.- renderSidebar(SIDEBAR_DEFAULT_WIDTH);+ test("carries no toggle of its own — the caption owns it", () => {+ // The header button moved to the caption's leading navigation+ // (SectionNavButtons): a sidebar that flipped its own state would drift+ // from the shell that owns the width beside it.+ renderCollapsed(false);expect(screen.queryByTestId("sidebar-collapse-toggle")).toBeNull();+ expect(screen.getByTestId("sidebar")).toBeTruthy();});});diff --git a/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx b/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsxindex 7c221a0884..5df6fec658 100644--- a/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx+++ b/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx@@ -6,8 +6,6 @@ import {MoreHorizontal,Store,UserCircle2,- PanelLeftClose,- PanelLeftOpen,Plus,} from "lucide-react";import {@@ -112,8 +110,6 @@ export interface SidebarProps {* the window is for. Left optional so the sidebar still renders standalone.*/collapsed?: boolean;- /** Toggle `collapsed`. Absent = the toggle button is not offered. */- onToggleCollapsed?: () => void;}/** Width the sidebar was designed at, and the one a double-click restores.@@ -168,7 +164,6 @@ export const SIDEBAR_RAIL_AT_WIDTH = 168;export function Sidebar({width = SIDEBAR_DEFAULT_WIDTH,collapsed = false,- onToggleCollapsed,}: SidebarProps = {}) {const t = useT();const active = useEventStore((s) => s.activeSection);@@ -270,7 +265,7 @@ export function Sidebar({// every unconfigured section would light up and the bar would never be calm.const { health: sectionHealth } = useSectionHealth();const apikeysHasError = useMemo(- () => Object.values(sectionHealth).some((h) => h?.status === "error"),+ () => Object.entries(sectionHealth).some(([section, health]) => section !== "computer-use" && health?.status === "error"),[sectionHealth],);// The footer card IS the button that opens API Keys, so its dot carries that@@ -380,7 +375,7 @@ export function Sidebar({style={{ width: railed ? SIDEBAR_RAIL_WIDTH : width }}data-testid="sidebar"data-railed={railed ? "true" : "false"}- className="jarvis-nav-surface relative isolate z-20 flex h-full shrink-0 flex-col"+ className="jarvis-nav-surface relative isolate z-20 flex h-full shrink-0 flex-col pt-8">{/* One 8px gutter down the whole column — header, navigation and footershare it, so the rows, the "+ New" button and the brain card all line@@ -465,32 +460,6 @@ export function Sidebar({aria-hidden/>))}- {onToggleCollapsed && (- <button- type="button"- data-testid="sidebar-collapse-toggle"- onClick={onToggleCollapsed}- aria-expanded={!railed}- title={railed ? t("sidebar.expand") : t("sidebar.collapse")}- aria-label={railed ? t("sidebar.expand") : t("sidebar.collapse")}- className={cn(- "flex shrink-0 items-center justify-center rounded-md text-muted-foreground",- // Hover goes UP the surface ladder. It used to be- // `hover:bg-background/20`, which composites the PAGE colour- // over the rail — on near-black that is darker than rest, so- // the control dimmed under the pointer.- "transition-colors hover:bg-secondary hover:text-foreground",- "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",- railed ? "h-7 w-7" : "-mr-1 h-7 w-7",- )}- >- {railed ? (- <PanelLeftOpen className="h-4 w-4" aria-hidden />- ) : (- <PanelLeftClose className="h-4 w-4" aria-hidden />- )}- </button>- )}</div></div>diff --git a/jarvis/ui/web/frontend/src/components/layout/TopBar.test.tsx b/jarvis/ui/web/frontend/src/components/layout/TopBar.test.tsxindex d76a28f7c6..11b856cbfa 100644--- a/jarvis/ui/web/frontend/src/components/layout/TopBar.test.tsx+++ b/jarvis/ui/web/frontend/src/components/layout/TopBar.test.tsx@@ -1,7 +1,9 @@import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { TopBar, TopBarActions } from "./TopBar";+import { ThemeProvider } from "@/hooks/useTheme";import { useEventStore } from "@/store/events";+import { resetSectionHistory } from "@/hooks/useSectionHistory";vi.mock("@/hooks/useUpdate", () => ({useUpdate: () => ({ status: { managed: false, update_available: false } }),@@ -10,11 +12,8 @@ vi.mock("@/components/MascotGigi", () => ({MascotGigi: () => <div data-testid="mascot-gigi" />,}));-// The bar is section-aware now, so every test below states which screen it is-// on rather than inheriting whatever a previous one left behind. The front-// page ("chats") renders no bar of its own — its header carries the actions-// (see the front-page describe below); a detachable section that keeps the-// bar stands in for the general case.+// The caption is on every screen. Tests still name the section so a later+// change cannot quietly hide Restart on one of them.beforeEach(() => {useEventStore.setState({activeSection: "dictation",@@ -25,6 +24,18 @@ beforeEach(() => {afterEach(() => vi.restoreAllMocks());describe("TopBar detach button", () => {+ it("offers the Settings navigation toggle with its current state", () => {+ useEventStore.setState({ activeSection: "profile" });+ const onToggle = vi.fn();+ const { rerender } = render(<TopBar settingsNavigation={{ open: false, onToggle }} />);+ const toggle = screen.getByTestId("settings-sidebar-toggle");+ expect(toggle.getAttribute("aria-expanded")).toBe("false");+ fireEvent.click(toggle);+ expect(onToggle).toHaveBeenCalledOnce();+ rerender(<TopBar settingsNavigation={{ open: true, onToggle }} />);+ expect(toggle.getAttribute("aria-expanded")).toBe("true");+ });+it("offers 'own window' on the detachable sections only", () => {render(<TopBar />);expect(screen.getByTestId("detach-view-button")).toBeTruthy();@@ -141,70 +152,78 @@ describe("TopBar restart button", () => {});});-/*- * The one screen that renders these actions itself.- *- * The Agentic IDE is a wall of terminal output with a single header row, and a- * second full-width strip above it holding two buttons was the third horizontal- * band in a row. So the bar steps aside there — but the ACTIONS must not, and- * that is the half worth pinning: a frontend change only reaches the user- * through that Restart button, so a refactor that quietly drops it from the IDE- * would leave the section with no way to pick up its own rebuild.- */-describe("TopBar on the front page", () => {- it("renders no bar of its own there — the home header carries the actions", () => {- useEventStore.setState({ activeSection: "chats" });- const { container } = render(<TopBar />);- expect(container.firstChild).toBeNull();+describe("TopBar section navigation", () => {+ beforeEach(() => {+ resetSectionHistory();+ useEventStore.setState({ activeSection: "chats", solo: false });});- it("restores the global bar in the main window while chats is detached", () => {- useEventStore.setState({ activeSection: "chats", detachedViews: ["chats"] });- const { container } = render(<TopBar />);- expect(container.firstChild).not.toBeNull();- expect(screen.getByRole("button", { name: /^restart$/i })).toBeTruthy();+ it.each(["chats", "agents", "dictation", "visualization", "profile"] as const)(+ "shows back/forward in the caption on %s",+ (section) => {+ useEventStore.setState({ activeSection: section });+ render(<TopBar />);+ expect(screen.getByTestId("section-nav-buttons")).toBeTruthy();+ expect(screen.getByTestId("section-nav-back")).toBeTruthy();+ expect(screen.getByTestId("section-nav-forward")).toBeTruthy();+ cleanup();+ },+ );++ it("offers the sidebar toggle from the caption and hands the click to the shell", () => {+ const onToggle = vi.fn();+ render(<TopBar navToggle={{ collapsed: false, onToggle }} />);++ const toggle = screen.getByTestId("section-nav-sidebar");+ expect(toggle.getAttribute("aria-expanded")).toBe("true");+ fireEvent.click(toggle);+ expect(onToggle).toHaveBeenCalledOnce();});- it("renders no bar on agents — the society header carries the actions", () => {- useEventStore.setState({ activeSection: "agents" });- const { container } = render(<TopBar />);- expect(container.firstChild).toBeNull();+ it("stays out of a detached solo window", () => {+ useEventStore.setState({ solo: true });+ render(<TopBar />);+ expect(screen.queryByTestId("section-nav-buttons")).toBeNull();});});-describe("TopBar in the classic terminal grid", () => {- it("renders no bar of its own there", () => {- useEventStore.setState({ activeSection: "agentic-ide-classic" });-- const { container } = render(<TopBar />);-- expect(container.firstChild).toBeNull();- });-- it("still offers the restart through the actions the IDE carries", () => {- useEventStore.setState({ activeSection: "agentic-ide-classic" });-- render(<TopBarActions />);-- expect(screen.getByRole("button", { name: /^restart$/i })).toBeTruthy();- });-- it("restores the global bar in the main window while the IDE is detached", () => {- useEventStore.setState({- activeSection: "agentic-ide-classic",- detachedViews: ["agentic-ide"],- });-- const { container } = render(<TopBar />);-- expect(container.firstChild).not.toBeNull();- expect(screen.getByRole("button", { name: /^restart$/i })).toBeTruthy();- });-- it("keeps its bar on every other screen", () => {- const { container } = render(<TopBar />);-- expect(container.firstChild).not.toBeNull();- expect(screen.getByRole("button", { name: /^restart$/i })).toBeTruthy();+describe("TopBar caption on every section", () => {+ it.each(["chats", "agents", "agentic-ide-classic", "dictation"] as const)(+ "keeps restart on %s",+ (section) => {+ useEventStore.setState({ activeSection: section });+ render(<TopBar />);+ const caption = screen.getByTestId("window-caption");+ expect(caption.className).not.toContain("jarvis-shell-surface");+ expect(caption).toBeTruthy();+ expect(screen.getByRole("button", { name: /^restart$/i })).toBeTruthy();+ expect(screen.queryByTestId("window-close")).toBeNull();+ },+ );++ it("places theme and restart immediately before the window buttons", async () => {+ (window as unknown as { pywebview?: { api: object } }).pywebview = { api: {} };+ vi.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue({+ ok: true,+ json: async () => ({ ok: true, frameless: true, controls: "trailing", platform: "windows" }),+ }),+ );++ render(+ <ThemeProvider>+ <TopBar />+ </ThemeProvider>,+ );++ const minimize = await screen.findByTestId("window-minimize");+ const restart = screen.getByRole("button", { name: /^restart$/i });+ const theme = screen.getByTestId("theme-toggle");+ expect(theme.compareDocumentPosition(restart) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();+ expect(restart.compareDocumentPosition(minimize) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();+ expect(minimize.compareDocumentPosition(screen.getByTestId("window-close")) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();++ delete (window as unknown as { pywebview?: unknown }).pywebview;});});diff --git a/jarvis/ui/web/frontend/src/components/layout/TopBar.tsx b/jarvis/ui/web/frontend/src/components/layout/TopBar.tsxindex 3475ea0e31..82dcca4bb4 100644--- a/jarvis/ui/web/frontend/src/components/layout/TopBar.tsx+++ b/jarvis/ui/web/frontend/src/components/layout/TopBar.tsx@@ -2,7 +2,6 @@ import { useCallback, useEffect, useRef, useState } from "react";import { AppWindow, Download, RotateCw } from "lucide-react";import { useEventStore, type SectionId } from "@/store/events";-import { NAV_FOOTER_ITEMS, NAV_GROUPS, resolveNavLabel } from "@/components/layout/navGroups";import {fetchUpdateProgress,useUpdate,@@ -12,41 +11,29 @@ import { clsx } from "clsx";import { fill, useT } from "@/i18n";import { cn } from "@/lib/utils";import { CodingModeBadge } from "@/components/layout/CodingModeBadge";+import { SectionNavButtons } from "@/components/layout/SectionNavButtons";import { ThemeToggle } from "@/components/layout/ThemeToggle";+import { useDesktopChrome, WindowControls } from "@/components/layout/WindowControls";import { hasEmbeddedDesktopBridge } from "@/components/voice/BrowserRealtimeControl";import { openExternalUrl } from "@/lib/openExternal";/**- * Global top bar rendered above every view (see App.tsx). It carries the app-- * chrome actions that must be reachable from *every* screen: a "Restart Jarvis"- * button, and — only when a newer version is published — an "Update" button that- * pulls the new code and restarts, so an end user never touches a terminal.+ * The window's title strip, on every screen.*- * Why a global bar and not the per-view ``ViewHeader``: a couple of views- * (DocsView's 3-column layout, SubAgentsView's departure board) don't render a- * ViewHeader at all, and ~13 views already fill the header's ``right`` slot with- * their own actions. Putting the buttons in the shell, above MainView, is the- * only placement that is on every screen and collides with nothing.+ * It is one thin row at the top of the window: drag the empty part to move+ * the window, and the right end holds the app buttons (theme, restart, and+ * an update when one exists) immediately beside minimize, maximize and close.+ * Sections do not grow a second bar for those buttons.*- * The backend already ships the whole self-restart machinery: both buttons POST- * to the existing ``/api/settings/restart-app`` endpoint, which spawns a- * detached, cross-platform relauncher (see jarvis/ui/relauncher.py). On a- * headless host that endpoint returns 503 and we recover with an honest toast.+ * The backend already ships the self-restart machinery: restart and update+ * POST to ``/api/settings/restart-app``, which spawns a detached relauncher+ * (see jarvis/ui/relauncher.py). On a headless host that endpoint returns 503+ * and we recover with an honest toast.*- * A restart tears down the whole app mid-task, so both buttons honor the mission- * guard (409 → arm a force override) rather than killing live missions silently.- * We avoid a native ``window.confirm`` on purpose — it blocks the pywebview loop.- *- * **Two surfaces render the bar themselves.** The Agentic IDE is a wall of- * terminal output with a single header row of its own, and a second full-width- * bar above it holding two buttons cost that view ~40 px it had better uses- * for. The mission deck has the same shape: its HUD is already a header, and- * an empty chrome strip above it was a second, boring row. Both take- * `TopBarActions` into their own row and this bar steps aside there — the- * actions are still on that screen, which is the rule that matters; what- * moved is the furniture around them. The agents section follows the same- * rule with its own unified header (`SocietyView`). Every other view keeps- * the bar.+ * A restart tears down the whole app mid-task, so both buttons honor the+ * mission guard (409 → arm a force override) rather than killing live missions+ * silently. We avoid a native ``window.confirm`` on purpose — it blocks the+ * pywebview loop.*/const CONFIRM_TIMEOUT_MS = 4000;@@ -68,7 +55,7 @@ const CONFIRM_TIMEOUT_MS = 4000;* change.)*/const CHROME_BUTTON =- "inline-flex h-8 shrink-0 items-center gap-2 rounded-md px-3 text-base font-medium " ++ "inline-flex h-8 shrink-0 items-center gap-2 rounded-md text-base font-medium " +"transition-[background-color,color,transform] duration-150 " +"motion-safe:active:scale-[0.98] focus-visible:outline-none focus-visible:ring-2 " +"focus-visible:ring-ring disabled:cursor-default disabled:opacity-70";@@ -83,76 +70,57 @@ const CHROME_QUIET = "text-muted-foreground hover:bg-secondary hover:text-foregr*/const CHROME_ARMED = "bg-warning text-background";-const CODING_SECTIONS = new Set<SectionId>([- "agentic-ide",- "agentic-ide-classic",- "chat-workspace",-]);--/** The active section's own nav label — the bar's breadcrumb-style title. */-function useViewTitle(activeSection: SectionId): string {- const t = useT();- const item = [...NAV_GROUPS.flat(), ...NAV_FOOTER_ITEMS].find((row) =>- row.matchIds ? row.matchIds.includes(activeSection) : row.id === activeSection,- );- return item ? resolveNavLabel(t, item) : "";-}--export function TopBar() {- const activeSection = useEventStore((s) => s.activeSection);- const solo = useEventStore((s) => s.solo);- const detachedViews = useEventStore((s) => s.detachedViews);- const viewTitle = useViewTitle(activeSection);- // The coding workspace takes the actions into its own toolbar row, under- // every id that reaches it. The rule is "the section carries the actions- // itself" — a section that does not would lose Restart, which is the one- // control a frontend change is reached through. Once detached, that toolbar- // lives in the solo window and the main window only has a placeholder, so- // the main shell must provide the global bar again.- const codingDetached =- !solo && detachedViews.some((view) => CODING_SECTIONS.has(view));- if (CODING_SECTIONS.has(activeSection) && !codingDetached) {- return null;- }-- /*- * The front page already has a header. A second empty strip above it was- * the boring row. Same rule as the IDE: this bar steps aside, the actions- * move into that header (`HomeView`). While chats is detached the main- * window is a placeholder and needs the bar back.+export function TopBar({ settingsNavigation, navToggle }: {+ settingsNavigation?: { open: boolean; onToggle: () => void };+ /**+ * The sidebar toggle the caption owns. State lives in the shell (App.tsx):+ * the sidebar header no longer carries its own button — it moved here, next+ * to back/forward, so the leading controls sit in the empty caption corner+ * on every section.*/- const chatsDetached = !solo && detachedViews.includes("chats");- if (activeSection === "chats" && !chatsDetached) {- return null;- }-+ navToggle?: { collapsed: boolean; onToggle: () => void };+} = {}) {+ const chrome = useDesktopChrome();+ const controls = chrome.frameless ? chrome.controls : "none";/*- * The agents section carries a single unified header of its own- * (`SocietyView`): the section toggle, the Map/Agents switch and these- * actions in one row. A global bar above it would be a second, boring row.- * Agents cannot detach, so no placeholder case applies here.+ * The settings hub's own navigation toggle and the caption sidebar toggle+ * are the same control: one panel button at the leading edge, not two+ * adjacent ones doing the same job. It keeps its test id so the hub's+ * contract ("the caption reopens the navigation") stays observable.*/- if (activeSection === "agents") {- return null;- }+ const sidebarToggle = settingsNavigation+ ? {+ collapsed: !settingsNavigation.open,+ onToggle: settingsNavigation.onToggle,+ testId: "settings-sidebar-toggle",+ }+ : navToggle;return (- // 48 px on the page ground with a hairline beneath. Left: the view's- // name, and the coding-mode badge only while the mode is ON. Right: the- // app-chrome actions.- <div className="jarvis-shell-surface flex h-12 shrink-0 items-center gap-2 border-b border-border px-4">- <div className="mr-auto flex min-w-0 items-center gap-3">- {viewTitle && (- <span- data-testid="topbar-view-title"- className="truncate text-base font-medium text-foreground"- >- {viewTitle}- </span>- )}+ // One title strip for the whole window. The empty middle is the drag+ // handle (pywebview only starts a drag on this class, not on a child+ // button — so the buttons sit beside it, never inside it).+ <div+ data-testid="window-caption"+ className="fixed inset-x-0 top-0 z-[120] flex h-8 items-stretch bg-transparent"+ >+ {controls === "leading" && (+ <WindowControls controls={controls} maximized={chrome.maximized} onCommand={chrome.command} />+ )}+ <SectionNavButtons sidebarToggle={sidebarToggle} />+ <div+ className="pywebview-drag-region min-w-0 flex-1"+ onDoubleClick={() => {+ if (chrome.frameless) chrome.command("maximize");+ }}+ />+ <div className="flex shrink-0 items-center"><CodingModeBadge />+ <TopBarActions />+ {controls === "trailing" && (+ <WindowControls controls={controls} maximized={chrome.maximized} onCommand={chrome.command} />+ )}</div>- <TopBarActions /></div>);}@@ -254,10 +222,10 @@ function DetachButton() {disabled={busy}title={t("topbar.detach_hint")}data-testid="detach-view-button"- className={clsx(CHROME_BUTTON, CHROME_QUIET)}+ aria-label={t("topbar.detach")}+ className={clsx(CHROME_BUTTON, "w-8 justify-center px-0", CHROME_QUIET)}><AppWindow aria-hidden className="h-4 w-4" />- {t("topbar.detach")}</button>);}@@ -355,14 +323,18 @@ function RestartButton() {? t("topbar.restart_confirm"): t("topbar.restart");+ const showLabel = confirming || forceArmed || restarting;+return (<buttontype="button"onClick={onClick}disabled={restarting}title={t("topbar.restart_hint")}+ aria-label={label}className={clsx(CHROME_BUTTON,+ showLabel ? "px-3" : "w-8 justify-center px-0",confirming || forceArmed ? CHROME_ARMED : CHROME_QUIET,)}>@@ -370,7 +342,7 @@ function RestartButton() {aria-hiddenclassName={cn("h-4 w-4", restarting && "animate-spin")}/>- {label}+ {showLabel ? label : null}</button>);}@@ -650,7 +622,7 @@ function UpdateButton() {aria-valuenow={busy ? percent : undefined}className={clsx(CHROME_BUTTON,- "relative overflow-hidden",+ "relative overflow-hidden px-3",// The one offer in the bar, so it is the one thing here with a fill// of its own: an object on the chrome, answering the pointer one// step up. It used to be accent-tinted TEXT on an accent-tinteddiff --git a/jarvis/ui/web/frontend/src/components/layout/WindowControls.tsx b/jarvis/ui/web/frontend/src/components/layout/WindowControls.tsxnew file mode 100644index 0000000000..4548a9cc4d--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/layout/WindowControls.tsx@@ -0,0 +1,118 @@+import { useCallback, useEffect, useState } from "react";+import { Copy, Minus, Square, X } from "lucide-react";++import { hasEmbeddedDesktopBridge } from "@/components/voice/BrowserRealtimeControl";+import { useT } from "@/i18n";+import { cn } from "@/lib/utils";+import { useEventStore } from "@/store/events";++export interface DesktopChrome {+ frameless: boolean;+ controls: "leading" | "trailing" | "none";+ maximized: boolean;+}++const IDLE: DesktopChrome = { frameless: false, controls: "none", maximized: false };++/**+ * The desktop window's own buttons, drawn by the page once the native title+ * bar is gone. A browser tab has none of these — the operating system already+ * provides them, and a fake set would close nothing.+ */+export function useDesktopChrome(): DesktopChrome & {+ command: (action: "minimize" | "maximize" | "close") => void;+} {+ const [chrome, setChrome] = useState<DesktopChrome>(IDLE);++ useEffect(() => {+ if (!hasEmbeddedDesktopBridge()) return;+ let live = true;+ fetch("/api/window/chrome")+ .then((res) => (res.ok ? res.json() : null))+ .then((body: { frameless?: boolean; controls?: string } | null) => {+ if (!live || !body) return;+ const controls = body.controls === "leading" || body.controls === "trailing" ? body.controls : "none";+ setChrome({ frameless: Boolean(body.frameless), controls, maximized: false });+ })+ .catch((error: unknown) => {+ console.warn("Window chrome is unavailable", error);+ });+ return () => {+ live = false;+ };+ }, []);++ const command = useCallback((action: "minimize" | "maximize" | "close") => {+ const solo = useEventStore.getState().solo;+ const view = solo ? useEventStore.getState().activeSection : null;+ void fetch("/api/window/command", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ action, view }),+ })+ .then((res) => (res.ok ? res.json() : null))+ .then((body: { maximized?: boolean } | null) => {+ if (!body || typeof body.maximized !== "boolean") return;+ setChrome((current) => ({ ...current, maximized: body.maximized as boolean }));+ })+ .catch((error: unknown) => {+ console.warn("Window command failed", error);+ });+ }, []);++ return { ...chrome, command };+}++const CAPTION_BUTTON =+ "inline-flex h-8 w-10 shrink-0 items-center justify-center text-muted-foreground " ++ "transition-colors hover:bg-secondary hover:text-foreground " ++ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring";++/** Minimize, maximize and close. Render nothing unless this window owns them. */+export function WindowControls({+ controls,+ maximized,+ onCommand,+}: {+ controls: DesktopChrome["controls"];+ maximized: boolean;+ onCommand: (action: "minimize" | "maximize" | "close") => void;+}) {+ const t = useT();+ if (controls === "none") return null;+ const MaxIcon = maximized ? Copy : Square;+ return (+ <div className="flex shrink-0 items-stretch" data-testid="window-controls" data-side={controls}>+ <button+ type="button"+ data-testid="window-minimize"+ title={t("topbar.minimize")}+ aria-label={t("topbar.minimize")}+ onClick={() => onCommand("minimize")}+ className={CAPTION_BUTTON}+ >+ <Minus aria-hidden className="h-4 w-4" />+ </button>+ <button+ type="button"+ data-testid="window-maximize"+ title={t(maximized ? "topbar.restore" : "topbar.maximize")}+ aria-label={t(maximized ? "topbar.restore" : "topbar.maximize")}+ onClick={() => onCommand("maximize")}+ className={CAPTION_BUTTON}+ >+ <MaxIcon aria-hidden className="h-3.5 w-3.5" />+ </button>+ <button+ type="button"+ data-testid="window-close"+ title={t("topbar.close")}+ aria-label={t("topbar.close")}+ onClick={() => onCommand("close")}+ className={cn(CAPTION_BUTTON, "hover:bg-destructive hover:text-destructive-foreground")}+ >+ <X aria-hidden className="h-4 w-4" />+ </button>+ </div>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/onboarding/OnboardingGate.tsx b/jarvis/ui/web/frontend/src/components/onboarding/OnboardingGate.tsxindex 0a3801343e..14c79b139f 100644--- a/jarvis/ui/web/frontend/src/components/onboarding/OnboardingGate.tsx+++ b/jarvis/ui/web/frontend/src/components/onboarding/OnboardingGate.tsx@@ -60,7 +60,7 @@ export function OnboardingGate() {<divrole="dialog"aria-modal="true"- className="fixed inset-0 z-50 bg-background text-foreground"+ className="fixed inset-x-0 bottom-0 top-8 z-50 bg-background text-foreground">{/* Fallback is empty: the stage ground is already painted while thefirst-run chunk fetches. */}diff --git a/jarvis/ui/web/frontend/src/components/providers/LiveProfile.test.tsx b/jarvis/ui/web/frontend/src/components/providers/LiveProfile.test.tsxindex 3ad263d63a..f9570d4210 100644--- a/jarvis/ui/web/frontend/src/components/providers/LiveProfile.test.tsx+++ b/jarvis/ui/web/frontend/src/components/providers/LiveProfile.test.tsx@@ -1,10 +1,10 @@-import { render, screen, fireEvent, waitFor } from "@testing-library/react";+import { cleanup, render, screen, fireEvent, waitFor } from "@testing-library/react";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { afterEach, expect, it, vi } from "vitest";import { LiveProfile } from "./LiveProfile";vi.mock("@/i18n", () => ({ useT: () => (key: string) => key }));-afterEach(() => vi.unstubAllGlobals());+afterEach(() => { cleanup(); vi.unstubAllGlobals(); });it("requires an explicit thinking model and sends one coherent selection", async () => {const requests: { path: string; body: unknown }[] = [];@@ -44,16 +44,17 @@ it("requires an explicit thinking model and sends one coherent selection", asyncconst client = new QueryClient({defaultOptions: { queries: { retry: false } },});+ client.setQueryData(["unrelated-background-work"], { ready: true });+ const onSaved = vi.fn();render(<QueryClientProvider client={client}>- <LiveProfile />+ <LiveProfile onSaved={onSaved} /></QueryClientProvider>,);const button = await screen.findByRole("button", { name: "live.save" });expect((button as HTMLButtonElement).disabled).toBe(true);- fireEvent.change(screen.getByLabelText("live.thinking_model"), {- target: { value: "chosen-model" },- });+ fireEvent.click(screen.getByRole("combobox", { name: "live.thinking_model" }));+ fireEvent.click(await screen.findByRole("option", { name: /Chosen/ }));fireEvent.click(button);await waitFor(() => expect(requests).toHaveLength(1));expect(requests[0]).toMatchObject({@@ -66,5 +67,32 @@ it("requires an explicit thinking model and sends one coherent selection", asyncweb_search: true,},});+ await waitFor(() => expect(onSaved).toHaveBeenCalledOnce());+ expect(client.getQueryState(["unrelated-background-work"])?.isInvalidated).toBe(false);+ client.clear();+});++it("recognizes a newly connected key without losing the user's model choice", async () => {+ let keyReady = false;+ const fetcher = vi.fn(async (path: string) => ({+ ok: true,+ json: async () => path.endsWith("options") ? {+ models: [{ id: "chosen-model", label: "Chosen" }], voices: ["gleam"], efforts: ["medium"],+ } : {+ key_ready: keyReady, active: false, agent_configured: true,+ profile: { model: "gpt-live-1", voice: "gleam", backend_model: "", reasoning_effort: "medium", web_search: true, instructions: "", backend_instructions: "", configured: false },+ },+ }));+ vi.stubGlobal("fetch", fetcher);+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ render(<QueryClientProvider client={client}><LiveProfile /></QueryClientProvider>);+ const button = await screen.findByRole("button", { name: "live.save" });+ fireEvent.click(screen.getByRole("combobox", { name: "live.thinking_model" }));+ fireEvent.click(await screen.findByRole("option", { name: /Chosen/ }));+ expect((button as HTMLButtonElement).disabled).toBe(true);+ keyReady = true;+ fireEvent(window, new CustomEvent("jarvis:secret-configured"));+ await waitFor(() => expect((button as HTMLButtonElement).disabled).toBe(false));+ expect(screen.getByRole("combobox", { name: "live.thinking_model" }).textContent).toContain("Chosen");client.clear();});diff --git a/jarvis/ui/web/frontend/src/components/providers/LiveProfile.tsx b/jarvis/ui/web/frontend/src/components/providers/LiveProfile.tsxindex 1c8b87646a..3b75cb6f83 100644--- a/jarvis/ui/web/frontend/src/components/providers/LiveProfile.tsx+++ b/jarvis/ui/web/frontend/src/components/providers/LiveProfile.tsx@@ -1,7 +1,10 @@-import { useState } from "react";+import { useEffect, useState } from "react";import { useQuery, useQueryClient } from "@tanstack/react-query";+import { Brain, Check, Loader2, Waves } from "lucide-react";import { useT } from "@/i18n";import { Button } from "@/components/ui/button";+import { BrandedSelect } from "@/components/ui/select";+import { Switch } from "@/components/ui/switch";export interface LiveProfileValue {model: string;@@ -14,46 +17,90 @@ export interface LiveProfileValue {configured: boolean;}-async function read<T>(url: string): Promise<T> {- const response = await fetch(url, { cache: "no-store" });+async function read<T>(url: string, signal: AbortSignal): Promise<T> {+ const response = await fetch(url, { cache: "no-store", signal });if (!response.ok) throw new Error(`GPT-Live: HTTP ${response.status}`);return response.json() as Promise<T>;}-export function LiveProfile() {+export function LiveProfile({ onSaved }: { onSaved?: () => void } = {}) {const t = useT();const queryClient = useQueryClient();const profile = useQuery({queryKey: ["live-profile"],- queryFn: () =>+ queryFn: ({ signal }) =>read<{profile: LiveProfileValue;key_ready: boolean;active: boolean;agent_configured: boolean;- }>("/api/live/profile"),+ }>("/api/live/profile", signal),});const options = useQuery({queryKey: ["live-options"],- queryFn: () =>+ queryFn: ({ signal }) =>read<{models: { id: string; label: string }[];voices: string[];efforts: string[];- }>("/api/live/options"),+ }>("/api/live/options", signal),staleTime: 300_000,});const [draft, setDraft] = useState<LiveProfileValue | null>(null);const [saving, setSaving] = useState(false);const [message, setMessage] = useState("");+ const [error, setError] = useState("");+ useEffect(() => {+ const credentialsChanged = () => {+ void queryClient.invalidateQueries({ queryKey: ["live-profile"] });+ };+ window.addEventListener("jarvis:secret-configured", credentialsChanged);+ return () => window.removeEventListener("jarvis:secret-configured", credentialsChanged);+ }, [queryClient]);const value = draft ?? profile.data?.profile;if (!value)- return <p role="status">{profile.error?.message ?? t("live.loading")}</p>;- const update = (patch: Partial<LiveProfileValue>) =>+ return (+ <p role="status" className="py-4 text-sm text-muted-foreground">+ {profile.error?.message ?? t("live.loading")}+ </p>+ );+ const update = (patch: Partial<LiveProfileValue>) => {setDraft({ ...value, ...patch });- const save = async () => {+ setMessage("");+ setError("");+ };+ const saved = profile.data?.profile;+ const dirty = saved && JSON.stringify(value) !== JSON.stringify(saved);+ const ready = Boolean(profile.data?.active && saved?.configured);+ const models = options.data?.models ?? [];+ const modelOptions = models.map((model) => ({+ value: model.id,+ label: model.label,+ hint: model.label === model.id ? undefined : model.id,+ }));+ if (+ value.backend_model &&+ !modelOptions.some((model) => model.value === value.backend_model)+ ) {+ modelOptions.unshift({+ value: value.backend_model,+ label: value.backend_model,+ hint: "",+ });+ }+ async function refresh() {+ // A settings save must not re-fetch every background query in the app.+ await Promise.all([+ queryClient.invalidateQueries({ queryKey: ["live-profile"] }),+ queryClient.invalidateQueries({ queryKey: ["voice-mode"] }),+ ]);+ window.dispatchEvent(new CustomEvent("jarvis:realtime-switched"));+ onSaved?.();+ }+ async function save() {setSaving(true);setMessage("");+ setError("");try {const response = await fetch("/api/live/profile", {method: "PUT",@@ -64,151 +111,201 @@ export function LiveProfile() {throw new Error((await response.json()).detail ?? `HTTP ${response.status}`,);+ await refresh();setDraft(null);- await queryClient.invalidateQueries();setMessage(t("live.saved"));- } catch (error) {- setMessage(String(error));+ } catch (cause) {+ setError(cause instanceof Error ? cause.message : String(cause));} finally {setSaving(false);}- };- const useForAgents = async () => {+ }+ async function useForAgents() {setSaving(true);+ setError("");try {const response = await fetch("/api/live/use-key-for-agent", {method: "POST",});if (!response.ok) throw new Error((await response.json()).detail);- await queryClient.invalidateQueries();+ window.dispatchEvent(new CustomEvent("jarvis:subagent-switched"));+ await refresh();setMessage(t("live.agent_saved"));- } catch (error) {- setMessage(String(error));+ } catch (cause) {+ setError(cause instanceof Error ? cause.message : String(cause));} finally {setSaving(false);}- };+ }const field =- "mt-1 w-full rounded-md border border-border bg-background px-3 py-2 text-foreground";+ "w-full rounded-md border border-border bg-background px-3 py-2 text-sm text-foreground";return (- <section- className="my-4 space-y-4 rounded-xl border border-border p-5"- aria-label="GPT-Live"- >- <div>- <h3 className="font-semibold">GPT-Live</h3>- <p className="mt-1 text-sm text-muted-foreground">- {t("live.description")}- </p>- </div>+ <section aria-label="GPT-Live" className="space-y-5 py-2">{!profile.data?.key_ready && (- <p className="text-sm text-warning">{t("live.key_required")}</p>+ <p role="status" className="text-sm text-warning">+ {t("live.key_required")}+ </p>)}- <div className="grid gap-4 md:grid-cols-2">- <label className="text-sm">- {t("live.voice_model")}- <input className={field} value={value.model} readOnly />- </label>- <label className="text-sm">- {t("live.voice")}- <select- className={field}- value={value.voice}- onChange={(e) => update({ voice: e.target.value })}- >- {(options.data?.voices ?? [value.voice]).map((v) => (- <option key={v} value={v}>- {v}- </option>- ))}- </select>- </label>- <label className="text-sm">- {t("live.thinking_model")}- <input- aria-label={t("live.thinking_model")}- className={field}- list="live-thinking-models"- value={value.backend_model}- placeholder={t("live.choose_model")}- onChange={(e) => update({ backend_model: e.target.value })}- />- <datalist id="live-thinking-models">- {options.data?.models.map((m) => (- <option key={m.id} value={m.id}>- {m.label}- </option>- ))}- </datalist>- </label>- <label className="text-sm">- {t("live.reasoning")}- <select- className={field}- value={value.reasoning_effort}- onChange={(e) => update({ reasoning_effort: e.target.value })}- >- {(options.data?.efforts ?? ["", value.reasoning_effort]).map(- (e) => (- <option key={e} value={e}>- {e || t("live.model_default")}- </option>- ),- )}- </select>- </label>+ <div className="grid gap-6 md:grid-cols-2">+ <div className="space-y-4">+ <div className="flex items-center gap-2 text-sm font-medium">+ <Waves className="h-4 w-4 text-muted-foreground" />+ {t("live.conversation_heading")}+ </div>+ <p className="text-xs leading-relaxed text-muted-foreground">+ {t("live.conversation_help")}+ </p>+ <div className="flex items-center justify-between rounded-lg bg-secondary/50 px-3 py-2.5 text-sm">+ <span className="text-muted-foreground">+ {t("live.voice_model")}+ </span>+ <span className="font-medium">GPT-Live 1</span>+ </div>+ <label className="block space-y-2 text-sm">+ <span>{t("live.voice")}</span>+ <BrandedSelect+ className={field}+ value={value.voice}+ onValueChange={(voice) => update({ voice })}+ ariaLabel={t("live.voice")}+ options={(options.data?.voices ?? [value.voice]).map((voice) => ({+ value: voice,+ label: voice.charAt(0).toUpperCase() + voice.slice(1),+ }))}+ />+ </label>+ </div>+ <div className="space-y-4 md:border-l md:border-border md:pl-6">+ <div className="flex items-center gap-2 text-sm font-medium">+ <Brain className="h-4 w-4 text-muted-foreground" />+ {t("live.thinking_heading")}+ </div>+ <p className="text-xs leading-relaxed text-muted-foreground">+ {t("live.thinking_help")}+ </p>+ <label className="block space-y-2 text-sm">+ <span>{t("live.thinking_model")}</span>+ <BrandedSelect+ className={field}+ value={value.backend_model}+ onValueChange={(backend_model) => update({ backend_model })}+ ariaLabel={t("live.thinking_model")}+ placeholder={t("live.choose_model")}+ searchPlaceholder={t("live.search_models")}+ options={modelOptions}+ />+ </label>+ <label className="block space-y-2 text-sm">+ <span>{t("live.reasoning")}</span>+ <BrandedSelect+ className={field}+ value={value.reasoning_effort}+ onValueChange={(reasoning_effort) => update({ reasoning_effort })}+ ariaLabel={t("live.reasoning")}+ options={(+ options.data?.efforts ?? ["", value.reasoning_effort]+ ).map((effort) => ({+ value: effort,+ label: effort ? effort.charAt(0).toUpperCase() + effort.slice(1) : t("live.model_default"),+ }))}+ />+ </label>+ </div></div>- <label className="flex items-center gap-2 text-sm">- <input- type="checkbox"+ <div className="flex items-center justify-between gap-4 border-t border-border pt-4">+ <div>+ <label htmlFor="live-web-search" className="text-sm font-medium">+ {t("live.web_search")}+ </label>+ <p className="mt-1 text-xs text-muted-foreground">+ {t("live.web_search_help")}+ </p>+ </div>+ <Switch+ id="live-web-search"checked={value.web_search}- onChange={(e) => update({ web_search: e.target.checked })}+ onCheckedChange={(web_search) => update({ web_search })}+ aria-label={t("live.web_search")}/>- {t("live.web_search")}- </label>- <details>- <summary className="cursor-pointer text-sm">+ </div>+ <details className="border-t border-border pt-4">+ <summary className="cursor-pointer text-sm text-muted-foreground hover:text-foreground">{t("live.prompts")}</summary>- <label className="mt-3 block text-sm">- {t("live.conversation_prompt")}- <textarea- className={field}- value={value.instructions}- onChange={(e) => update({ instructions: e.target.value })}- />- </label>- <label className="mt-3 block text-sm">- {t("live.backend_prompt")}- <textarea- className={field}- value={value.backend_instructions}- onChange={(e) => update({ backend_instructions: e.target.value })}- />- </label>+ <div className="mt-4 grid gap-4 md:grid-cols-2">+ <label className="space-y-2 text-sm">+ <span>{t("live.conversation_prompt")}</span>+ <textarea+ className={field}+ rows={3}+ value={value.instructions}+ onChange={(event) => update({ instructions: event.target.value })}+ />+ </label>+ <label className="space-y-2 text-sm">+ <span>{t("live.backend_prompt")}</span>+ <textarea+ className={field}+ rows={3}+ value={value.backend_instructions}+ onChange={(event) =>+ update({ backend_instructions: event.target.value })+ }+ />+ </label>+ <label className="space-y-2 text-sm md:col-span-2">+ <span>{t("live.custom_model")}</span>+ <input+ className={field}+ value={value.backend_model}+ onChange={(event) =>+ update({ backend_model: event.target.value })+ }+ />+ </label>+ </div></details>- <p className="text-xs text-muted-foreground">{t("live.billing")}</p>- <div className="flex flex-wrap gap-2">+ <div className="flex flex-wrap items-center justify-between gap-3 border-t border-border pt-4">+ <p className="max-w-md text-xs leading-relaxed text-muted-foreground">+ {t("live.billing")}+ </p><Buttondisabled={- saving || !value.backend_model.trim() || !profile.data?.key_ready+ saving ||+ !value.backend_model.trim() ||+ !profile.data?.key_ready ||+ (ready && !dirty)}onClick={() => void save()}>- {t("live.save")}+ {saving ? (+ <Loader2 className="mr-2 h-4 w-4 animate-spin" />+ ) : ready && !dirty ? (+ <Check className="mr-2 h-4 w-4" />+ ) : null}+ {ready && !dirty+ ? t("live.ready")+ : ready+ ? t("live.save_changes")+ : t("live.save")}</Button>- {profile.data?.profile.configured && !profile.data.agent_configured && (- <Button- variant="outline"- disabled={saving}- onClick={() => void useForAgents()}- >- {t("live.use_for_agents")}- </Button>- )}</div>+ {saved?.configured && !profile.data?.agent_configured && (+ <Button+ variant="outline"+ disabled={saving}+ onClick={() => void useForAgents()}+ >+ {t("live.use_for_agents")}+ </Button>+ )}+ {error && (+ <p role="alert" className="text-sm text-destructive">+ {error}+ </p>+ )}{message && (- <p role="status" className="text-sm">+ <p role="status" className="text-sm text-muted-foreground">{message}</p>)}diff --git a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.test.tsx b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.test.tsxindex 1063fd46ac..101abb60d0 100644--- a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.test.tsx+++ b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.test.tsx@@ -187,6 +187,21 @@ describe("ProviderCard — dictation polish activation", () => {cleanup();});+ it("leaves continuous voice selection to its coherent profile form", async () => {+ const calls = installFetchMock();+ renderCard(dictationCard({+ id: "continuous-test",+ label: "Continuous voice",+ tier: "realtime",+ active: true,+ configuration_surface: "live",+ }));+ fireEvent.click(screen.getByText("Continuous voice"));+ await screen.findByRole("button", { name: "Test" });+ expect(screen.queryByText("Realtime model")).toBeNull();+ expect(calls.some(call => call.url.includes("/realtime/options"))).toBe(false);+ });+it("activates on a single click of the row; a double click switches once", async () => {const calls = installFetchMock();diff --git a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsxindex 358be8e44b..1368977cd5 100644--- a/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx+++ b/jarvis/ui/web/frontend/src/components/providers/ProviderTierSection.tsx@@ -1,10 +1,9 @@-import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";import { AlertCircle, Bot, Brain, Check, ChevronDown, Copy, Cpu, Download, HardDrive, Loader2, LogIn, LogOut, Mic, Play, PlugZap, Radio, Search, Sparkles, Square, Terminal, Volume2, Wand2, Waypoints, XCircle } from "lucide-react";import { AltCredentialNote } from "@/components/AltCredentialNote";import { ApiKeyForm } from "@/components/ApiKeyForm";import { BrainModelSelector } from "@/components/BrainModelSelector";import { OpenRouterTtsControls } from "@/components/OpenRouterTtsVoicePicker";-import { CuModelSelector } from "@/components/CuModelSelector";import { RealtimeOptionsControl } from "@/components/RealtimeOptionsControl";import { ProviderLogo } from "@/components/providers/ProviderLogo";import { useRowGestures } from "@/components/providers/rowGestures";@@ -337,7 +336,7 @@ export function EngineModeSwitch({"relative z-10 inline-flex h-7 items-center justify-center gap-1.5 rounded-control px-3 text-xs font-medium transition-colors","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",isSelected- ? "text-primary-foreground"+ ? "text-foreground": needsKey? "text-muted-foreground hover:text-muted-foreground": "text-muted-foreground hover:text-foreground",@@ -352,7 +351,7 @@ export function EngineModeSwitch({aria-hidden="true"className={cn("h-1.5 w-1.5 rounded-full",- isSelected ? "bg-primary-foreground/80" : "bg-foreground/70",+ isSelected ? "bg-foreground/80" : "bg-foreground/70",)}/>)}@@ -992,6 +991,7 @@ export function ProviderCard({health,expanded = true,onToggleExpanded,+ configuration,}: {descriptor: ProviderDescriptor;onChanged: () => void;@@ -1007,6 +1007,8 @@ export function ProviderCard({expanded?: boolean;/** Toggles `expanded`; absent means the row is not collapsible. */onToggleExpanded?: () => void;+ /** Provider-owned setup shares the existing credential and verification controls. */+ configuration?: ReactNode;}) {const t = useT();const [activating, setActivating] = useState(false);@@ -1084,6 +1086,8 @@ export function ProviderCard({}async function activate(assumeConfigured = false) {+ // The Live profile saves the voice provider and thinking model together.+ if (descriptor.configuration_surface === "live") return;if (descriptor.active) return;if (!isBrainSwitchable) {pushToast(@@ -1443,6 +1447,7 @@ export function ProviderCard({{t("apikeys_view.local_models_open")}</button>)}+ {descriptor.configuration_surface !== "live" && (<ActiveControldescriptor={isCodexBrain@@ -1466,6 +1471,7 @@ export function ProviderCard({}/>+ )}{collapsible && (<ChevronDownaria-hidden="true"@@ -1502,11 +1508,14 @@ export function ProviderCard({</div>)}- <AuthWidget- descriptor={descriptor}- onChanged={onChanged}- onSavedActivate={handleSavedActivate}- />+ {configuration && descriptor.configured ? (+ <details className="rounded-lg border border-border px-3 py-2.5">+ <summary className="cursor-pointer text-sm font-medium">{t("live.shared_key_ready")}</summary>+ <div className="pt-3"><AuthWidget descriptor={descriptor} onChanged={onChanged} onSavedActivate={handleSavedActivate} /></div>+ </details>+ ) : <AuthWidget descriptor={descriptor} onChanged={onChanged} onSavedActivate={handleSavedActivate} />}++ {configuration}{!isBrainSwitchable && (<p className="rounded-control bg-secondary px-3 py-2 text-xs leading-relaxed text-foreground">@@ -1560,30 +1569,12 @@ export function ProviderCard({</p>)}- {/* Phase 3: a dedicated Computer-Use model, selectable per brain provider- (defaults to the provider's main model — no automatic escalation).- Also shown under the Computer-Use tab (synthetic "computer-use"- tier, same underlying brain id) — but never the plain- BrainModelSelector above, which stays Brain-tab-only. */}- {(descriptor.tier === "brain" || descriptor.tier === "computer-use") &&- descriptor.configured &&- isBrainSwitchable && (- <CuModelSelector- providerId={descriptor.id}- recommendedModel={descriptor.recommended_model}- healthActive={- descriptor.tier === "computer-use"- ? descriptor.active- : Boolean(descriptor.computer_use_active)- }- />- )}-{/* Realtime needs BOTH a model AND a voice pinned per provider — adedicated compact control (two dropdowns), gated on the cardalready having a stored credential like the other tiers' pickersabove. */}{descriptor.tier === "realtime" &&+ descriptor.configuration_surface !== "live" &&(descriptor.configured ||// Keep the model/voice pickers mounted through a transient busy// probe so the card does not visibly flicker while saying@@ -3713,7 +3704,8 @@ export function AuthWidget({dashboardUrl={descriptor.dashboard_url}configured={Boolean(descriptor.secrets_set[k])}effectiveConfigured={Boolean(descriptor.secrets_effective?.[k])}- coveredNote={descriptor.credential_note ?? null}+ coveredNote={descriptor.configuration_surface === "live" ? t("live.shared_key_help") : descriptor.credential_note ?? null}+ coveredEditLabel={descriptor.configuration_surface === "live" ? t("live.manage_key") : undefined}sharedWith={descriptor.secret_shared_with?.[k] ?? []}credentialHelp={descriptor.credential_help}onChanged={onChanged}@@ -3737,7 +3729,8 @@ export function AuthWidget({dashboardUrl={descriptor.dashboard_url}configured={Boolean(descriptor.secrets_set[k])}effectiveConfigured={Boolean(descriptor.secrets_effective?.[k])}- coveredNote={descriptor.credential_note ?? null}+ coveredNote={descriptor.configuration_surface === "live" ? t("live.shared_key_help") : descriptor.credential_note ?? null}+ coveredEditLabel={descriptor.configuration_surface === "live" ? t("live.manage_key") : undefined}sharedWith={descriptor.secret_shared_with?.[k] ?? []}credentialHelp={descriptor.credential_help}// A pasted key is checked right away — the dictation polishdiff --git a/jarvis/ui/web/frontend/src/components/providers/VoiceProviderSettings.tsx b/jarvis/ui/web/frontend/src/components/providers/VoiceProviderSettings.tsxnew file mode 100644index 0000000000..d660ebdb76--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/providers/VoiceProviderSettings.tsx@@ -0,0 +1,169 @@+import { useState } from "react";+import { Check, Radio } from "lucide-react";+import { LiveProfile } from "./LiveProfile";+import { ProviderCard } from "./ProviderTierSection";+import { ProviderLogo } from "./ProviderLogo";+import { Button } from "@/components/ui/button";+import { useVoiceMode } from "@/hooks/useVoiceMode";+import {+ type ProviderDescriptor,+ type ProviderTier,+ type SectionHealth,+ sectionHealthForSubject,+} from "@/hooks/useProviders";+import { useT } from "@/i18n";+import { cn } from "@/lib/utils";++export function VoiceProviderSettings({+ providers,+ loading,+ error,+ onChanged,+ onActivateOptimistic,+ health,+ localMode,+ onDisableLocalMode,+}: {+ providers: ProviderDescriptor[];+ loading: boolean;+ error: string | null;+ onChanged: () => void;+ onActivateOptimistic: (tier: ProviderTier, id: string) => void;+ health?: SectionHealth;+ localMode: boolean;+ onDisableLocalMode: () => void;+}) {+ const t = useT();+ const runtime = useVoiceMode();+ const [inspectedId, setInspectedId] = useState<string | null>(null);+ const choices = providers.filter(+ (provider) =>+ provider.tier === "realtime" &&+ (!localMode || provider.billing === "local"),+ );+ const selected =+ choices.find((provider) => provider.id === inspectedId) ??+ choices.find((provider) => provider.active) ??+ choices[0];+ return (+ <section+ role="tabpanel"+ aria-label={t("live.setup_title")}+ className="space-y-5"+ >+ <div className="flex flex-wrap items-start justify-between gap-3">+ <div>+ <h2 className="text-base font-semibold tracking-tight">+ {t("live.setup_title")}+ </h2>+ <p className="mt-1 max-w-xl text-sm leading-relaxed text-muted-foreground">+ {t("live.setup_description")}+ </p>+ </div>+ <span className="inline-flex items-center gap-1.5 rounded-full border border-border px-2.5 py-1 text-xs text-muted-foreground">+ <Radio className="h-3 w-3" />+ {runtime.sessionActive ? t("live.call_active") : t("live.next_call")}+ </span>+ </div>+ {runtime.sessionActive && runtime.activeSessionMode === "pipeline" && (+ <p+ role="status"+ data-testid="voice-engine-runtime-status"+ className="rounded-lg border border-warning/30 px-3 py-2 text-sm text-warning"+ >+ {t("live.pipeline_fallback")}+ </p>+ )}+ {runtime.lastStartError && (+ <p+ role="alert"+ className="rounded-lg border border-destructive/30 px-3 py-2 text-sm text-destructive"+ >+ {runtime.lastStartError.message}+ </p>+ )}+ {loading && !choices.length && (+ <p role="status" className="text-sm text-muted-foreground">+ {t("live.loading")}+ </p>+ )}+ {error && (+ <div+ role="alert"+ className="flex items-center gap-3 text-sm text-destructive"+ >+ <span>{error}</span>+ <Button variant="outline" onClick={onChanged}>+ {t("common.retry")}+ </Button>+ </div>+ )}+ <div+ role="group"+ aria-label={t("live.provider_selection")}+ className="grid grid-cols-2 gap-2 lg:grid-cols-4"+ >+ {choices.map((provider) => (+ <button+ key={provider.id}+ type="button"+ aria-pressed={selected?.id === provider.id}+ onClick={() => setInspectedId(provider.id)}+ className={cn(+ "flex min-w-0 items-center gap-2.5 rounded-xl border p-3 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",+ selected?.id === provider.id+ ? "border-foreground/30 bg-secondary"+ : "border-border bg-card hover:bg-secondary/60",+ )}+ >+ <ProviderLogo providerId={provider.id} label={provider.label} />+ <span className="min-w-0 flex-1">+ <span className="block truncate text-sm font-medium">+ {provider.label}+ </span>+ <span className="mt-1 flex items-center gap-1 text-xs text-muted-foreground">+ {provider.active && <Check className="h-3 w-3" />}+ {provider.active+ ? t("live.active")+ : provider.billing === "local"+ ? t("live.local_provider")+ : provider.configured+ ? t("live.connected")+ : t("live.connect")}+ </span>+ </span>+ </button>+ ))}+ </div>+ {selected && (+ <div className="overflow-hidden rounded-xl border border-border bg-card">+ <ProviderCard+ key={selected.id}+ descriptor={selected}+ onChanged={onChanged}+ onActivateOptimistic={onActivateOptimistic}+ autoActivateOnSave={false}+ health={+ selected.active+ ? sectionHealthForSubject(health, selected.id)+ : undefined+ }+ configuration={+ selected.configuration_surface === "live" ? (+ <LiveProfile onSaved={onChanged} />+ ) : undefined+ }+ />+ </div>+ )}+ {localMode && !choices.length && (+ <Button variant="outline" onClick={onDisableLocalMode}>+ {t("live.show_cloud")}+ </Button>+ )}+ <p className="text-xs leading-relaxed text-muted-foreground">+ {t("live.agents_separate")}+ </p>+ </section>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/society/AgentSwatch.test.tsx b/jarvis/ui/web/frontend/src/components/society/AgentSwatch.test.tsxnew file mode 100644index 0000000000..83741f473b--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/AgentSwatch.test.tsx@@ -0,0 +1,65 @@+import { render } from "@testing-library/react";+import { describe, expect, it } from "vitest";++import { AgentSwatch } from "./AgentSwatch";+import { symbolAppearance } from "./AgentSymbol";+import type { SocietyAgent } from "./data";++const agent: Pick<SocietyAgent, "agentId" | "tier" | "figure" | "palette" | "name"> = {+ agentId: "research-worker",+ tier: "specialist",+ name: "Research",+ figure: null,+ palette: { primary: "#111111", secondary: "#222222", accent: "#333333" },+};++describe("agent vector identities", () => {+ it("animates only a real working status, including the lead", () => {+ const { container, rerender } = render(<AgentSwatch agent={{ ...agent, state: "working" }} />);+ expect(container.querySelector("[data-thinking=true]")).not.toBeNull();+ for (const state of ["idle", "waiting", "paused"] as const) {+ rerender(<AgentSwatch agent={{ ...agent, state }} />);+ expect(container.querySelector("[data-thinking=true]")).toBeNull();+ }+ rerender(<AgentSwatch agent={{ ...agent, tier: "lead", state: "working" }} />);+ expect(container.querySelector("[data-agent-mascot=gigi]")).not.toBeNull();+ expect(container.querySelector("[data-thinking=true]")).not.toBeNull();+ });+ it("renders a symbol immediately without a portrait, image request or canvas", () => {+ const { container } = render(<AgentSwatch agent={agent} size={40} />);+ expect(container.querySelector("svg[data-agent-symbol]")).not.toBeNull();+ expect(container.querySelector("img, canvas")).toBeNull();+ expect(container.firstElementChild?.getAttribute("style")).toContain("width: 40px");+ expect(container.firstElementChild?.getAttribute("aria-hidden")).toBe("true");+ });++ it("keeps the same appearance on rename and figure edits", () => {+ const { container, rerender } = render(<AgentSwatch agent={agent} />);+ const before = container.querySelector("svg")?.outerHTML;+ rerender(<AgentSwatch agent={{ ...agent, name: "New name", figure: { contract: 1, archetype: "spirit", base: "gigi", parts: {}, palette: {} } }} />);+ expect(container.querySelector("svg")?.outerHTML).toBe(before);+ expect(container.querySelector("[data-agent-mascot]")).toBeNull();+ });++ it("draws the animated companion for the lead, even with an old figure recipe", () => {+ const { container } = render(<AgentSwatch agent={{ ...agent, tier: "lead", name: "Coordinator" }} size={56} />);+ expect(container.querySelector("[data-agent-mascot=gigi] svg")).not.toBeNull();+ expect(container.querySelector("img, canvas")).toBeNull();+ expect(container.querySelector("[data-agent-symbol]")).toBeNull();+ });++ it("supports historical name-only participants and the legacy Gigi recipe", () => {+ const { container, rerender } = render(<AgentSwatch agent={{ name: "Worker", figure: null, palette: agent.palette }} />);+ expect(container.querySelector("svg")).not.toBeNull();+ rerender(<AgentSwatch agent={{ name: "Jarvis", palette: agent.palette, figure: { contract: 1, archetype: "spirit", base: "gigi", parts: {}, palette: {} } }} />);+ expect(container.querySelector("[data-agent-mascot=gigi]")).not.toBeNull();+ });++ it("distributes a roster across multiple silhouettes and colours deterministically", () => {+ const identities = Array.from({ length: 40 }, (_, i) => `agent-${i}`);+ const first = identities.map(symbolAppearance);+ expect(identities.map(symbolAppearance)).toEqual(first);+ expect(new Set(first.map(a => a.shape)).size).toBe(7);+ expect(new Set(first.map(a => a.color)).size).toBe(8);+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/AgentSwatch.tsx b/jarvis/ui/web/frontend/src/components/society/AgentSwatch.tsxindex 1a68f69ff7..b1d3db4725 100644--- a/jarvis/ui/web/frontend/src/components/society/AgentSwatch.tsx+++ b/jarvis/ui/web/frontend/src/components/society/AgentSwatch.tsx@@ -1,110 +1,46 @@-/**- * An agent's face wherever a 3D canvas would be wasteful — roster rows, card- * headers, chips. A rendered headshot of the agent's own figure when the- * look has a built base (faceCrop.ts); until it arrives, and for a row with- * no figure, the flat stand-in below.- *- * Test revision (avatar readability): same size contract, distinct content.- * The ground pairs the figure's primary with its secondary so two agents- * never collapse to the same dark disc; the fallback draws a simple- * two-eye face from the figure's own skin/hair/eyes cells; a loaded crop- * is shown in full so the whole face stays visible inside the disc.- */-import { useEffect, useState } from "react";-+import { GigiAvatar } from "./GigiAvatar";import { cn } from "@/lib/utils";+import { AgentSymbol, SymbolThinkingDots } from "./AgentSymbol";+import { resolveCompanion } from "./companion/appearance";import type { SocietyAgent } from "./data";-import { faceCrop } from "./figures/faceCrop";-import { recipeKey, resolvePalette, type FigureRecipe } from "./figures/figureRecipe";--const crops = new Map<string, string>();-function useFaceCrop(figure: FigureRecipe | null): string | null {- const key = figure ? recipeKey(figure) : "";- const [url, setUrl] = useState<string | null>(() => (key ? (crops.get(key) ?? null) : null));- useEffect(() => {- if (!figure || !key) {- setUrl(null);- return;- }- const cached = crops.get(key);- if (cached) {- setUrl(cached);- return;- }- let live = true;- void faceCrop(figure).then((data) => {- if (!live) return;- if (data) crops.set(key, data);- setUrl(data);- });- return () => {- live = false;- };- }, [figure, key]);- return url;-}+type SwatchAgent = Pick<SocietyAgent, "figure" | "palette" | "name"> &+ Partial<Pick<SocietyAgent, "agentId" | "tier" | "state">>;+/** Lightweight vector identity shared by roster, profile and message surfaces. */export function AgentSwatch({agent,size = 36,className,}: {- agent: Pick<SocietyAgent, "figure" | "palette" | "name">;+ agent: SwatchAgent;size?: number;className?: string;}) {- const palette = resolvePalette(agent.figure);- const primary = agent.figure ? palette.primary : agent.palette.primary;- const secondary = agent.figure ? palette.secondary : agent.palette.secondary;- const accent = agent.figure ? palette.accent : agent.palette.accent;- const crop = useFaceCrop(agent.figure);- const eyeGap = Math.max(3, size * 0.11);- const eyeSize = Math.max(2.5, size * 0.085);+ // Older internal-message participants carry the figure but not the tier.+ const isJarvis = agent.tier === "lead" || (+ !agent.tier && agent.figure?.archetype === "spirit" && agent.figure.base === "gigi"+ );+ // Real roster identities survive renames. Name-only historical participants+ // still get a deterministic symbol without fetching a roster or a 3D model.+ const appearance = resolveCompanion(agent.agentId || agent.name, agent.figure?.companion);+ const thinking = agent.state === "working";+return (<spanaria-hidden- className={cn(- "relative inline-flex shrink-0 items-end justify-center overflow-hidden rounded-full border border-border",- className,- )}- style={{- width: size,- height: size,- background: `linear-gradient(170deg, ${primary} 0%, ${secondary} 135%)`,- boxShadow: `inset 0 0 0 2px ${accent}66`,- }}+ className={cn("relative inline-flex shrink-0 items-center justify-center select-none", isJarvis && "society-agent-symbol", className)}+ data-thinking={isJarvis && thinking ? "true" : undefined}+ style={{ width: size, height: size }}>- {crop ? (- <img- src={crop}- alt=""- draggable={false}- className="absolute inset-[4%] h-[92%] w-[92%] object-contain"- style={{- imageRendering: size <= 40 ? "auto" : "pixelated",- }}- />+ {isJarvis ? (+ <>+ <GigiAvatar size={size} />+ {thinking && <svg aria-hidden viewBox="0 0 40 44" className="pointer-events-none absolute inset-0 h-full w-full"><SymbolThinkingDots color="#ffcf45" /></svg>}+ </>) : (- <span- className="relative rounded-full"- style={{- width: size * 0.64,- height: size * 0.64,- marginBottom: size * 0.08,- background: palette.skin,- boxShadow: `0 ${-size * 0.16}px 0 0 ${palette.hair}, inset 0 0 0 ${Math.max(1, size * 0.03)}px rgba(0,0,0,0.08)`,- }}- >- <span- className="absolute left-1/2 top-1/2 flex -translate-x-1/2 -translate-y-1/2"- style={{ gap: eyeGap, marginTop: size * 0.04 }}- >- <span className="rounded-full" style={{ width: eyeSize, height: eyeSize * 1.25, background: palette.eyes }} />- <span className="rounded-full" style={{ width: eyeSize, height: eyeSize * 1.25, background: palette.eyes }} />- </span>- </span>+ <AgentSymbol {...appearance} size={size} thinking={thinking} />)}</span>);diff --git a/jarvis/ui/web/frontend/src/components/society/AgentSymbol.test.tsx b/jarvis/ui/web/frontend/src/components/society/AgentSymbol.test.tsxnew file mode 100644index 0000000000..fdcd6f6288--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/AgentSymbol.test.tsx@@ -0,0 +1,31 @@+import { cleanup, render } from "@testing-library/react";+import { afterEach, describe, expect, it } from "vitest";+import { AgentSymbol } from "./AgentSymbol";+import { COMPANION_SHAPES } from "./companion/appearance";++afterEach(cleanup);++describe("symbol gaze and thinking", () => {+ it.each(COMPANION_SHAPES)("keeps %s idle with plain black eyes facing the same direction", shape => {+ const { container } = render(<AgentSymbol shape={shape} color="#8b5cf6" size={48} />);+ const eyes = container.querySelector("[data-agent-eyes]")!;+ expect(eyes.getAttribute("fill")).toBe("#101014");+ expect(eyes.getAttribute("transform")).toContain("translate(2 -0.6) rotate(-14");+ expect(eyes.querySelectorAll("ellipse")).toHaveLength(2);+ expect(eyes.querySelectorAll("circle")).toHaveLength(0);+ expect(container.querySelector("[data-thinking=true]")).toBeNull();+ expect(container.querySelector(".agent-symbol-orbit")).toBeNull();+ });++ it("shows three working dots and removes them as soon as work ends", () => {+ const { container, rerender } = render(<AgentSymbol shape="cloud" color="#8b5cf6" size={48} thinking />);+ expect(container.querySelector("[data-thinking=true]")).not.toBeNull();+ expect(container.querySelector(".agent-symbol-orbit")).toBeNull();+ expect(container.querySelectorAll(".agent-symbol-thoughts circle")).toHaveLength(3);+ expect(container.querySelector("[data-agent-body]")).not.toBeNull();+ expect(container.querySelectorAll("[data-agent-eyes] ellipse")).toHaveLength(2);+ rerender(<AgentSymbol shape="cloud" color="#8b5cf6" size={48} />);+ expect(container.querySelector("[data-thinking]")).toBeNull();+ expect(container.querySelector(".agent-symbol-orbit, .agent-symbol-thoughts")).toBeNull();+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/AgentSymbol.tsx b/jarvis/ui/web/frontend/src/components/society/AgentSymbol.tsxnew file mode 100644index 0000000000..8b71e6e829--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/AgentSymbol.tsx@@ -0,0 +1,82 @@+/**+ * Flat bot silhouettes and eye placement adapted from Nous Research's+ * hermes-agent, apps/desktop/src/plugins/hermes-bots/avatar.tsx.+ * Source revision: 4a2bd7406ee3e09bd30a42cf9a7b970aac6edf9e.+ * Copyright (c) 2025 Nous Research. MIT license; see THIRD_PARTY_NOTICES.txt.+ *+ * Jarvis adaptation: stable ID-based appearance and state-driven CSS motion,+ * without a SDK, JavaScript frame clock, model download or WebGL in the roster.+ */++import { defaultCompanion, companionEyeColors, type SymbolShape } from "./companion/appearance";+import "./agentSymbol.css";+export type { SymbolShape } from "./companion/appearance";++export function symbolAppearance(identity: string): { shape: SymbolShape; color: string } {+ const { shape, color } = defaultCompanion(identity);+ return { shape, color };+}++/** The upstream superellipse sampler keeps the square soft without a bevel. */+function roundedOutline(shape: "squircle" | "pill"): string {+ const points: string[] = [];+ for (let i = 0; i < 52; i++) {+ const angle = (i / 52) * Math.PI * 2 - Math.PI / 2;+ const c = Math.cos(angle);+ const s = Math.sin(angle);+ const power = shape === "pill" ? 8 : 5;+ const divisor = Math.pow(Math.abs(c) ** power + Math.abs(s / (shape === "pill" ? 0.72 : 1)) ** power, 1 / power) || 1;+ const radius = (shape === "pill" ? 16 : 16.2) / divisor;+ points.push(`${i === 0 ? "M" : "L"}${(20 + radius * c).toFixed(2)} ${(20 + radius * s).toFixed(2)}`);+ }+ return points.join(" ") + "Z";+}++const ROUNDED_OUTLINES = { squircle: roundedOutline("squircle"), pill: roundedOutline("pill") };++function SymbolBody({ shape, color }: { shape: SymbolShape; color: string }) {+ switch (shape) {+ case "squircle":+ case "pill":+ return <path d={ROUNDED_OUTLINES[shape]} fill={color} />;+ case "triangle":+ return <path d="M20 5.5 L36 33.5 L4 33.5 Z" fill={color} stroke={color} strokeWidth={5} strokeLinejoin="round" />;+ case "hexagon":+ return <path d="M20 3.5 L34.5 11.75 L34.5 28.25 L20 36.5 L5.5 28.25 L5.5 11.75 Z" fill={color} stroke={color} strokeWidth={3} strokeLinejoin="round" />;+ case "cloud":+ return <path d="M11 32 a7.5 7.5 0 0 1 -1 -14.9 A9.5 9.5 0 0 1 29 12.5 A7 7 0 0 1 30 32 Z" fill={color} />;+ case "drop":+ return <path d="M20 3 C20 3 6 20 6 27 a14 13.5 0 0 0 28 0 C34 20 20 3 20 3 Z" fill={color} />;+ default:+ return <circle cx={20} cy={20} fill={color} r={16.2} />;+ }+}++/** A monochrome thinking interlude, using the agent's own identity colour. */+export function SymbolThinkingDots({ color }: { color: string }) {+ return <g className="agent-symbol-thoughts" fill={color}>+ <circle cx={10} cy={22} r={3} /><circle cx={20} cy={22} r={4} /><circle cx={30} cy={22} r={3} />+ </g>;+}++/** Plain ink eyes share one resting gaze; only a working agent moves. */+export function AgentSymbol({ shape, color, size, eyes = "lines", thinking = false }: { shape: SymbolShape; color: string; size: number; eyes?: "dots" | "lines"; thinking?: boolean }) {+ const eyeY = shape === "cloud" || shape === "triangle" ? 23 : shape === "drop" ? 25 : 17.2;+ const ink = companionEyeColors(color);+ return (+ <svg aria-hidden focusable="false" data-agent-symbol={shape} data-thinking={thinking ? "true" : undefined} width={size} height={size} style={{ width: size, height: size, flexShrink: 0 }} viewBox="0 0 40 44" className="society-agent-symbol block">+ <g className="agent-symbol-character">+ <g data-agent-body><SymbolBody shape={shape} color={color} /></g>+ <g className="agent-symbol-gaze">+ <g data-agent-eyes fill={ink.eye} transform={`translate(2 -0.6) rotate(-14 20 ${eyeY})`}>+ <g className="agent-symbol-lids">+ <ellipse cx={15.4} cy={eyeY} rx={eyes === "lines" ? 1.45 : 2} ry={eyes === "lines" ? 3.1 : 2.3} />+ <ellipse cx={24.6} cy={eyeY} rx={eyes === "lines" ? 1.45 : 2} ry={eyes === "lines" ? 3.1 : 2.3} />+ </g>+ </g>+ </g>+ </g>+ {thinking && <SymbolThinkingDots color={color} />}+ </svg>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/society/GigiAvatar.css b/jarvis/ui/web/frontend/src/components/society/GigiAvatar.cssnew file mode 100644index 0000000000..0af3f12ece--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/GigiAvatar.css@@ -0,0 +1,82 @@+.gigi-avatar { display: inline-flex; flex: none; pointer-events: none; isolation: isolate; }+.gigi-avatar svg { display: block; overflow: visible; }+.gigi-avatar__pose { transform-origin: 120px 132px; }+.gigi-avatar__shadow { transform-origin: 120px 242px; }+.gigi-avatar__eye--left { transform-origin: 89px 93px; }+.gigi-avatar__eye--right { transform-origin: 151px 93px; }+.gigi-avatar__arm--left { transform-origin: 46px 139px; }+.gigi-avatar__arm--right { transform-origin: 194px 139px; }+.gigi-avatar__eyes-happy, .gigi-avatar__wink, .gigi-avatar__smile, .gigi-avatar__sparks { opacity: 0; }++@media (prefers-reduced-motion: no-preference) {+ .gigi-avatar[data-animated="true"] .gigi-avatar__float { animation: gigi-avatar-hover 3.8s ease-in-out infinite; }+ .gigi-avatar[data-animated="true"] .gigi-avatar__shadow { animation: gigi-avatar-shadow 3.8s ease-in-out infinite; }+ .gigi-avatar[data-animated="true"] .gigi-avatar__pose { animation: gigi-avatar-sway 16s ease-in-out infinite; }+ .gigi-avatar[data-animated="true"] .gigi-avatar__eye--left { animation: gigi-avatar-blink 6.2s infinite; }+ .gigi-avatar[data-animated="true"] .gigi-avatar__eye--right { animation: gigi-avatar-blink 6.2s infinite, gigi-avatar-wink-open 16s infinite; }+ .gigi-avatar[data-animated="true"] .gigi-avatar__wink { animation: gigi-avatar-wink 16s infinite; }+ .gigi-avatar[data-animated="true"] .gigi-avatar__arm--right { animation: gigi-avatar-wave 16s ease-in-out infinite; }+ .gigi-avatar[data-animated="true"] .gigi-avatar__arm--left { animation: gigi-avatar-lift 16s ease-in-out infinite; }+ .gigi-avatar[data-animated="true"] :is(.gigi-avatar__eyes-open, .gigi-avatar__mouth-open) { animation: gigi-avatar-neutral 16s infinite; }+ .gigi-avatar[data-animated="true"] :is(.gigi-avatar__eyes-happy, .gigi-avatar__smile) { animation: gigi-avatar-happy 16s infinite; }+ .gigi-avatar[data-animated="true"] .gigi-avatar__sparks { animation: gigi-avatar-spark 16s infinite; }++ /* The host keeps its click/focus behaviour; the portrait adds no tab stop. */+ button:is(:hover, :focus-visible) .gigi-avatar[data-animated="true"] .gigi-avatar__arm--right { animation: gigi-avatar-greeting 1.4s ease-in-out infinite; }+ button:is(:hover, :focus-visible) .gigi-avatar[data-animated="true"] :is(.gigi-avatar__eyes-open, .gigi-avatar__mouth-open, .gigi-avatar__wink) { animation: none; opacity: 0; }+ button:is(:hover, :focus-visible) .gigi-avatar[data-animated="true"] :is(.gigi-avatar__eyes-happy, .gigi-avatar__smile, .gigi-avatar__sparks) { animation: none; opacity: 1; }+}++@keyframes gigi-avatar-hover {+ 0%, 100% { transform: translateY(2px); }+ 50% { transform: translateY(-5px); }+}+@keyframes gigi-avatar-shadow {+ 0%, 100% { transform: scaleX(1); opacity: .8; }+ 50% { transform: scaleX(.8); opacity: .45; }+}+@keyframes gigi-avatar-blink {+ 0%, 42%, 46%, 100% { transform: scaleY(1); }+ 44% { transform: scaleY(.08); }+}+@keyframes gigi-avatar-sway {+ 0%, 18%, 35%, 60%, 83%, 100% { transform: rotate(0); }+ 24%, 30% { transform: rotate(-7deg); }+ 68%, 76% { transform: rotate(6deg); }+}+@keyframes gigi-avatar-wave {+ 0%, 18%, 35%, 60%, 83%, 100% { transform: rotate(0); }+ 22%, 28%, 33% { transform: rotate(-115deg); }+ 25%, 31% { transform: rotate(-85deg); }+ 66%, 73%, 79% { transform: rotate(-105deg); }+ 69%, 76% { transform: rotate(-80deg); }+}+@keyframes gigi-avatar-lift {+ 0%, 60%, 83%, 100% { transform: rotate(0); }+ 67%, 77% { transform: rotate(90deg); }+}+@keyframes gigi-avatar-wink-open {+ 0%, 20%, 33%, 100% { opacity: 1; }+ 21%, 32% { opacity: 0; }+}+@keyframes gigi-avatar-wink {+ 0%, 20%, 33%, 100% { opacity: 0; }+ 21%, 32% { opacity: 1; }+}+@keyframes gigi-avatar-neutral {+ 0%, 64%, 80%, 100% { opacity: 1; }+ 65%, 79% { opacity: 0; }+}+@keyframes gigi-avatar-happy {+ 0%, 64%, 80%, 100% { opacity: 0; }+ 65%, 79% { opacity: 1; }+}+@keyframes gigi-avatar-spark {+ 0%, 21%, 25%, 29%, 33%, 65%, 70%, 75%, 80%, 100% { opacity: 0; }+ 23%, 27%, 31%, 68%, 73%, 78% { opacity: 1; }+}+@keyframes gigi-avatar-greeting {+ 0%, 100% { transform: rotate(-85deg); }+ 30%, 70% { transform: rotate(-120deg); }+ 50% { transform: rotate(-95deg); }+}diff --git a/jarvis/ui/web/frontend/src/components/society/GigiAvatar.test.tsx b/jarvis/ui/web/frontend/src/components/society/GigiAvatar.test.tsxnew file mode 100644index 0000000000..39147b3a03--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/GigiAvatar.test.tsx@@ -0,0 +1,29 @@+import { render } from "@testing-library/react";+import { describe, expect, it } from "vitest";++import { GigiAvatar } from "./GigiAvatar";++describe("Gigi portrait", () => {+ it("keeps SVG paints local when the roster and profile mount together", () => {+ const { container } = render(<><GigiAvatar /><GigiAvatar /></>);+ const ids = Array.from(container.querySelectorAll("[id]"), el => el.id);+ expect(new Set(ids).size).toBe(ids.length);+ for (const svg of container.querySelectorAll("svg")) {+ const localIds = new Set(Array.from(svg.querySelectorAll("[id]"), el => el.id));+ for (const el of svg.querySelectorAll("[fill], [stroke], [filter]")) {+ for (const attribute of ["fill", "stroke", "filter"]) {+ const reference = el.getAttribute(attribute)?.match(/^url\(#(.+)\)$/);+ if (reference) expect(localIds.has(reference[1])).toBe(true);+ }+ }+ }+ });++ it("keeps tiny message portraits static and the host's accessible name intact", () => {+ const { container } = render(<GigiAvatar size={18} />);+ expect(container.firstElementChild?.getAttribute("data-animated")).toBe("false");+ expect(container.firstElementChild?.getAttribute("aria-hidden")).toBe("true");+ expect(container.querySelector("button, [tabindex], img, canvas")).toBeNull();+ expect(container.querySelector("svg")?.getAttribute("width")).toBe("18");+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/GigiAvatar.tsx b/jarvis/ui/web/frontend/src/components/society/GigiAvatar.tsxnew file mode 100644index 0000000000..6ddba46e4e--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/GigiAvatar.tsx@@ -0,0 +1,84 @@+import { useId } from "react";+import "./GigiAvatar.css";++/** Graphite/gold companion portrait, drawn and animated without a GPU context. */+export function GigiAvatar({ size = 56 }: { size?: number }) {+ const id = `gigi-avatar-${useId().replace(/:/g, "")}`;+ const paint = (name: string) => `url(#${id}-${name})`;+ return (+ <span className="gigi-avatar agent-symbol-character" data-agent-mascot="gigi" data-animated={size >= 48} aria-hidden="true" style={{ width: size, height: size }}>+ <svg viewBox="0 0 240 260" width={size} height={size} fill="none" focusable="false">+ <defs>+ {/* Character material colours intentionally stay consistent across themes. */}+ <radialGradient id={`${id}-shell`} cx="34%" cy="18%" r="85%">+ <stop stopColor="#41403e" /><stop offset=".3" stopColor="#222224" /><stop offset=".7" stopColor="#101012" /><stop offset="1" stopColor="#070709" />+ </radialGradient>+ <radialGradient id={`${id}-lens`} cx="38%" cy="12%" r="95%">+ <stop stopColor="#333335" /><stop offset=".32" stopColor="#171719" /><stop offset=".8" stopColor="#070708" /><stop offset="1" stopColor="#141312" />+ </radialGradient>+ <linearGradient id={`${id}-metal`} x1="0" y1="0" x2="1" y2=".45">+ <stop stopColor="#876333" /><stop offset=".19" stopColor="#ffe3a0" /><stop offset=".36" stopColor="#3c3428" /><stop offset=".7" stopColor="#1a1817" /><stop offset="1" stopColor="#bb9150" />+ </linearGradient>+ <linearGradient id={`${id}-gold`} x1="0" y1="0" x2=".8" y2="1">+ <stop stopColor="#fff2bd" /><stop offset=".36" stopColor="#ffd769" /><stop offset=".72" stopColor="#ffbd36" /><stop offset="1" stopColor="#c98319" />+ </linearGradient>+ <radialGradient id={`${id}-eye`}>+ <stop stopColor="#ffeaa2" /><stop offset=".68" stopColor="#ffda61" /><stop offset="1" stopColor="#ffb72c" />+ </radialGradient>+ <radialGradient id={`${id}-pool`}>+ <stop stopColor="#ffc247" stopOpacity=".65" /><stop offset=".45" stopColor="#e9a83a" stopOpacity=".2" /><stop offset="1" stopColor="#d99c30" stopOpacity="0" />+ </radialGradient>+ <linearGradient id={`${id}-edge`}>+ <stop stopColor="#fff1c4" /><stop offset=".35" stopColor="#c18f3e" /><stop offset=".62" stopColor="#79592c" /><stop offset="1" stopColor="#ffe3a0" />+ </linearGradient>+ <filter id={`${id}-glow`} x="-60%" y="-60%" width="220%" height="220%" colorInterpolationFilters="sRGB">+ <feGaussianBlur stdDeviation="3" />+ </filter>+ </defs>+ <ellipse className="gigi-avatar__shadow" cx="120" cy="242" rx="57" ry="9" fill={paint("pool")} />+ <g className="gigi-avatar__float"><g className="gigi-avatar__pose">+ <g className="gigi-avatar__arm--left">+ <path d="M47 131C36 139 24 159 24 174C24 187 34 188 41 174L54 145Z" fill={paint("metal")} stroke={paint("edge")} strokeWidth="1.5" />+ <path d="M44 139C33 151 29 165 30 176C34 179 41 162 48 148Z" fill={paint("gold")} />+ </g>+ <g className="gigi-avatar__arm--right">+ <path d="M193 131C204 139 216 159 216 174C216 187 206 188 199 174L186 145Z" fill={paint("metal")} stroke={paint("edge")} strokeWidth="1.5" />+ <path d="M196 139C207 151 211 165 210 176C206 179 199 162 192 148Z" fill={paint("gold")} />+ </g>+ <rect x="37" y="89" width="15" height="39" rx="7.5" fill={paint("metal")} stroke="#8d7042" />+ <rect x="188" y="89" width="15" height="39" rx="7.5" fill={paint("metal")} stroke="#8d7042" />+ <path d="M40 98V118M200 98V118" stroke={paint("gold")} strokeWidth="3" strokeLinecap="round" />+ <path d="M45 113V94C45 45 73 22 120 22S195 45 195 94V184Q195 194 187 202L171 218L147 200L120 224L93 200L69 218L53 202Q45 194 45 184Z" fill={paint("shell")} stroke={paint("metal")} strokeWidth="2.5" />+ <path d="M49 118V94C49 48 75 26 120 26S191 48 191 94V118Z" fill={paint("lens")} />+ <path d="M46 100V94C46 46 75 23 120 23S194 46 194 94V100" stroke="#ffcd61" strokeWidth="3" filter={paint("glow")} />+ <path d="M46 99V94C46 46 75 23 120 23S194 46 194 94V99" stroke={paint("gold")} strokeWidth="1.8" />+ <path d="M60 59C72 36 95 27 119 27C145 27 165 35 177 51" stroke="#fff4d6" strokeOpacity=".72" strokeWidth="1.1" strokeLinecap="round" />+ <path d="M51 124V181Q51 193 58 197M188 127V180Q188 191 184 196" stroke={paint("edge")} strokeOpacity=".28" strokeWidth="1.3" />+ <path d="M46 119H194" stroke="#060606" strokeWidth="3.5" />+ <path d="M46 119H194" stroke={paint("edge")} strokeWidth="1" />+ <path d="M53 202L69 218L93 200L120 224L147 200L171 218L187 202" stroke="#ffb930" strokeWidth="7" strokeLinejoin="round" filter={paint("glow")} />+ <path d="M53 202L69 218L93 200L120 224L147 200L171 218L187 202" stroke={paint("gold")} strokeWidth="3.5" strokeLinejoin="round" />+ <path d="M56 203L69 215L93 197L120 221L147 197L171 215L185 202" stroke="#ffefb4" strokeWidth="1.1" strokeLinejoin="round" />+ <g className="gigi-avatar__eyes-open">+ {[89, 151].map((x, index) => (+ <g key={x} className={`gigi-avatar__eye--${index ? "right" : "left"}`}>+ <ellipse cx={x} cy="93" rx="16" ry="22" fill="#ffbc38" opacity=".65" filter={paint("glow")} />+ <ellipse cx={x} cy="93" rx="13" ry="18" fill={paint("eye")} />+ <ellipse cx={x + 2} cy="98" rx="6" ry="9" fill="#090909" />+ <ellipse cx={x + 5} cy="88" rx="3" ry="3.5" fill="#fffdf2" />+ </g>+ ))}+ </g>+ <path className="gigi-avatar__eyes-happy" d="M78 97C78 78 100 78 100 97M140 97C140 78 162 78 162 97" stroke={paint("gold")} strokeWidth="4" strokeLinecap="round" />+ <path className="gigi-avatar__wink" d="M140 97C140 78 162 78 162 97" stroke={paint("gold")} strokeWidth="4" strokeLinecap="round" />+ <g className="gigi-avatar__mouth-open">+ <ellipse cx="120" cy="137" rx="6" ry="9" stroke="#ffbd39" strokeWidth="4" filter={paint("glow")} />+ <ellipse cx="120" cy="137" rx="5.5" ry="8" stroke={paint("gold")} strokeWidth="2.7" />+ </g>+ <path className="gigi-avatar__smile" d="M113 135Q120 146 127 135Q120 139 113 135Z" fill={paint("gold")} />+ <path className="gigi-avatar__sparks" d="M203 58L206 49M212 65L220 61M210 77L218 78" stroke={paint("gold")} strokeWidth="2.8" strokeLinecap="round" />+ </g></g>+ </svg>+ </span>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/society/agentSymbol.css b/jarvis/ui/web/frontend/src/components/society/agentSymbol.cssnew file mode 100644index 0000000000..dafcbda5ca--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/agentSymbol.css@@ -0,0 +1,34 @@+.society-agent-symbol .agent-symbol-thoughts {+ opacity: 0;+ pointer-events: none;+}++/* Working replaces the face with three dots for the entire operation. */+.society-agent-symbol[data-thinking="true"] .agent-symbol-character {+ display: none;+}++.society-agent-symbol[data-thinking="true"] .agent-symbol-thoughts {+ opacity: 1;+}++.society-agent-symbol[data-thinking="true"] .agent-symbol-thoughts circle {+ transform-box: fill-box;+ transform-origin: center;+ animation: agent-symbol-dot 0.9s ease-in-out infinite alternate;+}++.society-agent-symbol .agent-symbol-thoughts circle:nth-child(2) { animation-delay: -0.3s; }+.society-agent-symbol .agent-symbol-thoughts circle:nth-child(3) { animation-delay: -0.6s; }++@keyframes agent-symbol-dot {+ from { transform: translateY(1px) scale(0.8); opacity: 0.45; }+ to { transform: translateY(-1px) scale(1.1); opacity: 1; }+}++@media (prefers-reduced-motion: reduce) {+ .society-agent-symbol[data-thinking="true"] .agent-symbol-thoughts circle {+ animation: none;+ opacity: 1;+ }+}diff --git a/jarvis/ui/web/frontend/src/components/society/card/AgentBrowserPreview.tsx b/jarvis/ui/web/frontend/src/components/society/card/AgentBrowserPreview.tsxindex 683e7de680..73af82248b 100644--- a/jarvis/ui/web/frontend/src/components/society/card/AgentBrowserPreview.tsx+++ b/jarvis/ui/web/frontend/src/components/society/card/AgentBrowserPreview.tsx@@ -92,7 +92,9 @@ export function AgentBrowserPreview({ agent }: { agent: SocietyAgent }) {control("key", { key: [...modifiers, e.key].join("+") });}}} />- <AgentCursor pointer={state.ready && state.connected && !state.manual ? state.pointer : undefined} />+ {!state.fullWindow && (+ <AgentCursor pointer={state.ready && state.connected && !state.manual ? state.pointer : undefined} />+ )}{!state.ready && <div className="absolute inset-0 grid place-items-center bg-muted p-3 text-center text-xs text-muted-foreground">{install.data?.detail || status}{install.data?.running && <span>{install.data.percent}%</span>}diff --git a/jarvis/ui/web/frontend/src/components/society/card/AgentCardOverlay.tsx b/jarvis/ui/web/frontend/src/components/society/card/AgentCardOverlay.tsxindex 23a6bc2a07..fcdf93ef42 100644--- a/jarvis/ui/web/frontend/src/components/society/card/AgentCardOverlay.tsx+++ b/jarvis/ui/web/frontend/src/components/society/card/AgentCardOverlay.tsx@@ -3,6 +3,7 @@* The workspace can be embedded in the section or opened as a modal.* Radix Dialog provides focus containment and Escape-to-close.*/+import type { ReactNode } from "react";import * as Dialog from "@radix-ui/react-dialog";import { X } from "lucide-react";@@ -30,6 +31,8 @@ export interface AgentCardOverlayProps {onClose: () => void;/** Render as the section workspace instead of a modal. */embedded?: boolean;+ /** Drawn at the top of the agent list, in the gray column. */+ railHeader?: ReactNode;}export function AgentCardOverlay({@@ -41,6 +44,7 @@ export function AgentCardOverlay({onCreate,onClose,embedded = false,+ railHeader,}: AgentCardOverlayProps) {const t = useT();useLocaleChunk("society");@@ -73,7 +77,7 @@ export function AgentCardOverlay({</button></header>)}- <div className="grid min-h-0 flex-1 grid-cols-[minmax(220px,1fr)_minmax(0,5fr)_minmax(300px,320px)]">+ <div className="grid min-h-0 flex-1 grid-cols-[minmax(240px,300px)_minmax(0,1fr)]"><RosterRailagents={roster}loading={rosterLoading}@@ -82,8 +86,15 @@ export function AgentCardOverlay({onOpen={(id) => { if (id !== agent.agentId) onSelectAgent?.(id); }}onCreate={() => onCreate?.()}side="left"- className="w-full"+ className="w-full border-0 jarvis-nav-surface"+ header={railHeader}/>+ {/* Inner reading pane: same ground, divider and corner as the+ window sheet, but WITHOUT its top border. Top + left borders+ meet exactly at the rounded corner, and on a fractional grid+ seam that joint rasterizes as a small step. The gray caption+ above already separates by ground, so one border is enough. */}+ <div className="grid min-h-0 grid-cols-[minmax(0,1fr)_minmax(280px,320px)] overflow-hidden rounded-tl-[12px] border-l border-border bg-background"><sectionclassName="flex min-h-0 flex-col"aria-label={t("society.card.chat")}@@ -92,6 +103,7 @@ export function AgentCardOverlay({<AgentChatPanel key={agent.agentId} agent={agent} roster={roster} /></section><OptionsRail agent={agent} onRetired={onClose} sample={sample} />+ </div></div></>) : null}diff --git a/jarvis/ui/web/frontend/src/components/society/card/AgentRoutineDetail.test.tsx b/jarvis/ui/web/frontend/src/components/society/card/AgentRoutineDetail.test.tsxindex 9bcd3975d5..ec219077dd 100644--- a/jarvis/ui/web/frontend/src/components/society/card/AgentRoutineDetail.test.tsx+++ b/jarvis/ui/web/frontend/src/components/society/card/AgentRoutineDetail.test.tsx@@ -5,20 +5,25 @@ import { AgentRoutineDetail, routineRuns } from "./AgentRoutineDetail";import type { LiveRoutine } from "../cardData";import type { TaskDetail, TaskStep } from "@/views/automations/automationsModel";import en from "@/i18n/locales/society/en.json";+import { RoutineChatHost } from "../chat/RoutineChatHost";+import { useRoutineNavigation } from "../chat/routineNavigation";++// Transcript rendering is covered separately; this suite exercises lazy lifecycle.+vi.mock("@/components/agentchat/AgentTimeline", () => ({ AgentTimeline: () => null }));vi.mock("@/i18n", () => ({useLocaleChunk: () => {},useT: () => (key: string) => key.split(".").reduce<unknown>((value, part) => (value as Record<string, unknown>)?.[part], en) ?? key,}));-afterEach(() => { cleanup(); vi.unstubAllGlobals(); });+afterEach(() => { cleanup(); useRoutineNavigation.getState().close(); vi.unstubAllGlobals(); });-function setup(multiple = false) {+function setup(multiple = false, steps: TaskStep[] = [], host = false) {const trigger = { type: "calendar", local_time: "08:00", timezone: "Europe/Berlin", weekdays: [0, 2] };const member: LiveRoutine = { id: "r1", title: "[agent:Mail] Inbox", prompt: "Read mail.", trigger, schedule: "", state: "scheduled", dueMs: null, lastRunMs: null };const members = multiple ? [member, { ...member, id: "r2" }] : [member];const tasks = new Map(members.map((m) => [m.id, {- ...m, trigger_type: "calendar", spec: { action: { kind: "agent", prompt: "Identity\nRoutine:\nRead mail." } }, steps: [],+ ...m, trigger_type: "calendar", spec: { action: { kind: "agent", prompt: "Identity\nRoutine:\nRead mail." } }, steps,} as unknown as TaskDetail]));const fetcher = vi.fn(async (url: string, init?: RequestInit) => {const method = init?.method ?? "GET";@@ -29,6 +34,7 @@ function setup(multiple = false) {vi.stubGlobal("fetch", fetcher);const onClose = vi.fn();render(<QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>+ {host && <RoutineChatHost agentId="mail" onOpen={() => {}}><p data-testid="main-agent-chat">Main conversation</p></RoutineChatHost>}<AgentRoutineDetail routine={{ ...member, members }} agentId="mail" onClose={onClose} /></QueryClientProvider>);return { fetcher, onClose };@@ -46,6 +52,45 @@ test("loads the instruction and saves all timings under the original ids", asyncexpect(JSON.parse(String(writes[0][1]?.body))).toMatchObject({ title: "Updated inbox", prompt: "Read mail.", schedule: { weekdays: [0, 2] } });});+test("opens only the selected execution socket and releases it on return", async () => {+ const sockets: { url: string; close: ReturnType<typeof vi.fn> }[] = [];+ class Socket {+ close = vi.fn();+ constructor(public url: string) { sockets.push(this); }+ }+ vi.stubGlobal("WebSocket", Socket);+ const sid = "society:mail:routine:r1:proof";+ const events = [{ event: "run_started" }, { event: "routine_chat", session_id: sid }, { event: "run_completed" }];+ const { fetcher } = setup(false, events.map((payload, seq) => ({ seq, kind: "log", timestamp_ns: (seq + 1) * 1e9, payload })), true);+ await screen.findByText("Open latest chat");+ expect(sockets).toHaveLength(0);+ expect(fetcher.mock.calls.some(([url]) => url.includes("agent-chat"))).toBe(false);+ fireEvent.click(screen.getByTestId("routine-run-r1:0"));+ // Cold module transformation includes the real dialog and socket store.+ await screen.findByTestId("routine-chat", {}, { timeout: 10000 });+ expect(screen.queryByRole("dialog")).toBeNull();+ expect(screen.queryByTestId("main-agent-chat")).toBeNull();+ expect(screen.getByTestId("agent-routine-detail")).toBeTruthy();+ expect(sockets).toHaveLength(1);+ expect(decodeURIComponent(sockets[0].url)).toContain(sid);+ fireEvent.click(screen.getByRole("button", { name: "Back to agent chat" }));+ await screen.findByTestId("main-agent-chat");+ expect(sockets[0].close).toHaveBeenCalledOnce();+ expect(fetcher.mock.calls.some(([url]) => url.endsWith("/cancel"))).toBe(false);+}, 15000);++test("latest means the newest execution even when only an older run has a separate chat", async () => {+ const events = [{ event: "run_started" }, { event: "routine_chat", session_id: "society:mail:routine:r1:older" }, { event: "run_completed" }, { event: "run_started" }, { event: "error" }];+ const { fetcher } = setup(false, events.map((payload, seq) => ({ seq, kind: "log", timestamp_ns: (seq + 1) * 1e12, payload })));+ await screen.findByText("Open latest chat");+ expect(useRoutineNavigation.getState().target).toBeNull();+ fireEvent.click(screen.getByText("Open latest chat"));+ expect(useRoutineNavigation.getState().target).toMatchObject({ sessionId: "society:mail", timestamp: 4000000, legacy: { taskId: "r1", startedMs: 4000000, finishedMs: 5000000 } });+ expect(fetcher.mock.calls.some(([url]) => url.includes("agent-chat"))).toBe(false);+ fireEvent.click(screen.getByTestId("routine-run-r1:0"));+ expect(useRoutineNavigation.getState().target?.sessionId).toBe("society:mail:routine:r1:older");+});+test("pauses every timing, tests once, and requires a delete confirmation", async () => {const { fetcher, onClose } = setup(true);await waitFor(() => expect((screen.getByRole("switch") as HTMLButtonElement).disabled).toBe(false));diff --git a/jarvis/ui/web/frontend/src/components/society/card/AgentRoutineDetail.tsx b/jarvis/ui/web/frontend/src/components/society/card/AgentRoutineDetail.tsxindex 158854ea80..e079d55c2a 100644--- a/jarvis/ui/web/frontend/src/components/society/card/AgentRoutineDetail.tsx+++ b/jarvis/ui/web/frontend/src/components/society/card/AgentRoutineDetail.tsx@@ -10,6 +10,8 @@ import type { TaskDetail, TaskStep } from "@/views/automations/automationsModel"import { TriggerBuilder } from "./TriggerBuilder";import { WebhookConnection } from "./WebhookConnection";import { SourceControls } from "./SourceControls";+import { RoutineSeatPicker, type RoutineSeat } from "./RoutineSeatPicker";+import { useRoutineNavigation } from "../chat/routineNavigation";const field = "w-full rounded-lg border border-border bg-background px-3 py-2 text-[12px] text-foreground";const button = "rounded-md bg-secondary px-2.5 py-1.5 text-[12px] text-foreground hover:bg-secondary/70 disabled:opacity-50";@@ -17,7 +19,7 @@ const recurring = ["every", "calendar", "cron", "webhook", "event_hook", "sourceconst terminal = ["completed", "failed", "cancelled", "interrupted"];const timeKinds = ["every", "calendar", "cron"];-interface Run { id: string; timestamp: number; status: string; text: string }+interface Run { id: string; taskId: string; timestamp: number; status: string; text: string; sessionId?: string; startedMs?: number; finishedMs?: number }/** New runs have explicit boundaries; retain older result/error records too. */export function routineRuns(taskId: string, steps: TaskStep[]): Run[] {@@ -28,17 +30,19 @@ export function routineRuns(taskId: string, steps: TaskStep[]): Run[] {const text = String(step.payload.message ?? step.payload.text ?? "");if (event === "run_started") {if (current?.status === "running") current.status = "interrupted";- current = { id: `${taskId}:${step.seq}`, timestamp: step.timestamp_ns / 1e6, status: "running", text: "" };+ current = { id: `${taskId}:${step.seq}`, taskId, timestamp: step.timestamp_ns / 1e6, startedMs: step.timestamp_ns / 1e6, status: "running", text: "" };runs.push(current);+ } else if (event === "routine_chat" && current && typeof step.payload.session_id === "string") {+ current.sessionId = step.payload.session_id;} else if (event === "agent_result" && current) {current.text = text;} else if (["run_completed", "run_cancelled", "error", "deferred"].includes(String(event))) {const status = event === "run_completed" ? "completed" : event === "run_cancelled" ? "cancelled" : event === "deferred" ? "pending" : "failed";- if (current) { current.status = status; if (text) current.text = text; current = undefined; }- else runs.push({ id: `${taskId}:${step.seq}`, timestamp: step.timestamp_ns / 1e6, status, text });+ if (current) { current.status = status; current.finishedMs = step.timestamp_ns / 1e6; if (text) current.text = text; current = undefined; }+ else runs.push({ id: `${taskId}:${step.seq}`, taskId, timestamp: step.timestamp_ns / 1e6, finishedMs: step.timestamp_ns / 1e6, status, text });} else if (event === "agent_result") {// Legacy runners persisted the result before the final state transition.- runs.push({ id: `${taskId}:${step.seq}`, timestamp: step.timestamp_ns / 1e6, status: "legacy", text });+ runs.push({ id: `${taskId}:${step.seq}`, taskId, timestamp: step.timestamp_ns / 1e6, finishedMs: step.timestamp_ns / 1e6, status: "legacy", text });}}return runs;@@ -70,18 +74,34 @@ export function AgentRoutineDetail({ agentId, routine, onClose }: {const [error, setError] = useState("");const [notice, setNotice] = useState("");const [confirmDelete, setConfirmDelete] = useState(false);+ const openChat = useRoutineNavigation((state) => state.open);const details = queries.map((query) => query.data);const first = details[0];const rawPrompt = String((first?.spec?.action as { prompt?: string } | undefined)?.prompt ?? "");const marker = rawPrompt.indexOf("\nRoutine:\n");const saved = { title: displayRoutineTitle(first?.title ?? routine.title), prompt: marker >= 0 ? rawPrompt.slice(marker + 10) : routine.prompt ?? rawPrompt };const values = draft ?? saved;+ const seatAction = (first?.spec?.action ?? {}) as { kind?: string; provider?: unknown; model?: unknown; effort?: unknown; account_id?: unknown };+ const savedSeat: RoutineSeat = {+ provider: String(seatAction.provider ?? ""),+ model: String(seatAction.model ?? ""),+ effort: String(seatAction.effort ?? ""),+ account_id: String(seatAction.account_id ?? ""),+ };+ const [seatDraft, setSeatDraft] = useState<RoutineSeat | null>(null);+ const [seatOpen, setSeatOpen] = useState(false);+ const seat = seatDraft ?? savedSeat;+ const seatDirty = seatDraft !== null && (+ seatDraft.provider !== savedSeat.provider || seatDraft.model !== savedSeat.model ||+ seatDraft.effort !== savedSeat.effort || seatDraft.account_id !== savedSeat.account_id+ );const ready = details.every(Boolean);const running = details.some((detail) => detail?.state === "running");const active = details.some((detail) => detail && detail.state !== "paused" && !terminal.includes(detail.state));const editable = ready && !running && details.every((detail, index) => detail && (index > 0 && terminal.includes(detail.state) || recurring.includes(detail.trigger_type) && !terminal.includes(detail.state)));+ const seatEditable = ready && !running && seatAction.kind !== "workflow";const url = `/api/society/agents/${encodeURIComponent(agentId)}/routines`;const refresh = () => Promise.all([client.invalidateQueries({ queryKey: ["tasks"] }),@@ -95,6 +115,7 @@ export function AgentRoutineDetail({ agentId, routine, onClose }: {};const update = (member: LiveRoutine, nextSchedule: unknown) => writeRoutine(`${url}/${encodeURIComponent(member.id)}`, {title: values.title.trim(), prompt: values.prompt.trim(), schedule: nextSchedule,+ ...(seatDirty ? { provider: seat.provider, model: seat.model, effort: seat.effort, account_id: seat.account_id } : {}),});const valid = Boolean(values.title.trim() && values.prompt.trim());const runs = details.flatMap((detail) => detail ? routineRuns(detail.id, detail.steps) : []).sort((a, b) => b.timestamp - a.timestamp);@@ -104,6 +125,14 @@ export function AgentRoutineDetail({ agentId, routine, onClose }: {return null;};+ const openRun = (run: Run) => {+ const ownChat = run.sessionId?.startsWith(`society:${agentId}:routine:${run.taskId}:`);+ openChat({ agentId, sessionId: ownChat ? run.sessionId! : `society:${agentId}`,+ title: saved.title, timestamp: run.timestamp, result: run.text,+ ...(!ownChat ? { legacy: { taskId: run.taskId, startedMs: run.startedMs, finishedMs: run.finishedMs } } : {}),+ });+ };+return <section className="min-h-0 flex-1 space-y-4 overflow-y-auto pb-4 text-foreground" data-testid="agent-routine-detail"><button type="button" className="flex items-center gap-1 text-[12px] text-muted-foreground" disabled={pending} onClick={onClose}><ArrowLeft size={14} />{t("society.card.routines")}</button><div className="flex flex-wrap items-center gap-2">@@ -130,8 +159,29 @@ export function AgentRoutineDetail({ agentId, routine, onClose }: {<label className="block space-y-1 text-[11px] text-muted-foreground">{label("prompt")}<textarea className={field} aria-label={label("prompt")} maxLength={16000} rows={7} disabled={pending || !editable || Boolean(editing) || (first?.spec?.action as { kind?: string } | undefined)?.kind !== "agent"} value={values.prompt} onChange={(event) => setDraft({ ...values, prompt: event.target.value })} /></label>{draft && <div className="flex gap-2"><button className={button} disabled={pending || !valid || !editable || Boolean(editing)} onClick={() => void act(async () => {for (const [index, member] of members.entries()) if (!terminal.includes(details[index]!.state)) await update(member, details[index]?.trigger);- setDraft(null); setNotice(label("saved"));+ setDraft(null); setSeatDraft(null); setSeatOpen(false); setNotice(label("saved"));})}>{label("save")}</button><button className={button} disabled={pending} onClick={() => setDraft(null)}>{label("cancel")}</button></div>}+ {seatEditable && <div className="space-y-2 rounded-xl border border-border p-3">+ <div className="flex items-center justify-between gap-2">+ <h4 className="text-[11px] text-muted-foreground">{label("model")}</h4>+ <button+ type="button"+ className="text-[11px] text-muted-foreground underline disabled:opacity-50"+ disabled={pending || !editable || Boolean(editing)}+ onClick={() => setSeatOpen((open) => !open)}+ >+ {seatOpen ? label("cancel") : label("change")}+ </button>+ </div>+ <p className="text-[12px]">+ {!seat.provider ? label("follow_agent") : `${seat.provider}${seat.model ? ` · ${seat.model}` : ""}${seat.effort ? ` · ${seat.effort}` : ""}`}+ </p>+ {seatOpen && <RoutineSeatPicker seat={seat} disabled={pending || !editable || Boolean(editing)} onChange={setSeatDraft} />}+ </div>}+ {seatDirty && <div className="flex gap-2"><button className={button} disabled={pending || !valid || !editable || Boolean(editing) || Boolean(draft)} onClick={() => void act(async () => {+ for (const [index, member] of members.entries()) if (!terminal.includes(details[index]!.state)) await update(member, details[index]?.trigger);+ setSeatDraft(null); setSeatOpen(false); setNotice(label("saved"));+ })}>{label("save")}</button><button className={button} disabled={pending} onClick={() => setSeatDraft(null)}>{label("cancel")}</button></div>}<div className="space-y-2"><h4 className="text-[11px] text-muted-foreground">{label("when")}</h4><div className="space-y-2 rounded-xl border border-border p-3">@@ -160,13 +210,11 @@ export function AgentRoutineDetail({ agentId, routine, onClose }: {</div><div className="space-y-2"><h4 className="text-[11px] text-muted-foreground">{label("history")}</h4>+ {runs.length > 0 && <button type="button" className={button} onClick={() => openRun(runs[0])}>{label("latest_chat")}</button>}{ready && runs.length === 0 && <p className="text-[12px] text-muted-foreground">{label("no_runs")}</p>}- {runs.map((run) => <details key={run.id} className="text-[12px]">- <summary className="flex cursor-pointer items-center justify-between gap-2 rounded py-1 hover:bg-secondary"><time dateTime={new Date(run.timestamp).toISOString()}>{new Date(run.timestamp).toLocaleString()}</time><span className="flex items-center gap-1" title={run.status === "legacy" ? label("legacy") : t(`tasks_view.state.${run.status}`)}>+ {runs.map((run) => <button key={run.id} type="button" data-testid={`routine-run-${run.id}`} aria-label={`${label("open_chat")} · ${new Date(run.timestamp).toLocaleString()}`} onClick={() => openRun(run)} className="flex w-full cursor-pointer items-center justify-between gap-2 rounded py-1 text-left text-[12px] hover:bg-secondary focus-visible:outline focus-visible:outline-ring"><time dateTime={new Date(run.timestamp).toISOString()}>{new Date(run.timestamp).toLocaleString()}</time><span className="flex items-center gap-1" title={run.status === "legacy" ? label("legacy") : t(`tasks_view.state.${run.status}`)}>{run.status === "completed" ? <Check size={15} className="text-success" aria-label={t("tasks_view.state.completed")} /> : run.status === "failed" || run.status === "cancelled" ? <X size={15} className="text-destructive" aria-label={t(`tasks_view.state.${run.status}`)} /> : <Clock size={15} aria-label={run.status === "legacy" ? label("legacy") : t(`tasks_view.state.${run.status}`)} />}- </span></summary>- <p className="whitespace-pre-wrap break-words rounded bg-secondary p-2">{run.text || (run.status === "legacy" ? label("legacy") : t(`tasks_view.state.${run.status}`))}</p>- </details>)}+ </span></button>)}</div></section>;}diff --git a/jarvis/ui/web/frontend/src/components/society/card/AgentRoutineDetailSeat.test.tsx b/jarvis/ui/web/frontend/src/components/society/card/AgentRoutineDetailSeat.test.tsxnew file mode 100644index 0000000000..1734206eb1--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/card/AgentRoutineDetailSeat.test.tsx@@ -0,0 +1,92 @@+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { afterEach, expect, test, vi } from "vitest";+import { AgentRoutineDetail } from "./AgentRoutineDetail";+import type { TaskDetail } from "@/views/automations/automationsModel";+import en from "@/i18n/locales/society/en.json";++vi.mock("@/components/agentchat/AgentTimeline", () => ({ AgentTimeline: () => null }));++vi.mock("@/i18n", () => ({+ useLocaleChunk: () => {},+ useT: () => (key: string) => key.split(".").reduce<unknown>((value, part) => (value as Record<string, unknown>)?.[part], en) ?? key,+}));++afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+});++function setup() {+ const trigger = { type: "calendar", local_time: "08:00", timezone: "Europe/Berlin" };+ const task = {+ id: "r1",+ title: "[agent:Mail] Inbox",+ trigger_type: "calendar",+ trigger,+ state: "scheduled",+ spec: {+ action: {+ kind: "agent",+ prompt: "Identity\nRoutine:\nRead mail.",+ provider: "claude-api",+ model: "opus",+ effort: "",+ account_id: "",+ },+ },+ steps: [],+ } as unknown as TaskDetail;+ const fetcher = vi.fn(+ async (_url: string, _init?: RequestInit) =>+ ({ ok: true, status: 200, json: async () => task }) as Response,+ );+ vi.stubGlobal("fetch", fetcher);+ render(+ <QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>+ <AgentRoutineDetail+ routine={{ id: "r1", title: "[agent:Mail] Inbox", prompt: "Read mail.", trigger, schedule: "", state: "scheduled", dueMs: null, lastRunMs: null }}+ agentId="mail"+ onClose={() => {}}+ />+ </QueryClientProvider>,+ );+ return { fetcher };+}++test("the pinned seat is shown and can follow the agent again", async () => {+ const { fetcher } = setup();+ await waitFor(() => expect((screen.getByLabelText("Name") as HTMLInputElement).disabled).toBe(false));+ // The pin is visible without any catalog fetch.+ expect(screen.getByText("claude-api · opus")).toBeTruthy();+ expect(fetcher.mock.calls.some(([url]) => String(url).includes("agent-chat"))).toBe(false);+ // Opening the picker loads the catalog; clearing the pin saves empty seat fields.+ fireEvent.click(screen.getByText("Change"));+ const provider = (await screen.findByLabelText("Provider")) as HTMLSelectElement;+ expect(provider.value).toBe("claude-api");+ fireEvent.change(provider, { target: { value: "" } });+ expect(provider.value).toBe("");+ expect(screen.getByText("Follow agent", { selector: "p" })).toBeTruthy();+ fireEvent.click(screen.getAllByText("Save")[0]);+ await waitFor(() =>+ expect(+ fetcher.mock.calls.some(+ ([url, init]) =>+ String(url).includes("/routines/") &&+ init?.method === "PATCH" &&+ JSON.parse(String(init?.body))?.provider === "",+ ),+ ).toBe(true),+ );+ const patch = fetcher.mock.calls.find(+ ([url, init]) => String(url).includes("/routines/") && init?.method === "PATCH",+ );+ expect(JSON.parse(String(patch?.[1]?.body))).toMatchObject({+ title: "Inbox",+ prompt: "Read mail.",+ provider: "",+ model: "",+ effort: "",+ account_id: "",+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/card/OptionsRail.tsx b/jarvis/ui/web/frontend/src/components/society/card/OptionsRail.tsxindex fe9fe0819d..deb66896f0 100644--- a/jarvis/ui/web/frontend/src/components/society/card/OptionsRail.tsx+++ b/jarvis/ui/web/frontend/src/components/society/card/OptionsRail.tsx@@ -5,7 +5,7 @@* from AgentCardOverlay so the overlay stays the layout and this file owns* what you can do to the agent.*/-import { useEffect, useRef, useState } from "react";+import { lazy, Suspense, useEffect, useRef, useState } from "react";import { MoreHorizontal } from "lucide-react";import { useT } from "@/i18n";@@ -15,6 +15,7 @@ import { AgentBrowserPreview } from "./AgentBrowserPreview";import { AgentRoutinesList } from "./AgentRoutinesList";import { JarvisHistoryRail } from "../chat/JarvisHistoryRail";import { RetireButton } from "./RetireButton";+const AgentAppearanceDialog = lazy(() => import("../companion/AgentAppearanceDialog").then(m => ({ default: m.AgentAppearanceDialog })));export interface OptionsRailProps {agent: SocietyAgent;@@ -26,11 +27,13 @@ export interface OptionsRailProps {export function OptionsRail({ agent, onRetired, sample = false }: OptionsRailProps) {const t = useT();const [more, setMore] = useState(false);+ const [appearanceOpen, setAppearanceOpen] = useState(false);const [routineOpen, setRoutineOpen] = useState(false);const moreRef = useRef<HTMLDivElement>(null);useEffect(() => {setMore(false);+ setAppearanceOpen(false);}, [agent.agentId]);useEffect(() => {@@ -82,6 +85,7 @@ export function OptionsRail({ agent, onRetired, sample = false }: OptionsRailPro</div></header><div className="flex min-h-0 flex-1 flex-col gap-3 overflow-hidden px-3 pb-3 pt-2">+ <button type="button" onClick={() => setAppearanceOpen(true)} data-testid="edit-agent-appearance" className="shrink-0 rounded-lg border border-border px-3 py-2 text-left text-sm font-medium text-foreground hover:bg-secondary">{t("society.companion.appearance")}</button><div className={routineOpen ? "hidden" : "contents"}><AgentBrowserPreview agent={agent} />{agent.tier === "lead" ? <JarvisHistoryRail /> : null}@@ -95,6 +99,7 @@ export function OptionsRail({ agent, onRetired, sample = false }: OptionsRailProclassName="min-h-0 flex-1"/></div>+ {appearanceOpen && <Suspense fallback={null}><AgentAppearanceDialog key={agent.agentId} agent={agent} sample={sample} onClose={() => setAppearanceOpen(false)} /></Suspense>}</aside>);}diff --git a/jarvis/ui/web/frontend/src/components/society/card/RoutineChat.test.tsx b/jarvis/ui/web/frontend/src/components/society/card/RoutineChat.test.tsxnew file mode 100644index 0000000000..4bb90fc1a3--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/card/RoutineChat.test.tsx@@ -0,0 +1,55 @@+import { cleanup, render, screen } from "@testing-library/react";+import { afterEach, expect, test, vi } from "vitest";+import type { TimelineItem } from "@/components/agentchat/reduce";+import RoutineChat from "./RoutineChat";+import type { RoutineChatTarget } from "../chat/routineExecution";++vi.mock("@/i18n", () => ({ useT: () => (key: string) => key }));+vi.mock("@/components/agentchat/ChatMarkdown", () => ({ ChatMarkdown: ({ text }: { text: string }) => <p>{text}</p> }));+vi.mock("@/components/agentchat/AgentTimeline", () => ({ AgentTimeline: ({ items }: { items: TimelineItem[] }) => <pre data-testid="selected-transcript">{JSON.stringify(items)}</pre> }));++afterEach(() => { cleanup(); vi.unstubAllGlobals(); });++const instruction = "Scheduled routine daily. Follow your CURRENT standing instructions and permissions.\nUse your memory and conversation archive for prior results. For information watches, check sources and dates, remember last-seen items, and report only meaningful new findings.\n\nRead mail.";+const events = [+ { seq: 1, ts_ms: 10000, kind: "user_message", payload: { text: instruction } },+ { seq: 2, ts_ms: 10001, kind: "turn_started", payload: { turn_id: "first" } },+ { seq: 3, ts_ms: 10500, kind: "assistant_text", payload: { turn_id: "first", text: "FIRST ONLY" } },+ { seq: 4, ts_ms: 11000, kind: "turn_finished", payload: { turn_id: "first", status: "done" } },+ { seq: 5, ts_ms: 20000, kind: "user_message", payload: { text: "PRIVATE MAIN CHAT" } },+];+const target: RoutineChatTarget = { agentId: "mail", sessionId: "society:mail", title: "Inbox", timestamp: 10000,+ legacy: { taskId: "daily", startedMs: 9900, finishedMs: 11100 }, result: "Saved result" };++test("an old execution loads its own turn without opening a writable main chat", async () => {+ const fetcher = vi.fn(async () => new Response(JSON.stringify({ session: { title: "Mail" }, events })));+ const socket = vi.fn();+ vi.stubGlobal("fetch", fetcher);+ vi.stubGlobal("WebSocket", socket);+ render(<RoutineChat target={target} onClose={() => {}} />);+ const transcript = await screen.findByTestId("selected-transcript");+ expect(transcript.textContent).toContain("FIRST ONLY");+ expect(transcript.textContent).not.toContain("PRIVATE MAIN CHAT");+ expect(transcript.textContent).not.toContain("Follow your CURRENT");+ expect(socket).not.toHaveBeenCalled();+ expect(screen.queryByRole("textbox")).toBeNull();+ expect(fetcher).toHaveBeenCalledOnce();+ expect(fetcher.mock.calls[0]).toEqual(["/api/agent-chat/sessions/society%3Amail"]);+ // An old task could succeed through a fallback after its chat attempt failed.+ expect(screen.getByTestId("routine-saved-result").textContent).toContain("Saved result");+});++test("does not duplicate a saved result already present in the selected conversation", async () => {+ vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({ session: { title: "Mail" }, events }))));+ render(<RoutineChat target={{ ...target, result: "FIRST ONLY" }} onClose={() => {}} />);+ await screen.findByTestId("selected-transcript");+ expect(screen.queryByTestId("routine-saved-result")).toBeNull();+});++test("a missing historical turn shows only that execution's saved result", async () => {+ vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({ session: { title: "Mail" }, events }))));+ render(<RoutineChat target={{ ...target, legacy: { taskId: "daily", startedMs: 90000, finishedMs: 91000 } }} onClose={() => {}} />);+ await screen.findByText("Saved result");+ expect(screen.queryByTestId("selected-transcript")).toBeNull();+ expect(screen.queryByRole("textbox")).toBeNull();+});diff --git a/jarvis/ui/web/frontend/src/components/society/card/RoutineChat.tsx b/jarvis/ui/web/frontend/src/components/society/card/RoutineChat.tsxnew file mode 100644index 0000000000..55d131aada--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/card/RoutineChat.tsx@@ -0,0 +1,99 @@+/** The selected execution occupies the agent's chat lane and loads only on navigation. */+import { useEffect, useMemo, useState } from "react";+import { ArrowLeft, Send, Square } from "lucide-react";+import { AgentTimeline } from "@/components/agentchat/AgentTimeline";+import { ChatMarkdown } from "@/components/agentchat/ChatMarkdown";+import { EMPTY_TIMELINE, reduceEvents, runningTurn, type TimelineItem } from "@/components/agentchat/reduce";+import { AgentChatStoreProvider } from "@/components/agentchat/AgentChatStoreContext";+import { fetchAgentChatSession } from "@/lib/agentChatApi";+import { createAgentChatStore } from "@/store/agentChat";+import { useStickToBottom } from "@/hooks/useStickToBottom";+import { useT } from "@/i18n";+import { legacyRoutineEvents, routineTask, type RoutineChatTarget } from "../chat/routineExecution";++function displayItems(items: TimelineItem[]): TimelineItem[] {+ return items.map((item) => item.type === "user" ? { ...item, text: routineTask(item.text) ?? item.text } : item);+}++export default function RoutineChat({ target, onClose }: { target: RoutineChatTarget; onClose: () => void }) {+ const t = useT();+ return <section className="flex h-full min-h-0 flex-1 flex-col bg-background p-4 text-foreground sm:p-6" data-testid="routine-chat" data-session-id={target.sessionId}>+ <header className="flex shrink-0 flex-wrap items-center gap-x-4 gap-y-2 border-b border-border pb-3">+ <button type="button" className="flex items-center gap-1 text-[12px] text-muted-foreground hover:text-foreground" onClick={onClose}><ArrowLeft size={14} />{t("society.routine_detail.back_to_agent")}</button>+ <div className="min-w-0 flex-1"><h3 className="truncate text-sm font-medium">{target.title}</h3>+ <time className="text-[11px] text-muted-foreground" dateTime={new Date(target.timestamp).toISOString()}>{new Date(target.timestamp).toLocaleString()}</time>+ </div>+ <span className="text-[11px] text-muted-foreground">{t("society.routine_detail.background_chat")}</span>+ </header>+ {target.legacy ? <HistoricalExecution target={target} /> : <LiveExecution sessionId={target.sessionId} />}+ </section>;+}++function HistoricalExecution({ target }: { target: RoutineChatTarget }) {+ const t = useT();+ const [snapshot, setSnapshot] = useState<{ name: string; items: TimelineItem[]; resultInChat: boolean } | null>(null);+ const [error, setError] = useState("");+ useEffect(() => {+ let alive = true;+ void fetchAgentChatSession(target.sessionId).then(({ session, events }) => {+ if (!alive) return;+ const selected = legacyRoutineEvents(events, target);+ const items = displayItems(reduceEvents(EMPTY_TIMELINE, selected).items).map((item) => item.type === "turn"+ ? { ...item, blocks: item.blocks.map((block) => block.kind === "tool" ? { ...block, approval: null } : block) } : item);+ const replies = items.flatMap((item) => item.type === "turn" ? item.blocks.flatMap((block) => block.kind === "text" ? [block.text] : []) : []).join("\n");+ setSnapshot({ name: session.title, items, resultInChat: Boolean(target.result?.trim() && replies.includes(target.result.trim())) });+ }).catch((err) => { if (alive) setError(err instanceof Error ? err.message : String(err)); });+ return () => { alive = false; };+ }, [target]);+ return <>+ <div className="min-h-0 flex-1 space-y-4 overflow-y-auto py-4" data-testid="routine-historical-transcript">+ {!snapshot && !error && <p role="status">{t("tasks_view.loading_details")}</p>}+ {error && <p role="alert" className="text-sm text-destructive">{error}</p>}+ {snapshot?.items.length ? <AgentTimeline items={snapshot.items} assistantName={snapshot.name} providerLabel={(id) => id} onDecide={async () => { /* Historical approvals are hidden; this transcript cannot act. */ }} /> : null}+ {(snapshot?.items.length === 0 || error) && <>+ <p className="text-sm text-muted-foreground">{t("society.routine_detail.trace_unavailable")}</p>+ </>}+ {(snapshot || error) && target.result && !snapshot?.resultInChat && <section className="space-y-2 border-t border-border pt-3" data-testid="routine-saved-result">+ <h4 className="text-xs font-medium text-muted-foreground">{t("society.routine_detail.saved_result")}</h4>+ <ChatMarkdown text={target.result} />+ </section>}+ </div>+ <p className="shrink-0 border-t border-border pt-3 text-xs text-muted-foreground">{t("society.routine_detail.historical_chat")}</p>+ </>;+}++function LiveExecution({ sessionId }: { sessionId: string }) {+ const t = useT();+ const label = (key: string) => t(`society.routine_detail.${key}`);+ const [store] = useState(() => createAgentChatStore("society", "routine"));+ const timeline = store((state) => state.timeline);+ const visibleItems = useMemo(() => displayItems(timeline.items), [timeline.items]);+ const session = store((state) => state.activeSession);+ const busy = store((state) => state.busy);+ const socketState = store((state) => state.socketState);+ const error = store((state) => state.lastError);+ const [message, setMessage] = useState("");+ const running = Boolean(runningTurn(timeline)) || busy;+ const ready = session?.session_id === sessionId && socketState === "open";+ const scroll = useStickToBottom();+ useEffect(() => {+ store.getState().openSession(sessionId);+ return () => store.getState().disconnect();+ }, [sessionId, store]);+ return <AgentChatStoreProvider store={store}>+ <div ref={scroll.rootRef} className="min-h-0 flex-1 overflow-y-auto py-4"><div ref={scroll.contentRef} className="space-y-3">+ {!ready && !error && <p role="status" className="text-sm">{t("tasks_view.loading_details")}</p>}+ <AgentTimeline items={visibleItems} assistantName={session?.title.split(" · ")[0] ?? ""} providerLabel={(id) => id} onDecide={store.getState().decide} />+ </div></div>+ {error && <p role="alert" className="text-sm text-destructive">{error}</p>}+ <form className="mt-3 flex shrink-0 items-end gap-2" onSubmit={(event) => {+ event.preventDefault();+ if (!message.trim() || !ready || running) return;+ void store.getState().send(message).then(() => { if (!store.getState().lastError) setMessage(""); });+ }}>+ <textarea className="min-w-0 flex-1 rounded-lg border border-border bg-background p-2 text-sm" rows={2} aria-label={label("follow_up")} placeholder={label("follow_up")} value={message} onChange={(event) => setMessage(event.target.value)} />+ {running ? <button type="button" className="rounded p-2 hover:bg-secondary" aria-label={label("stop_run")} onClick={() => void store.getState().cancel()}><Square size={16} /></button>+ : <button type="submit" className="rounded p-2 hover:bg-secondary disabled:opacity-50" disabled={!ready || !message.trim()} aria-label={label("send")}><Send size={16} /></button>}+ </form>+ </AgentChatStoreProvider>;+}diff --git a/jarvis/ui/web/frontend/src/components/society/card/RoutineSeatPicker.tsx b/jarvis/ui/web/frontend/src/components/society/card/RoutineSeatPicker.tsxnew file mode 100644index 0000000000..c695ad231d--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/card/RoutineSeatPicker.tsx@@ -0,0 +1,152 @@+/** The model seat one routine runs on — pinned at creation, changeable here. */+import { useT } from "@/i18n";+import { useAgentChat } from "@/components/agentchat/AgentChatStoreContext";+import { effortsFor } from "../create/brainPicker";+import { modelSeats, providerTitle } from "../chat/modelChoices";+import { useModelMenuData } from "../chat/useModelMenuData";++export interface RoutineSeat {+ provider: string;+ model: string;+ effort: string;+ account_id: string;+}++export const EMPTY_SEAT: RoutineSeat = { provider: "", model: "", effort: "", account_id: "" };++const field = "w-full rounded-lg border border-border bg-background px-3 py-2 text-[12px] text-foreground";+const miniLabel = "block space-y-1 text-[11px] text-muted-foreground";++function kindSuffix(kind: string, t: (key: string) => string): string {+ try {+ return t(`society.create.kind_${kind}`);+ } catch {+ return kind;+ }+}++export function RoutineSeatPicker({ seat, onChange, disabled }: {+ seat: RoutineSeat;+ onChange: (next: RoutineSeat) => void;+ disabled: boolean;+}) {+ const t = useT();+ const label = (key: string) => t(`society.routine_detail.${key}`);+ const chatCatalog = useAgentChat((state) => (state.surface === "society" ? state.catalog : null));+ const chatConnections = useAgentChat((state) => state.connections);+ const { options, providers, live, loading } = useModelMenuData(chatCatalog, chatConnections, { [seat.provider]: seat.account_id });+ // The catalog query can resolve to anything while the backend is away; only+ // arrays reach the seat join so the picker degrades to free text, never a crash.+ const rows = Array.isArray(providers) ? providers : [];+ const seats = modelSeats(options, rows, live, t("agent_chat.model_default"));+ const active = seats.find((s) => s.provider.id === seat.provider) ?? null;+ const models = active?.provider.curated_models ?? [];+ const efforts = active ? effortsFor(active, seat.model) : [];+ const showAllModels = models.length === 0;++ return (+ <div className="space-y-2 rounded-xl border border-border p-3">+ <div className="flex items-center justify-between gap-2">+ <h4 className="text-[11px] text-muted-foreground">{label("model")}</h4>+ {seat.provider ? (+ <button+ type="button"+ className="text-[11px] text-muted-foreground underline disabled:opacity-50"+ disabled={disabled}+ onClick={() => onChange({ ...EMPTY_SEAT })}+ >+ {label("follow_agent")}+ </button>+ ) : null}+ </div>+ {!seat.provider ? (+ <p className="text-[12px] text-muted-foreground">{label("model_follows_agent")}</p>+ ) : null}+ <label className={miniLabel}>+ {label("provider")}+ <select+ className={field}+ aria-label={label("provider")}+ disabled={disabled || loading}+ value={seat.provider}+ onChange={(e) => {+ const next = seats.find((s) => s.provider.id === e.target.value) ?? null;+ onChange({+ provider: e.target.value,+ model: "",+ effort: next?.provider.default_effort ?? "",+ account_id: "",+ });+ }}+ >+ <option value="">{label("follow_agent")}</option>+ {seats.map((s) => (+ <option key={s.provider.id} value={s.provider.id}>+ {`${providerTitle(s, t)} · ${kindSuffix(s.kind, t)}`}+ </option>+ ))}+ {seat.provider && !active ? <option value={seat.provider}>{seat.provider}</option> : null}+ </select>+ </label>+ {seat.provider ? (+ <label className={miniLabel}>+ {label("model_name")}+ <input+ className={field}+ aria-label={label("model_name")}+ disabled={disabled}+ list="routine-seat-models"+ placeholder={showAllModels ? t("agent_chat.model_default") : undefined}+ value={seat.model}+ onChange={(e) => onChange({ ...seat, model: e.target.value })}+ />+ <datalist id="routine-seat-models">+ {models.map((m) => (+ <option key={m.id} value={m.id}>+ {m.label || m.id}+ </option>+ ))}+ </datalist>+ </label>+ ) : null}+ {seat.provider && efforts.length > 0 ? (+ <label className={miniLabel}>+ {label("effort")}+ <select+ className={field}+ aria-label={label("effort")}+ disabled={disabled}+ value={seat.effort}+ onChange={(e) => onChange({ ...seat, effort: e.target.value })}+ >+ <option value="">{t("agent_chat.model_default")}</option>+ {efforts.map((level) => (+ <option key={level} value={level}>+ {level}+ </option>+ ))}+ </select>+ </label>+ ) : null}+ {seat.provider && (active?.accounts.length ?? 0) > 0 ? (+ <label className={miniLabel}>+ {label("account")}+ <select+ className={field}+ aria-label={label("account")}+ disabled={disabled}+ value={seat.account_id}+ onChange={(e) => onChange({ ...seat, account_id: e.target.value })}+ >+ <option value="">{t("society.chat.model_active_account")}</option>+ {(active?.accounts ?? []).map((a) => (+ <option key={a.id} value={a.id}>+ {a.label}+ </option>+ ))}+ </select>+ </label>+ ) : null}+ </div>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/society/card/SourceControls.tsx b/jarvis/ui/web/frontend/src/components/society/card/SourceControls.tsxindex 8200075bef..4de7f4a458 100644--- a/jarvis/ui/web/frontend/src/components/society/card/SourceControls.tsx+++ b/jarvis/ui/web/frontend/src/components/society/card/SourceControls.tsx@@ -1,6 +1,7 @@import { useState } from "react";import { useQuery, useQueryClient } from "@tanstack/react-query";import { useLocaleChunk, useT } from "@/i18n";+import { BrandedSelect } from "@/components/ui/select";type Source = { kind: string; form_fields?: Record<string, { label: string; kind: string; required: boolean; choices: string[] }> };@@ -48,7 +49,7 @@ function SourceInputs({ taskId, source }: { taskId: string; source: Source }) {</> : null}{open && !listener ? <form onSubmit={(event) => { event.preventDefault(); void send("invoke", "POST", { payload: values }); }} className="space-y-2">{Object.entries(source.form_fields ?? {}).map(([name, spec]) => <label className="block text-[11px]" key={name}>{spec.label}- {spec.kind === "choice" ? <select className={field} required={spec.required} value={String(values[name] ?? "")} onChange={(e) => setValues((v) => ({ ...v, [name]: e.target.value }))}><option value="">—</option>{spec.choices.map((choice) => <option key={choice}>{choice}</option>)}</select> : <input className={field} type={spec.kind === "boolean" ? "checkbox" : spec.kind === "number" ? "number" : "text"} required={spec.required && spec.kind !== "boolean"} onChange={(e) => setValues((v) => ({ ...v, [name]: spec.kind === "boolean" ? e.target.checked : spec.kind === "number" ? (e.target.value === "" ? null : Number(e.target.value)) : e.target.value }))} />}+ {spec.kind === "choice" ? <BrandedSelect className={field} value={String(values[name] ?? "")} onValueChange={(value) => setValues((v) => ({ ...v, [name]: value }))} ariaLabel={spec.label} options={[{ value: "", label: "—" }, ...spec.choices.map((choice) => ({ value: choice, label: choice }))]} /> : <input className={field} type={spec.kind === "boolean" ? "checkbox" : spec.kind === "number" ? "number" : "text"} required={spec.required && spec.kind !== "boolean"} onChange={(e) => setValues((v) => ({ ...v, [name]: spec.kind === "boolean" ? e.target.checked : spec.kind === "number" ? (e.target.value === "" ? null : Number(e.target.value)) : e.target.value }))} />}</label>)}<button type="submit" className={button} disabled={busy}>{label("run")}</button></form> : null}diff --git a/jarvis/ui/web/frontend/src/components/society/cardData.ts b/jarvis/ui/web/frontend/src/components/society/cardData.tsindex cbe3548257..4b06d314ba 100644--- a/jarvis/ui/web/frontend/src/components/society/cardData.ts+++ b/jarvis/ui/web/frontend/src/components/society/cardData.ts@@ -59,6 +59,11 @@ export interface LiveRoutine {lastRunMs: number | null;prompt?: string;members?: LiveRoutine[];+ /** Pinned model seat ("", all empty = the routine follows its owner). */+ provider?: string;+ model?: string;+ effort?: string;+ account_id?: string;}/** Per-agent browser status from `GET /api/society/agents/{id}/browser`. */@@ -204,6 +209,10 @@ export function useAgentRoutines(agentId: string | null) {last_run_ns?: number;prompt?: string;tags?: string[];+ provider?: string;+ model?: string;+ effort?: string;+ account_id?: string;}[];};const raw = body?.routines ?? [];@@ -216,6 +225,10 @@ export function useAgentRoutines(agentId: string | null) {dueMs: nsToMs(r.due_at_ns),lastRunMs: nsToMs(r.last_run_ns),prompt: r.prompt ?? "",+ provider: String(r.provider ?? ""),+ model: String(r.model ?? ""),+ effort: String(r.effort ?? ""),+ account_id: String(r.account_id ?? ""),}));const groups = new Map<string, LiveRoutine[]>();mapped.forEach((row, i) => {diff --git a/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.switch.test.tsx b/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.switch.test.tsxindex 6a735d2375..8ed2f1102c 100644--- a/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.switch.test.tsx+++ b/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.switch.test.tsx@@ -6,6 +6,7 @@ import { EMPTY_TIMELINE, reduceEvents, type Timeline, type UserItem } from "@/coimport type { SocietyAgent } from "../data";import {AgentChatPanel,+ UserBubble,itemsForOpenSession,useSocietyChatStore,setJarvisCardMode,@@ -15,6 +16,7 @@ import { useEventStore } from "@/store/events";import type { AgentChatEvent, AgentChatSession } from "@/lib/agentChatApi";import { useHomeStore } from "@/store/home";import { JarvisHistoryRail } from "./JarvisHistoryRail";+import { useRoutineNavigation } from "./routineNavigation";import * as cardData from "../cardData";vi.mock("@/i18n", () => ({ useT: () => (key: string) => key, fill: (text: string) => text }));@@ -107,6 +109,7 @@ const visual = agent({ agentId: "visual-qa", name: "Visual QA" });const gmail = agent({ agentId: "gmail-agent", name: "Gmail Agent" });beforeEach(() => {+ useRoutineNavigation.getState().close();seq = 0;useTranscriptViewStore.setState({ boundaries: {} });useHomeStore.setState({ transcript: [], liveReply: "", jarvisCardMode: "voice", freshVoicePending: false });@@ -286,6 +289,17 @@ it.each(["specialist", "lead"] as const)("turns send into stop while the %s is rexpect(screen.queryByTestId("composer-stop")).toBeNull();});+it("routine-check opens the clicked execution instead of folding its instruction", () => {+ const text = "Scheduled routine daily. Follow your CURRENT standing instructions and permissions.\nUse your memory and conversation archive for prior results. For information watches, check sources and dates, remember last-seen items, and report only meaningful new findings.\n\nInspect this execution.";+ render(<UserBubble agentId={gmail.agentId} sessionId={gmail.chatSessionId!} item={{ type: "user", id: "u-88", tsMs: 10000, text, attachments: [] }} />);+ expect(useRoutineNavigation.getState().target).toBeNull();+ fireEvent.click(screen.getByRole("button", { name: /routine_check/ }));+ expect(useRoutineNavigation.getState().target).toEqual({+ agentId: gmail.agentId, sessionId: gmail.chatSessionId, title: "Inspect this execution.", timestamp: 10000,+ legacy: { taskId: "daily", messageId: "u-88" },+ });+});+it("shows stop while the send request is in flight, before the turn stream starts", () => {useSocietyChatStore.getState().disconnect();useSocietyChatStore.getState().openSession(gmail.chatSessionId!);diff --git a/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx b/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsxindex 24d9a2d43b..d69b7dd7db 100644--- a/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx+++ b/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx@@ -23,7 +23,10 @@ import { mergeOutgoingMessages, useOutgoingMessages } from "@/components/agentch* runner can drive. The header says so while voice is showing.*/import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";+import { useRoutineNavigation } from "./routineNavigation";import { notifyRoutineChanged } from "../cardData";+import { routineTaskId } from "./routineExecution";+import { RoutineChatHost } from "./RoutineChatHost";import { MessageSquare, Mic, Paperclip, Plus, RotateCcw, Send, Square } from "lucide-react";import { ChatMarkdown, MediaPreview, mediaKind } from "@/components/agentchat/ChatMarkdown";@@ -138,7 +141,12 @@ export function itemsForOpenSession(}export function AgentChatPanel(props: AgentChatPanelProps) {- return <PairConversationBoundary key={props.agent.agentId} recipient={{ id: props.agent.agentId, name: props.agent.name }}><AgentChatPanelContent {...props} /></PairConversationBoundary>;+ const disconnect = useCallback(() => {+ (props.agent.tier === "lead" ? useAgentChatStore : useSocietyChatStore).getState().disconnect();+ }, [props.agent.tier]);+ return <PairConversationBoundary key={props.agent.agentId} recipient={{ id: props.agent.agentId, name: props.agent.name }}>+ <RoutineChatHost agentId={props.agent.agentId} onOpen={disconnect}><AgentChatPanelContent {...props} /></RoutineChatHost>+ </PairConversationBoundary>;}function AgentChatPanelContent({ agent, roster }: AgentChatPanelProps) {@@ -633,6 +641,7 @@ export function Transcript({onDecide: (approvalId: string, decision: ApprovalDecision) => Promise<void>;}) {const t = useT();+ const sessionId = useAgentChat((state) => state.activeSessionId);// Follow the newest while the view sits at the end — the rule every// conversation surface shares (hooks/useStickToBottom). This used to scroll// a bottom sentinel into view on `[items.length, busy]` only, so a@@ -672,7 +681,7 @@ export function Transcript({{item.type === "internal" ? (<AgentMessageActivity item={item} roster={roster} />) : item.type === "user" ? (- <UserBubble item={item} />+ <UserBubble item={item} agentId={agent.agentId} sessionId={sessionId ?? agent.chatSessionId ?? undefined} />) : item.type === "turn" ? (<TurnBubble item={item} onDecide={onDecide} />) : item.type === "notice" ? (@@ -901,13 +910,17 @@ function visibleUserText(text: string): string {.trimEnd();}-export function UserBubble({ item }: { item: UserItem }) {+export function UserBubble({ item, agentId, sessionId }: { item: UserItem; agentId?: string; sessionId?: string }) {const t = useT();const choices = messageChoices(item);const text = visibleUserText(item.text);if (item.origin === "control") return <div className="self-start px-1 py-2 text-xs text-muted-foreground">{t("slash.control_turn")}{item.attachments.map((file) => <span key={file.name} className="ml-2">{file.name}</span>)}</div>;const task = routineTask(item.text);- if (task !== null && item.attachments.length === 0) return <RoutineActivity task={task} original={item.text} />;+ if (task !== null && item.attachments.length === 0) return <RoutineActivity task={task} original={item.text}+ onOpen={agentId && sessionId ? () => useRoutineNavigation.getState().open({+ agentId, sessionId, title: task.split(/\r?\n/)[0], timestamp: item.tsMs,+ ...(!sessionId.includes(":routine:") ? { legacy: { taskId: routineTaskId(item.text)!, messageId: item.id } } : {}),+ }) : undefined} />;return (<div className="flex min-w-0 max-w-[min(85%,42rem)] flex-col items-end gap-1 self-end"><div className="min-w-0 rounded-2xl rounded-br-md bg-secondary px-4 py-2.5 text-sm leading-relaxed text-foreground [overflow-wrap:anywhere]">diff --git a/jarvis/ui/web/frontend/src/components/society/chat/AgentModelPicker.test.tsx b/jarvis/ui/web/frontend/src/components/society/chat/AgentModelPicker.test.tsxindex a170143cdf..2bb87d5e8f 100644--- a/jarvis/ui/web/frontend/src/components/society/chat/AgentModelPicker.test.tsx+++ b/jarvis/ui/web/frontend/src/components/society/chat/AgentModelPicker.test.tsx@@ -279,7 +279,7 @@ test("all connected subscription accounts are selectable for a model", async ()fireEvent.click(screen.getByRole("button", { name: "Account: ChatGPT / Codex subscription" }));expect(screen.queryByRole("menuitemradio", { name: "Expired" })).toBeNull();fireEvent.click(screen.getByRole("menuitemradio", { name: "Personal" }));- fireEvent.click(screen.getByTitle("openai-codex-large"));+ fireEvent.click(await screen.findByTitle("openai-codex-large"));await waitFor(() => expect(posts[0].account_id).toBe("personal"));expect(posts[0].provider).toBe("openai-codex");});diff --git a/jarvis/ui/web/frontend/src/components/society/chat/AgentModelPicker.tsx b/jarvis/ui/web/frontend/src/components/society/chat/AgentModelPicker.tsxindex 503114f571..67bbf51187 100644--- a/jarvis/ui/web/frontend/src/components/society/chat/AgentModelPicker.tsx+++ b/jarvis/ui/web/frontend/src/components/society/chat/AgentModelPicker.tsx@@ -44,7 +44,7 @@ export function AgentModelPicker({ agent, busy, onSavingChange }: {const chatCatalog = useAgentChat((state) => state.surface === "society" ? state.catalog : null);const chatConnections = useAgentChat((state) => state.connections);- const { options, providers, live, loading, refreshing, failed, refresh: refreshData } = useModelMenuData(chatCatalog, chatConnections);+ const { options, providers, live, loading, refreshing, failed, refresh: refreshData } = useModelMenuData(chatCatalog, chatConnections, { [agent.provider]: agent.accountId ?? "", ...accounts });const defaultModelLabel = t("agent_chat.model_default");const seats = useMemo(() => modelSeats(options, providers ?? [], live, defaultModelLabel), [options, providers, live, defaultModelLabel]);const currentAccount = (seat: BrainSeat) => accounts[seat.provider.id] ?? (agent.provider === seat.provider.id ? agent.accountId ?? "" : "");diff --git a/jarvis/ui/web/frontend/src/components/society/chat/ChatActivity.test.tsx b/jarvis/ui/web/frontend/src/components/society/chat/ChatActivity.test.tsxindex bf92d5ce5e..24d8659168 100644--- a/jarvis/ui/web/frontend/src/components/society/chat/ChatActivity.test.tsx+++ b/jarvis/ui/web/frontend/src/components/society/chat/ChatActivity.test.tsx@@ -14,6 +14,8 @@ it("folds only a full scheduler envelope, preserving ordinary user messages", ()expect(routineTask(envelope + "Check the inbox.\nSummarize changes.")).toBe("Check the inbox.\nSummarize changes.");expect(routineTask("Scheduled routine task-123. Please explain this.")).toBeNull();expect(routineTask("Please quote:\n" + envelope)).toBeNull();+ const background = envelope.replace(" and permissions.\n", ".\nThis execution has its own background chat with bypass permissions.\n");+ expect(routineTask(background + "Check the inbox.")).toBe("Check the inbox.");render(<RoutineActivity task={"Check the inbox.\nSummarize changes."} original={envelope + "Check the inbox.\nSummarize changes."} />);expect(screen.queryByText("Summarize changes.")).toBeNull();fireEvent.click(screen.getByRole("button", { name: "Routine check · Check the inbox." }));diff --git a/jarvis/ui/web/frontend/src/components/society/chat/ChatActivity.tsx b/jarvis/ui/web/frontend/src/components/society/chat/ChatActivity.tsxindex 12d3232003..e1a0550861 100644--- a/jarvis/ui/web/frontend/src/components/society/chat/ChatActivity.tsx+++ b/jarvis/ui/web/frontend/src/components/society/chat/ChatActivity.tsx@@ -7,6 +7,7 @@ import { useT } from "@/i18n";import { cn } from "@/lib/utils";import { AgentSwatch } from "../AgentSwatch";import type { SocietyAgent } from "../data";+export { routineTask } from "./routineExecution";/** A quiet event in the conversation; details remain keyboard accessible. */export function ChatActivity({ label, icon, children, failed = false }: {@@ -24,15 +25,12 @@ export function ChatActivity({ label, icon, children, failed = false }: {</div>;}-/** Recognize only the scheduler's complete envelope; ordinary messages stay intact. */-export function routineTask(text: string): string | null {- const envelope = /^Scheduled routine [^\s.]+\. Follow your CURRENT standing instructions and permissions\.\r?\nUse your memory and conversation archive for prior results\. For information watches, check sources and dates, remember last-seen items, and report only meaningful new findings\.\r?\n\r?\n/;- const match = envelope.exec(text);- return match ? text.slice(match[0].length).trim() : null;-}--export function RoutineActivity({ task, original }: { task: string; original: string }) {+export function RoutineActivity({ task, original, onOpen }: { task: string; original: string; onOpen?: () => void }) {const t = useT();+ if (onOpen) return <button type="button" onClick={onOpen}+ className="mx-auto my-3 flex max-w-[min(100%,36rem)] items-center gap-2 rounded-md px-2 py-1.5 text-left text-xs text-muted-foreground hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">+ <Clock3 aria-hidden className="h-3.5 w-3.5 shrink-0" /><span className="truncate">{t("society.chat.routine_check")} · {task.split(/\r?\n/)[0]}</span><ChevronRight aria-hidden className="h-3 w-3 shrink-0" />+ </button>;return <ChatActivity label={<>{t("society.chat.routine_check")} · {task.split(/\r?\n/)[0]}</>} icon={<Clock3 aria-hidden className="h-3.5 w-3.5 shrink-0" />}><ChatMarkdown text={task} /><details className="mt-2 text-xs"><summary className="cursor-pointer">{t("society.chat.activity_details")}</summary><p className="mt-2 whitespace-pre-wrap">{original}</p></details>diff --git a/jarvis/ui/web/frontend/src/components/society/chat/RoutineChatHost.tsx b/jarvis/ui/web/frontend/src/components/society/chat/RoutineChatHost.tsxnew file mode 100644index 0000000000..8e60eb50d2--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/chat/RoutineChatHost.tsx@@ -0,0 +1,21 @@+import { lazy, Suspense, useEffect, type ReactNode } from "react";+import { useT } from "@/i18n";+import { useRoutineNavigation } from "./routineNavigation";++const RoutineChat = lazy(() => import("../card/RoutineChat"));++export function RoutineChatHost({ agentId, onOpen, children }: {+ agentId: string; onOpen: () => void; children: ReactNode;+}) {+ const t = useT();+ const target = useRoutineNavigation((state) => state.target);+ const close = useRoutineNavigation((state) => state.close);+ const selected = target?.agentId === agentId ? target : null;+ useEffect(() => { if (selected) onOpen(); }, [selected, onOpen]);+ useEffect(() => () => {+ if (useRoutineNavigation.getState().target?.agentId === agentId) close();+ }, [close, agentId]);+ return selected ? <Suspense fallback={<p role="status" className="p-4 text-sm">{t("tasks_view.loading_details")}</p>}>+ <RoutineChat key={`${selected.sessionId}:${selected.legacy?.messageId ?? selected.timestamp}`} target={selected} onClose={close} />+ </Suspense> : children;+}diff --git a/jarvis/ui/web/frontend/src/components/society/chat/routineExecution.test.ts b/jarvis/ui/web/frontend/src/components/society/chat/routineExecution.test.tsnew file mode 100644index 0000000000..73c1c28418--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/chat/routineExecution.test.ts@@ -0,0 +1,46 @@+import { expect, test } from "vitest";+import type { AgentChatEvent } from "@/lib/agentChatApi";+import { legacyRoutineEvents, routineTask, routineTaskId, type RoutineChatTarget } from "./routineExecution";++export const instruction = (id: string) => `Scheduled routine ${id}. Follow your CURRENT standing instructions and permissions.\nUse your memory and conversation archive for prior results. For information watches, check sources and dates, remember last-seen items, and report only meaningful new findings.\n\nCheck this run.`;++function run(seq: number, start: number, id: string, answer: string): AgentChatEvent[] {+ const turn = `turn-${seq}`;+ return [+ { seq, ts_ms: start, kind: "user_message", payload: { text: instruction(id) } },+ { seq: seq + 1, ts_ms: start + 10, kind: "turn_started", payload: { turn_id: turn } },+ { seq: seq + 2, ts_ms: start + 20, kind: "tool_call", payload: { turn_id: turn, name: "read", call_id: turn } },+ { seq: seq + 3, ts_ms: start + 30, kind: "assistant_text", payload: { turn_id: turn, text: answer } },+ { seq: seq + 4, ts_ms: start + 1000, kind: "turn_finished", payload: { turn_id: turn, status: "done" } },+ ];+}++const target: RoutineChatTarget = { agentId: "mail", sessionId: "society:mail", title: "Inbox", timestamp: 10000,+ legacy: { taskId: "daily", startedMs: 9900, finishedMs: 11100 } };+const first = run(1, 10000, "daily", "FIRST RUN");+const second = run(10, 100000, "daily", "SECOND RUN");++test("history selects the matching execution, including tools, without other conversations", () => {+ expect(legacyRoutineEvents([...first, ...second], target)).toEqual(first);+});++test("routine-check navigation uses the exact message even for an identical later prompt", () => {+ expect(legacyRoutineEvents([...first, ...second], { ...target, legacy: { taskId: "daily", messageId: "u-10" } })).toEqual(second);+});++test("missing and ambiguous executions never fall back to a different run", () => {+ expect(legacyRoutineEvents(second, target)).toEqual([]);+ expect(legacyRoutineEvents([...first, ...run(20, 10500, "daily", "ambiguous")], target)).toEqual([]);+ expect(legacyRoutineEvents(first, { ...target, legacy: { taskId: "other", messageId: "u-1" } })).toEqual([]);+});++test("old result-only steps match their completion time, not the latest prompt", () => {+ expect(legacyRoutineEvents([...first, ...second], { ...target, legacy: { taskId: "daily", finishedMs: 11020 } })).toEqual(first);+});++test("ordinary messages and notices cannot become execution links", () => {+ expect(routineTaskId("Scheduled routine daily. Explain this text.")).toBeNull();+ expect(routineTask(instruction("daily"))).toBe("Check this run.");+ const notice: AgentChatEvent = { seq: 200, ts_ms: 10500, kind: "notice", payload: { text: "PRIVATE unrelated notice" } };+ expect(legacyRoutineEvents([...first.slice(0, 2), notice, ...first.slice(2), ...second], target)).toEqual(first);+});diff --git a/jarvis/ui/web/frontend/src/components/society/chat/routineExecution.ts b/jarvis/ui/web/frontend/src/components/society/chat/routineExecution.tsnew file mode 100644index 0000000000..6c65dd4fce--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/chat/routineExecution.ts@@ -0,0 +1,59 @@+import type { AgentChatEvent } from "@/lib/agentChatApi";++export interface RoutineChatTarget {+ agentId: string;+ sessionId: string;+ title: string;+ timestamp: number;+ result?: string;+ legacy?: {+ taskId: string;+ messageId?: string;+ startedMs?: number;+ finishedMs?: number;+ };+}++/** Only a complete scheduler envelope is a routine, never a similar user message. */+const envelope = /^Scheduled routine ([^\s.]+)\. Follow your CURRENT standing instructions(?: and permissions)?\.\r?\n(?:This execution has its own background chat with bypass permissions\.\r?\n)?Use your memory and conversation archive for prior results\. For information watches, check sources and dates, remember last-seen items, and report only meaningful new findings\.\r?\n\r?\n/;++export function routineTask(text: string): string | null {+ const match = envelope.exec(text);+ return match ? text.slice(match[0].length).trim() : null;+}++export function routineTaskId(text: string): string | null {+ return envelope.exec(text)?.[1] ?? null;+}++/** Read the exact old turn; never substitute the latest turn or the whole main chat. */+export function legacyRoutineEvents(events: AgentChatEvent[], target: RoutineChatTarget): AgentChatEvent[] {+ const legacy = target.legacy;+ if (!legacy) return [];+ const matches: AgentChatEvent[][] = [];+ for (let index = 0; index < events.length; index += 1) {+ const message = events[index];+ if (message.kind !== "user_message" || routineTaskId(String(message.payload.text ?? "")) !== legacy.taskId) continue;+ if (legacy.messageId && legacy.messageId !== `u-${message.seq || message.ts_ms}`) continue;+ let next = index + 1;+ while (next < events.length && events[next].kind !== "user_message") next += 1;+ const span = events.slice(index + 1, next);+ const turn = span.find((event) => event.kind === "turn_started");+ if (!turn?.payload.turn_id) continue;+ const own = span.filter((event) => event.payload.turn_id === turn.payload.turn_id);+ if (!legacy.messageId) {+ // Task steps and chat messages share the local clock. A small allowance+ // covers timestamp rounding, not another daily run of the same prompt.+ if (legacy.startedMs !== undefined) {+ if (message.ts_ms < legacy.startedMs - 2000) continue;+ if (legacy.finishedMs === undefined || message.ts_ms > legacy.finishedMs + 2000) continue;+ } else {+ const finished = own.find((event) => event.kind === "turn_finished");+ if (!finished || legacy.finishedMs === undefined || Math.abs(finished.ts_ms - legacy.finishedMs) > 5000) continue;+ }+ }+ matches.push([message, ...own]);+ }+ // Ambiguous timestamps are not permission to show a different execution.+ return matches.length === 1 ? matches[0] : [];+}diff --git a/jarvis/ui/web/frontend/src/components/society/chat/routineNavigation.ts b/jarvis/ui/web/frontend/src/components/society/chat/routineNavigation.tsnew file mode 100644index 0000000000..2b4fd8424c--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/chat/routineNavigation.ts@@ -0,0 +1,13 @@+import { create } from "zustand";+import type { RoutineChatTarget } from "./routineExecution";++/** Navigation only: opening the selected chat is the host's lazy responsibility. */+export const useRoutineNavigation = create<{+ target: RoutineChatTarget | null;+ open: (target: RoutineChatTarget) => void;+ close: () => void;+}>((set) => ({+ target: null,+ open: (target) => set({ target }),+ close: () => set({ target: null }),+}));diff --git a/jarvis/ui/web/frontend/src/components/society/chat/useModelMenuData.accounts.test.tsx b/jarvis/ui/web/frontend/src/components/society/chat/useModelMenuData.accounts.test.tsxnew file mode 100644index 0000000000..551b28d440--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/chat/useModelMenuData.accounts.test.tsx@@ -0,0 +1,43 @@+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { act, cleanup, renderHook, waitFor } from "@testing-library/react";+import { afterEach, expect, test, vi } from "vitest";+import type { ReactNode } from "react";+import type { AgentChatCatalog } from "@/lib/agentChatApi";+import { useModelMenuData } from "./useModelMenuData";+import { clearModelMenuSnapshot } from "./modelMenuSnapshot";++afterEach(() => { cleanup(); clearModelMenuSnapshot(); vi.unstubAllGlobals(); });++test("changing a pinned account hides the previous models until that account replies", async () => {+ clearModelMenuSnapshot();+ let release!: () => void;+ const secondAccount = new Promise<void>((resolve) => { release = resolve; });+ vi.stubGlobal("fetch", vi.fn(async (url: string) => {+ if (url.includes("/catalog")) {+ const account = new URL(url, "http://localhost").searchParams.get("account_id");+ if (account === "second") await secondAccount;+ const model = account ? `${account}-only` : "default-account-only";+ return new Response(JSON.stringify({ providers: [{+ id: "openai-codex", label: "Codex", family: "openai", runner: "codex-cli",+ cli_installed: true, models_source: "curated", curated_models: [{ id: model, label: model }],+ keyless: false, native_resume: false,+ default_model: "", effort_levels: [], default_effort: "", permission_modes: [], default_permission_mode: "plan",+ }], default_cwd: "", shell: "" } satisfies Partial<AgentChatCatalog>));+ }+ if (url.includes("/jarvis-agent/status")) return new Response(JSON.stringify({ mapping: [] }));+ return new Response(JSON.stringify({ providers: [] }));+ }));+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ const wrapper = ({ children }: { children: ReactNode }) => <QueryClientProvider client={client}>{children}</QueryClientProvider>;+ const { result, rerender } = renderHook(({ account }) => useModelMenuData(null, [], { "openai-codex": account }), {+ wrapper, initialProps: { account: "first" },+ });+ const models = () => result.current.options.find((row) => row.id === "openai-codex")?.curated_models.map((row) => row.id);+ await waitFor(() => expect(models()).toEqual(["first-only"]));+ rerender({ account: "second" });+ expect(models()).toEqual([]);+ expect(result.current.loading).toBe(true);+ await act(async () => { release(); await secondAccount; });+ await waitFor(() => expect(models()).toEqual(["second-only"]));+ client.clear();+});diff --git a/jarvis/ui/web/frontend/src/components/society/chat/useModelMenuData.ts b/jarvis/ui/web/frontend/src/components/society/chat/useModelMenuData.tsindex 67572e125b..910500362d 100644--- a/jarvis/ui/web/frontend/src/components/society/chat/useModelMenuData.ts+++ b/jarvis/ui/web/frontend/src/components/society/chat/useModelMenuData.ts@@ -10,19 +10,48 @@ const EMPTY_CONNECTIONS: AgentConnectionRow[] = [];const QUERY_POLICY = { staleTime: 60_000, gcTime: 30 * 60_000, refetchOnWindowFocus: false };/** Prepare once at the Agents view; the card reuses the same query instances. */-export function useModelMenuData(chatCatalog: AgentChatCatalog | null = null, chatConnections = EMPTY_CONNECTIONS) {+export function useModelMenuData(chatCatalog: AgentChatCatalog | null = null, chatConnections = EMPTY_CONNECTIONS, accountIds: Record<string, string> = {}) {const client = useQueryClient();const previousChatCatalog = useRef(chatCatalog);const [saved] = useState(readModelMenuSnapshot);const catalog = useQuery({ queryKey: ["agent-chat", "catalog", "society"], queryFn: () => fetchAgentChatCatalog("society"),- initialData: saved?.catalog, initialDataUpdatedAt: saved?.savedAt, placeholderData: chatCatalog ?? undefined, ...QUERY_POLICY });+ initialData: saved?.catalog, initialDataUpdatedAt: saved?.savedAt, ...QUERY_POLICY });const connections = useQuery({ queryKey: ["agent-chat", "connections"], queryFn: fetchAgentConnections,initialData: saved?.connections, initialDataUpdatedAt: saved?.savedAt, placeholderData: chatCatalog ? chatConnections : undefined, ...QUERY_POLICY });const providers = useQuery({ queryKey: ["society", "providers"], queryFn: fetchSocietyProviders,initialData: saved?.providers, initialDataUpdatedAt: saved?.savedAt, ...QUERY_POLICY });- const availableCatalog = catalog.data ?? chatCatalog;+ const fallbackCatalog = useMemo(() => chatCatalog ? { ...chatCatalog, providers: chatCatalog.providers.map((provider) =>+ provider.runner.endsWith("-cli") ? { ...provider, curated_models: [] } : provider,+ ) } : undefined, [chatCatalog]);+ const availableCatalog = catalog.data ?? fallbackCatalog;const availableConnections = connections.data ?? (chatCatalog ? chatConnections : undefined);- const options = useMemo(() => joinProviderOptions(availableCatalog?.providers ?? [], availableConnections ?? []), [availableCatalog, availableConnections]);+ const cliProviders = new Set((availableCatalog?.providers ?? []).filter((provider) => provider.runner.endsWith("-cli")).map((provider) => provider.id));+ const scopedIds = [...new Set(Object.entries(accountIds).filter(([provider, account]) => cliProviders.has(provider) && account).map(([, account]) => account))].sort();+ const scopeKey = JSON.stringify(scopedIds);+ const accountKey = JSON.stringify(accountIds);+ const combineScoped = useCallback((queries: UseQueryResult<AgentChatCatalog, Error>[]) => ({+ data: Object.fromEntries(queries.map((query, index) => [(JSON.parse(scopeKey) as string[])[index], query.data])),+ pending: queries.some((query) => query.isPending),+ fetching: queries.some((query) => query.isFetching),+ failed: queries.some((query) => query.isError),+ refresh: () => Promise.all(queries.map((query) => query.refetch())),+ }), [scopeKey]);+ const scopedCatalogs = useQueries({ queries: scopedIds.map((accountId) => ({+ queryKey: ["agent-chat", "catalog", "society", accountId],+ queryFn: () => fetchAgentChatCatalog("society", { accountId }),+ ...QUERY_POLICY,+ })), combine: combineScoped });+ const options = useMemo(() => {+ const seats = JSON.parse(accountKey) as Record<string, string>;+ // Never display a different login's models while a pinned seat is loading.+ const rows = (availableCatalog?.providers ?? []).map((provider) => {+ const accountId = seats[provider.id];+ if (!accountId || !provider.runner.endsWith("-cli")) return provider;+ return scopedCatalogs.data[accountId]?.providers.find((row) => row.id === provider.id)+ ?? { ...provider, curated_models: [] };+ });+ return joinProviderOptions(rows, availableConnections ?? []);+ }, [availableCatalog, availableConnections, accountKey, scopedCatalogs.data]);const liveProviders = useMemo(() => options.filter((option) => option.connected && option.models_source === "live"), [options]);const combine = useCallback((queries: UseQueryResult<CuratedModel[], Error>[]) => ({live: Object.fromEntries(queries.flatMap((query, index) => query.data ? [[liveProviders[index].id, query.data]] : [])) as Record<string, CuratedModel[]>,@@ -41,27 +70,27 @@ export function useModelMenuData(chatCatalog: AgentChatCatalog | null = null, chif (chatCatalog && previousChatCatalog.current !== chatCatalog) {// A fresh chat-store load after a key/account change supersedes the// display snapshot, including providers that have just disconnected.- client.setQueryData(["agent-chat", "catalog", "society"], chatCatalog);+ void client.invalidateQueries({ queryKey: ["agent-chat", "catalog", "society"] });client.setQueryData(["agent-chat", "connections"], chatConnections);}previousChatCatalog.current = chatCatalog;}, [client, chatCatalog, chatConnections]);useEffect(() => {- if (!availableCatalog || !availableConnections || !providers.data) return;+ if (!catalog.data || !availableConnections || !providers.data) return;// Coalesce independently arriving lists; never stringify during the click.const timer = window.setTimeout(() => writeModelMenuSnapshot({version: 1, savedAt: Math.min(catalog.dataUpdatedAt || Date.now(), connections.dataUpdatedAt || Date.now(), providers.dataUpdatedAt || Date.now()),- catalog: availableCatalog, connections: availableConnections, providers: providers.data!, live: models.live, liveUpdatedAt: models.updatedAt,+ catalog: catalog.data!, connections: availableConnections, providers: providers.data!, live: models.live, liveUpdatedAt: models.updatedAt,}), 100);return () => window.clearTimeout(timer);- }, [availableCatalog, availableConnections, providers.data, models.live, models.updatedAt, catalog.dataUpdatedAt, connections.dataUpdatedAt, providers.dataUpdatedAt]);+ }, [catalog.data, availableConnections, providers.data, models.live, models.updatedAt, catalog.dataUpdatedAt, connections.dataUpdatedAt, providers.dataUpdatedAt]);return {options, live: models.live, providers: providers.data,- loading: !availableCatalog || !availableConnections,- refreshing: catalog.isFetching || connections.isFetching || providers.isFetching || models.fetching,- failed: (!availableCatalog && catalog.isError) || (!availableConnections && connections.isError),- refresh: () => Promise.all([catalog.refetch(), connections.refetch(), providers.refetch(), models.refresh()]),+ loading: !availableCatalog || !availableConnections || scopedCatalogs.pending,+ refreshing: scopedCatalogs.fetching || catalog.isFetching || connections.isFetching || providers.isFetching || models.fetching,+ failed: scopedCatalogs.failed || (!availableCatalog && catalog.isError) || (!availableConnections && connections.isError),+ refresh: () => Promise.all([catalog.refetch(), connections.refetch(), providers.refetch(), models.refresh(), scopedCatalogs.refresh()]),};}diff --git a/jarvis/ui/web/frontend/src/components/society/companion/AgentAppearanceDialog.test.tsx b/jarvis/ui/web/frontend/src/components/society/companion/AgentAppearanceDialog.test.tsxnew file mode 100644index 0000000000..657802ac13--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/companion/AgentAppearanceDialog.test.tsx@@ -0,0 +1,71 @@+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { afterEach, expect, it, vi } from "vitest";+import { AgentAppearanceDialog } from "./AgentAppearanceDialog";+import { SAMPLE_ROSTER } from "../mockRoster";+import { defaultCompanion } from "./appearance";++vi.mock("@/i18n", () => ({ useT: () => (key: string) => key }));+vi.mock("./CompanionPreview", () => ({ CompanionPreview: () => <div data-testid="preview" /> }));+vi.mock("../figures/AgentFigureViewer", () => ({ AgentFigureViewer: () => <div data-testid="character-preview" /> }));+afterEach(() => { cleanup(); vi.unstubAllGlobals(); });++function setup(fail = false, legacy = false) {+ const original = SAMPLE_ROSTER.find(a => a.tier !== "lead")!;+ const figure = legacy ? { contract: 1 as const, archetype: "biped" as const, base: "rogue", parts: {} } : original.figure!;+ const agent = { ...original, agentId: "appearance-test", figure: { ...figure, companion: { ...defaultCompanion("test"), shape: "circle" as const } } };+ const close = vi.fn();+ const fetcher = vi.fn(async () => new Response(JSON.stringify({ agent }), { status: fail ? 500 : 200 }));+ vi.stubGlobal("fetch", fetcher);+ render(<QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } })}><AgentAppearanceDialog agent={agent} sample={false} onClose={close} /></QueryClientProvider>);+ return { agent, fetcher, close };+}++it("saves companion edits without overwriting character parts or other agent fields", async () => {+ const { agent, fetcher } = setup();+ fireEvent.click(screen.getByRole("button", { name: "society.companion.shapes.cloud" }));+ fireEvent.click(screen.getByRole("button", { name: "society.card.save" }));+ await waitFor(() => expect(fetcher).toHaveBeenCalledOnce());+ const [, init] = fetcher.mock.calls[0] as unknown as [string, RequestInit];+ const body = JSON.parse(init.body as string);+ expect(Object.keys(body)).toEqual(["avatar"]);+ expect(body.avatar.companion.shape).toBe("cloud");+ expect(body.avatar.parts).toEqual(agent.figure?.parts);+ expect(body.avatar.base).toBe(agent.figure?.base);+});++it("protects an unsaved companion after a rejected save", async () => {+ const { close } = setup(true);+ fireEvent.click(screen.getByRole("button", { name: "society.companion.shapes.cloud" }));+ fireEvent.click(screen.getByRole("button", { name: "society.card.save" }));+ await screen.findByRole("alert");+ expect(screen.getByRole("button", { name: "society.companion.shapes.cloud" }).getAttribute("aria-pressed")).toBe("true");+ fireEvent.click(screen.getAllByRole("button", { name: "society.card.close" })[0]);+ expect(close).not.toHaveBeenCalled();+ expect(screen.getByText("society.profile_card.unsaved")).toBeTruthy();+});++it("keeps the companion choice while editing the character", async () => {+ setup();+ fireEvent.click(screen.getByRole("button", { name: "society.companion.shapes.cloud" }));+ fireEvent.click(screen.getByRole("tab", { name: "society.companion.character" }));+ await screen.findByTestId("character-preview");+ fireEvent.click(screen.getByRole("tab", { name: "society.companion.companion" }));+ expect(screen.getByRole("button", { name: "society.companion.shapes.cloud" }).getAttribute("aria-pressed")).toBe("true");+});++it("keeps shape customization without size or following-distance sliders", () => {+ setup();+ expect(screen.queryByRole("slider")).toBeNull();+ expect(screen.queryByText("society.companion.size")).toBeNull();+ expect(screen.queryByText("society.companion.distance")).toBeNull();+ expect(screen.getByRole("button", { name: "society.companion.shapes.cloud" })).toBeTruthy();+});++it("finds the character's actual style for older recipes without style metadata", async () => {+ setup(false, true);+ fireEvent.click(screen.getByRole("tab", { name: "society.companion.character" }));+ await screen.findByTestId("character-preview");+ expect((screen.getByLabelText("society.create.style") as HTMLSelectElement).value).toBe("fantasy");+ expect((screen.getByLabelText("society.create.base") as HTMLSelectElement).value).toBe("rogue");+});diff --git a/jarvis/ui/web/frontend/src/components/society/companion/AgentAppearanceDialog.tsx b/jarvis/ui/web/frontend/src/components/society/companion/AgentAppearanceDialog.tsxnew file mode 100644index 0000000000..e20b1b80ce--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/companion/AgentAppearanceDialog.tsx@@ -0,0 +1,83 @@+import { useRef, useState, Suspense, lazy } from "react";+import * as Dialog from "@radix-ui/react-dialog";+import { useQueryClient } from "@tanstack/react-query";+import { X } from "lucide-react";+import { useT } from "@/i18n";+import { Button } from "@/components/ui/button";+import type { SocietyAgent } from "../data";+import { AgentSwatch } from "../AgentSwatch";+import { defaultRecipe, EDITABLE_CELLS, resolvePalette, type FigureRecipe } from "../figures/figureRecipe";+import { basesForStyle, CATALOG, catalogBaseFor, isReservedStyle, keepablePartsFor, partsForSlot, slotsWithParts, stylesWithBases } from "../figures/figureRegistry";+import { CompanionEditor } from "./CompanionEditor";+import { resolveCompanion } from "./appearance";++const AgentFigureViewer = lazy(() => import("../figures/AgentFigureViewer").then(m => ({ default: m.AgentFigureViewer })));+const selectClass = "min-w-0 rounded-md border border-border bg-background p-2 text-sm text-foreground";++function CharacterEditor({ value, onChange, disabled, lead }: { value: FigureRecipe; onChange: (r: FigureRecipe) => void; disabled: boolean; lead: boolean }) {+ const t = useT();+ const base = catalogBaseFor(value);+ const style = value.model ? "custom" : value.style && base?.styles.includes(value.style) ? value.style : base?.styles[0] ?? "modern";+ const availableStyles = [...stylesWithBases(), ...(lead || isReservedStyle(style) ? ["spirit"] : [])];+ const colors = resolvePalette(value);+ const selectBase = (id: string, nextStyle: string) => {+ const entry = CATALOG.bases.find(b => b.base === id);+ if (!entry) return;+ const { model: _model, ...rest } = value;+ onChange({ ...rest, base: entry.base, archetype: entry.archetype, style: nextStyle,+ heightM: entry.heightM, parts: keepablePartsFor(value.parts, entry.archetype, nextStyle, entry.family ?? null, entry.fitSize ?? null) });+ };+ const slots = value.model ? [] : slotsWithParts(value.archetype, style, base?.family ?? null, base?.fitSize ?? null);+ return <fieldset disabled={disabled} className="grid gap-4 p-4" data-testid="character-editor">+ <div className="h-60"><Suspense fallback={null}><AgentFigureViewer recipe={value} quiet /></Suspense></div>+ <label className="grid grid-cols-[6rem_1fr] items-center gap-3 text-sm">{t("society.create.style")}<select aria-label={t("society.create.style")} className={selectClass} value={style} onChange={e => {+ const first = basesForStyle(e.target.value)[0]; if (first) selectBase(first.base, e.target.value);+ }}>{availableStyles.map(s => <option key={s} value={s}>{t(`society.style.${s}`)}</option>)}{value.model && <option value={style}>{t("society.style.custom")}</option>}</select></label>+ {!value.model && <label className="grid grid-cols-[6rem_1fr] items-center gap-3 text-sm">{t("society.create.base")}<select aria-label={t("society.create.base")} className={selectClass} value={value.base} onChange={e => selectBase(e.target.value, style)}>+ {basesForStyle(style).map(b => <option key={b.id} value={b.base}>{b.label}</option>)}+ </select></label>}+ {slots.map(slot => <label key={slot} className="grid grid-cols-[6rem_1fr] items-center gap-3 text-sm">{t(`society.slot.${slot}`)}<select className={selectClass} value={value.parts[slot] ?? ""} onChange={e => {+ const parts = { ...value.parts }; if (e.target.value) parts[slot] = e.target.value; else delete parts[slot]; onChange({ ...value, parts });+ }}><option value="">{t("society.create.none")}</option>{partsForSlot(slot, value.archetype, style, base?.family ?? null, base?.fitSize ?? null).map(p => <option key={p.id} value={p.id}>{p.label}</option>)}</select></label>)}+ <div className="grid grid-cols-2 gap-3">{EDITABLE_CELLS.map(cell => <label key={cell} className="flex items-center justify-between gap-2 text-sm">{t(`society.cell.${cell}`)}<input type="color" value={colors[cell]} onChange={e => onChange({ ...value, palette: { ...value.palette, [cell]: e.target.value } })} className="h-8 w-10 rounded border border-border bg-background" /></label>)}</div>+ <label className="text-sm">{t("society.create.height")} <span className="float-right">{(value.heightM ?? base?.heightM ?? 1.75).toFixed(2)} m</span>+ <input className="mt-2 w-full" type="range" min={0.6} max={2.4} step={0.05} value={value.heightM ?? base?.heightM ?? 1.75} onChange={e => onChange({ ...value, heightM: Number(e.target.value) })} />+ </label>+ </fieldset>;+}++export function AgentAppearanceDialog({ agent, sample, onClose }: { agent: SocietyAgent; sample: boolean; onClose: () => void }) {+ const t = useT();+ const client = useQueryClient();+ const [recipe, setRecipe] = useState<FigureRecipe>(() => ({ ...(agent.figure ?? defaultRecipe()), companion: resolveCompanion(agent.agentId, agent.figure?.companion) }));+ const [saved, setSaved] = useState(() => JSON.stringify(recipe));+ const [tab, setTab] = useState<"character" | "companion">("companion");+ const [saving, setSaving] = useState(false);+ const [error, setError] = useState(false);+ const [discard, setDiscard] = useState(false);+ const opener = useRef(document.activeElement instanceof HTMLElement ? document.activeElement : null);+ const dirty = JSON.stringify(recipe) !== saved;+ const close = () => { if (saving) return; if (dirty) setDiscard(true); else onClose(); };+ const save = async () => {+ setSaving(true); setError(false);+ try {+ const response = await fetch(`/api/society/agents/${encodeURIComponent(agent.agentId)}`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ avatar: recipe }) });+ if (!response.ok) throw new Error(`appearance ${response.status}`);+ setSaved(JSON.stringify(recipe)); setDiscard(false);+ await Promise.all([client.invalidateQueries({ queryKey: ["society", "roster"] }), client.invalidateQueries({ queryKey: ["mars"] })]);+ } catch { setError(true); } // Keep the draft and display the recoverable failure.+ finally { setSaving(false); }+ };+ return <Dialog.Root open onOpenChange={open => { if (!open) close(); }}><Dialog.Portal>+ <Dialog.Overlay className="fixed inset-0 z-50 bg-scrim/60 backdrop-blur-sm" />+ <Dialog.Content data-testid="agent-appearance-dialog" onCloseAutoFocus={e => { e.preventDefault(); opener.current?.focus(); }} className="fixed left-1/2 top-1/2 z-50 flex max-h-[90dvh] w-[min(640px,calc(100vw-24px))] -translate-x-1/2 -translate-y-1/2 flex-col overflow-hidden rounded-xl border border-border bg-popover text-foreground shadow-float">+ <header className="flex items-center gap-3 border-b border-border p-4"><AgentSwatch agent={{ ...agent, figure: recipe }} size={48} /><div className="flex-1"><Dialog.Title className="font-semibold">{agent.name}</Dialog.Title><Dialog.Description className="text-sm text-muted-foreground">{t("society.companion.appearance")}</Dialog.Description></div><button aria-label={t("society.card.close")} onClick={close} className="rounded p-2 hover:bg-secondary"><X size={18} /></button></header>+ <div className="flex shrink-0 gap-2 border-b border-border p-3" role="tablist" aria-label={t("society.companion.appearance")}>{(["character", "companion"] as const).map(value => <button key={value} type="button" role="tab" aria-selected={tab === value} onClick={() => setTab(value)} className={`rounded-md px-3 py-2 text-sm ${tab === value ? "bg-secondary text-foreground" : "text-muted-foreground"}`}>{t(`society.companion.${value}`)}</button>)}</div>+ <div className="min-h-0 overflow-y-auto">{tab === "character" ? <CharacterEditor value={recipe} onChange={setRecipe} disabled={saving || sample} lead={agent.tier === "lead"} /> : <CompanionEditor value={resolveCompanion(agent.agentId, recipe.companion)} onChange={companion => setRecipe(r => ({ ...r, companion }))} disabled={saving || sample} lead={agent.tier === "lead"} />}</div>+ <footer className="flex shrink-0 flex-wrap justify-end gap-2 border-t border-border p-4">+ {error && <p role="alert" className="w-full text-sm text-destructive">{t("society.profile_card.save_error")}</p>}+ {discard ? <><span className="mr-auto text-sm" role="alert">{t("society.profile_card.unsaved")}</span><Button variant="ghost" onClick={() => setDiscard(false)}>{t("society.profile_card.keep_editing")}</Button><Button variant="secondary" onClick={onClose}>{t("society.profile_card.discard")}</Button></> : <><Button variant="ghost" onClick={close} disabled={saving}>{t("society.card.close")}</Button><Button onClick={() => void save()} disabled={!dirty || saving || sample}>{t(saving ? "society.card.saving" : "society.card.save")}</Button></>}+ </footer>+ </Dialog.Content>+ </Dialog.Portal></Dialog.Root>;+}diff --git a/jarvis/ui/web/frontend/src/components/society/companion/AgentFollower.tsx b/jarvis/ui/web/frontend/src/components/society/companion/AgentFollower.tsxnew file mode 100644index 0000000000..cb18f795c4--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/companion/AgentFollower.tsx@@ -0,0 +1,88 @@+import { Component, Suspense, useEffect, useMemo, useRef, type ReactNode, type RefObject } from "react";+import { useGLTF } from "@react-three/drei";+import { useFrame, useThree } from "@react-three/fiber";+import { Group, Mesh, MeshStandardMaterial, Vector3 } from "three";+import { useReducedMotion } from "framer-motion";+import companionModels from "@/assets/society/companions/companions.glb";+import gigiModel from "@/assets/society/companions/gigi.glb";+import { companionEyeColors, type CompanionAppearance } from "./appearance";+import { advancePetTrail, createPetTrail, petDisplayPosition, recordOwner, type PetTrail, type TrailPoint } from "./trail";++class PetBoundary extends Component<{ children: ReactNode }, { failed: boolean }> {+ state = { failed: false };+ static getDerivedStateFromError() { return { failed: true }; }+ componentDidCatch(error: Error) { console.warn("Companion asset unavailable", error); }+ render() { return this.state.failed ? null : this.props.children; }+}++/** A cached authored mesh, with instance-owned materials and no extra canvas. */+export function CompanionModel({ appearance, lead = false }: { appearance: CompanionAppearance; lead?: boolean }) {+ const { scene } = useGLTF(lead ? gigiModel : companionModels);+ const instance = useMemo(() => {+ const original = lead ? scene : scene.getObjectByName(appearance.shape);+ if (!original) throw new Error("Companion silhouette missing from asset");+ const model = original.clone(true);+ const materials: MeshStandardMaterial[] = [];+ if (!lead) {+ const ink = companionEyeColors(appearance.color);+ const body = new MeshStandardMaterial({ color: appearance.color, roughness: 0.82 });+ const eyes = new MeshStandardMaterial({ color: ink.eye, roughness: 1 });+ const shine = new MeshStandardMaterial({ color: ink.highlight, roughness: 1 });+ materials.push(body, eyes, shine);+ model.traverse(object => {+ const mesh = object as Mesh;+ if (!mesh.isMesh) return;+ const name = mesh.name;+ mesh.castShadow = true;+ mesh.visible = name.includes("Dots") ? appearance.eyes === "dots" : name.includes("Lines") ? appearance.eyes === "lines" : !name.includes("Highlight");+ mesh.material = name.includes("Body") ? body : name.includes("Highlight") ? shine : eyes;+ });+ }+ return { model, materials };+ }, [scene, lead, appearance.shape, appearance.color, appearance.eyes]);+ useEffect(() => () => { instance.materials.forEach(material => material.dispose()); }, [instance]);+ // Gigi's authored body is 0.4 m; the symbol master is exactly 1 m.+ return <primitive object={instance.model} scale={appearance.sizeM / (lead ? 0.4 : 1)} dispose={null} />;+}++/** Sibling of the character: world-space footsteps never inherit its rotation. */+export function AgentFollower({ owner, appearance, paused, lead = false, waypoint, initialPosition, clear }: {+ owner: RefObject<Group>; appearance: CompanionAppearance; paused: boolean; lead?: boolean;+ waypoint?: { current: TrailPoint | null };+ /** A nearby point on the owner's verified navigation segment, when known. */+ initialPosition?: TrailPoint;+ clear?: (point: TrailPoint, radius: number) => boolean;+}) {+ const root = useRef<Group>(null);+ const motion = useRef<PetTrail | null>(null);+ const scratch = useMemo(() => new Vector3(), []);+ const phase = useRef(0);+ const reduced = useReducedMotion() ?? false;+ const { invalidate } = useThree();+ useEffect(() => { motion.current = null; invalidate(); }, [appearance.enabled, invalidate]);+ useFrame((_, delta) => {+ if (!root.current || !owner.current) return;+ root.current.visible = appearance.enabled && owner.current.visible;+ if (!root.current.visible || paused) return;+ owner.current.getWorldPosition(scratch);+ const point: TrailPoint = [scratch.x, scratch.y, scratch.z];+ let trail = motion.current ?? (motion.current = createPetTrail(initialPosition ?? point));+ if (!recordOwner(trail, point, waypoint?.current ?? undefined) && initialPosition) {+ // A delayed snapshot must not put the pet inside the character. The map+ // supplies an already verified nearby segment point for re-placement.+ trail = motion.current = createPetTrail(initialPosition);+ recordOwner(trail, point);+ }+ if (waypoint) waypoint.current = null;+ advancePetTrail(trail, appearance.followDistanceM, delta);+ if (!reduced) phase.current += Math.min(delta, 0.1) * trail.speed * 9;+ const bob = reduced || trail.speed < 0.02 ? 0 : Math.abs(Math.sin(phase.current)) * 0.035;+ const display = petDisplayPosition(trail.position, trail.yaw, appearance.sizeM, clear);+ root.current.position.set(display[0], display[1] + 0.04 + bob, display[2]);+ root.current.rotation.y = trail.points.length ? trail.yaw : owner.current.rotation.y;+ if (trail.speed > 0.005) invalidate();+ });+ return <group ref={root} visible={false}>+ {appearance.enabled && <PetBoundary key={lead ? "gigi" : appearance.shape}><Suspense fallback={null}><CompanionModel appearance={appearance} lead={lead} /></Suspense></PetBoundary>}+ </group>;+}diff --git a/jarvis/ui/web/frontend/src/components/society/companion/CompanionEditor.tsx b/jarvis/ui/web/frontend/src/components/society/companion/CompanionEditor.tsxnew file mode 100644index 0000000000..88c22424dc--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/companion/CompanionEditor.tsx@@ -0,0 +1,43 @@+import { useT } from "@/i18n";+import { Switch } from "@/components/ui/switch";+import { AgentSymbol } from "../AgentSymbol";+import { COMPANION_COLORS, COMPANION_SHAPES, type CompanionAppearance } from "./appearance";+import gigiMark from "@/assets/gigi-companion-avatar.png";+import { lazy, Suspense } from "react";+const CompanionPreview = lazy(() => import("./CompanionPreview").then(m => ({ default: m.CompanionPreview })));++export function CompanionEditor({ value, onChange, disabled = false, lead = false }: {+ value: CompanionAppearance; onChange: (next: CompanionAppearance) => void; disabled?: boolean; lead?: boolean;+}) {+ const t = useT();+ const update = (patch: Partial<CompanionAppearance>) => onChange({ ...value, ...patch });+ return <fieldset disabled={disabled} className="flex min-w-0 flex-col gap-5 p-4" data-testid="companion-editor">+ <div className="flex items-center gap-5 rounded-xl bg-secondary/50 p-5">+ {lead ? <img src={gigiMark} width={88} height={88} alt="" /> : <AgentSymbol {...value} size={88} />}+ <div><h3 className="font-medium">{t("society.companion.title")}</h3><p className="mt-1 text-sm text-muted-foreground">{t("society.companion.hint")}</p></div>+ </div>+ <Suspense fallback={null}><CompanionPreview appearance={value} lead={lead} /></Suspense>+ {!lead && <><div><span className="mb-2 block text-sm font-medium">{t("society.companion.shape")}</span>+ <div className="flex flex-wrap gap-2">{COMPANION_SHAPES.map(shape => <button key={shape} type="button"+ aria-label={t(`society.companion.shapes.${shape}`)} aria-pressed={value.shape === shape}+ onClick={() => update({ shape })} className={`grid h-12 w-12 place-items-center rounded-lg border focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring ${value.shape === shape ? "border-foreground bg-secondary" : "border-border hover:bg-secondary"}`}>+ <AgentSymbol shape={shape} color={value.color} eyes={value.eyes} size={36} />+ </button>)}</div>+ </div>+ <div><span className="mb-2 block text-sm font-medium">{t("society.companion.color")}</span>+ <div className="flex flex-wrap items-center gap-2">{COMPANION_COLORS.map(color => <button key={color} type="button" aria-label={`${t("society.companion.color")} ${color}`} aria-pressed={value.color === color}+ onClick={() => update({ color })} className={`h-8 w-8 rounded-full border-2 ${value.color === color ? "border-foreground ring-2 ring-background" : "border-transparent"}`} style={{ background: color }} />)}+ <input type="color" aria-label={t("society.companion.custom_color")} value={value.color} onChange={e => update({ color: e.target.value })} className="h-8 w-10 rounded border border-border bg-background" />+ </div>+ </div>+ <label className="flex items-center justify-between gap-3 text-sm">{t("society.companion.eyes")}+ <select aria-label={t("society.companion.eyes")} className="rounded-md border border-border bg-background p-2 text-foreground" value={value.eyes} onChange={e => update({ eyes: e.target.value as CompanionAppearance["eyes"] })}>+ <option value="dots">{t("society.companion.dots")}</option><option value="lines">{t("society.companion.lines")}</option>+ </select>+ </label>+ </>}+ <label className="flex items-center justify-between gap-3 text-sm">{t("society.companion.visible")}+ <Switch checked={value.enabled} onCheckedChange={enabled => update({ enabled })} aria-label={t("society.companion.visible")} />+ </label>+ </fieldset>;+}diff --git a/jarvis/ui/web/frontend/src/components/society/companion/CompanionPreview.tsx b/jarvis/ui/web/frontend/src/components/society/companion/CompanionPreview.tsxnew file mode 100644index 0000000000..40831fa375--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/companion/CompanionPreview.tsx@@ -0,0 +1,29 @@+import { Component, Suspense, useRef, type ReactNode } from "react";+import { Canvas } from "@react-three/fiber";+import { OrbitControls } from "@react-three/drei";+import { useCanvasAwake } from "@/hooks/useCanvasAwake";+import { useWebglSurface } from "@/hooks/useWebglSurface";+import { useWebglSupported } from "@/lib/graphDimension";+import { CompanionModel } from "./AgentFollower";+import type { CompanionAppearance } from "./appearance";++class PreviewBoundary extends Component<{ children: ReactNode }, { failed: boolean }> {+ state = { failed: false };+ static getDerivedStateFromError() { return { failed: true }; }+ componentDidCatch(error: Error) { console.warn("Companion preview unavailable", error); }+ render() { return this.state.failed ? null : this.props.children; }+}++export function CompanionPreview({ appearance, lead = false }: { appearance: CompanionAppearance; lead?: boolean }) {+ const host = useRef<HTMLDivElement>(null);+ const { generation } = useWebglSurface(host);+ const awake = useCanvasAwake(host);+ const supported = useWebglSupported();+ return <div ref={host} className="h-48 w-full touch-none" data-testid="companion-preview">+ {supported && awake && <PreviewBoundary key={generation}><Canvas frameloop="demand" dpr={[1, 1.5]} camera={{ position: [0.75, 0.65, 1.8], fov: 38 }} gl={{ alpha: true, antialias: true }}>+ <ambientLight intensity={1.6} /><directionalLight position={[2, 3, 4]} intensity={2.6} />+ <Suspense fallback={null}><CompanionModel appearance={appearance} lead={lead} /></Suspense>+ <OrbitControls target={[0, appearance.sizeM / 2, 0]} enablePan={false} enableZoom={false} minPolarAngle={0.25} maxPolarAngle={Math.PI * 0.65} />+ </Canvas></PreviewBoundary>}+ </div>;+}diff --git a/jarvis/ui/web/frontend/src/components/society/companion/GigiCompanion.tsx b/jarvis/ui/web/frontend/src/components/society/companion/GigiCompanion.tsxnew file mode 100644index 0000000000..e7cc1351cb--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/companion/GigiCompanion.tsx@@ -0,0 +1,130 @@+import { useEffect, useMemo, useRef, useState, type MutableRefObject } from "react";+import { useFrame, useThree, type ThreeEvent } from "@react-three/fiber";+import { Html } from "@react-three/drei";+import { Group, Material, Mesh, Object3D, Texture } from "three";+import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";+import gigiUrl from "../../../../../../../../art/studies/gigi-hover-companion/exports/gigi.glb";+import { createMotion, expressionFor, type AssistantPresentation, type CompanionWorld, type PlayerPose, type Point } from "./kinematics";++import { createCompanionFrame } from "./companionFrame";++const QUIET: AssistantPresentation = { audio: "idle", task: "idle", muted: false };++export interface GigiCompanionProps extends CompanionWorld {+ /** Remount the host with a new key when user/world/swarm context changes. */+ player: MutableRefObject<PlayerPose>;+ presentation?: AssistantPresentation;+ reducedMotion: boolean;+ awake: boolean;+ visible?: boolean;+ focusTarget?: Point | null;+ /** Validated navigation waypoint or vehicle docking anchor from the host. */+ destination?: Point | null;+ recallSequence?: number;+ positionRef?: MutableRefObject<Point | null>;+ onPositionReady?: () => void;+ onOpenAssistant: () => void;+ onFocus: () => void;+ markerLabel: string;+ unavailableLabel: string;+}++function disposeModel(root: Group) {+ const materials = new Set<Material>();+ const textures = new Set<Texture>();+ root.traverse((object) => {+ if (!(object instanceof Mesh)) return;+ object.geometry.dispose();+ for (const material of Array.isArray(object.material) ? object.material : [object.material]) {+ materials.add(material);+ for (const value of Object.values(material)) if (value instanceof Texture) textures.add(value);+ }+ });+ for (const value of textures) value.dispose();+ for (const value of materials) value.dispose();+}++/** One owned GLB per mounted companion; no cached orphan GPU resources or sessions. */+function useModel(enabled: boolean) {+ const [model, setModel] = useState<Group | null>(null);+ const [failed, setFailed] = useState(false);+ const invalidate = useThree((state) => state.invalidate);+ useEffect(() => {+ if (!enabled) { setModel(null); return; }+ const controller = new AbortController();+ let retired = false;+ let owned: Group | null = null;+ setModel(null); setFailed(false);+ void fetch(gigiUrl, { signal: controller.signal })+ .then((response) => {+ if (!response.ok) throw new Error("companion_model_unavailable");+ return response.arrayBuffer();+ })+ .then((buffer) => new GLTFLoader().parseAsync(buffer, ""))+ .then((asset) => {+ if (retired) { disposeModel(asset.scene); return; }+ owned = asset.scene;+ owned.traverse((object) => {+ if (object instanceof Mesh) { object.castShadow = true; object.receiveShadow = true; }+ });+ setModel(owned); invalidate();+ })+ .catch((error: unknown) => {+ if (retired) return;+ console.warn("Companion model could not load", error instanceof Error ? error.name : "Error");+ setFailed(true); invalidate();+ });+ return () => { retired = true; controller.abort(); if (owned) disposeModel(owned); };+ }, [enabled, invalidate]);+ return { model, failed };+}++export function GigiCompanion({ player, colliders, getGround, isLoaded, presentation = QUIET,+ reducedMotion, awake, visible = true, focusTarget, destination, recallSequence = 0,+ positionRef, onPositionReady, onOpenAssistant, onFocus, markerLabel, unavailableLabel }: GigiCompanionProps) {+ const { model, failed } = useModel(visible);+ const motion = useRef(createMotion());+ const root = useRef<Group>(null), body = useRef<Group>(null);+ const marker = useRef<HTMLButtonElement>(null);+ const scratch = useRef<Point>([0, 0, 0]), target = useRef<Point>([0, 0, 0]);+ const previousRecall = useRef(recallSequence);+ const route = useRef<Point[]>([]), nextPlan = useRef(0);+ const plannedTarget = useRef<Point>([NaN, NaN, NaN]);+ const publishedPosition = useRef(false);+ const world = useMemo(() => ({ colliders, getGround, isLoaded }), [colliders, getGround, isLoaded]);+ const invalidate = useThree((state) => state.invalidate);+ const parts = useMemo(() => {+ const find = (name: string): Object3D | undefined => {+ let result: Object3D | undefined;+ model?.traverse((object) => { if (object.userData.name === name) result = object; });+ return result;+ };+ return { eyes: [find("Gigi.Eye.L"), find("Gigi.Eye.R")], mouth: find("Gigi.Mouth"), arms: [find("Gigi.Arm.L"), find("Gigi.Arm.R")] };+ }, [model]);+ const expression = expressionFor(presentation);+ useEffect(() => { invalidate(); }, [expression, visible, destination, recallSequence, invalidate]);+ useEffect(() => () => { if (positionRef) positionRef.current = null; }, [positionRef]);+ useEffect(() => {+ if (!visible) { publishedPosition.current = false; if (positionRef) positionRef.current = null; }+ }, [visible, positionRef]);++ useFrame(createCompanionFrame({ visible, awake, root, motion, player, target, destination, world, previousRecall, recallSequence, route, nextPlan, plannedTarget, reducedMotion, scratch, publishedPosition, positionRef, onPositionReady, focusTarget, body, parts, expression, marker, failed, invalidate }));++ if (!visible) return null;+ const open = (event: ThreeEvent<MouseEvent>) => {+ if (event.delta > 4) return;+ event.stopPropagation(); onOpenAssistant();+ };+ return (+ <group ref={root}>+ <group ref={body} onClick={open}>+ {model && <primitive object={model} dispose={null} />}+ </group>+ <Html center position={[0, 0.52, 0]} zIndexRange={[15, 0]}>+ <button ref={marker} type="button" className="gigi-focus-marker" onClick={(event) => { event.stopPropagation(); onFocus(); }} aria-label={markerLabel}>+ {failed ? unavailableLabel : "Gigi"}+ </button>+ </Html>+ </group>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/society/companion/appearance.test.ts b/jarvis/ui/web/frontend/src/components/society/companion/appearance.test.tsnew file mode 100644index 0000000000..92b6f09e37--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/companion/appearance.test.ts@@ -0,0 +1,24 @@+import { describe, expect, it } from "vitest";+import { readFileSync } from "node:fs";+import { resolve } from "node:path";+import { companionEyeColors, companionSchema, defaultCompanion, resolveCompanion } from "./appearance";++const cases = JSON.parse(readFileSync(resolve(process.cwd(), "../../../../tests/contract/fixtures/agent-companion.json"), "utf8")) as { valid: Record<string, unknown>[]; invalid: Record<string, unknown>[] };+describe("the shared Python/JSON/TypeScript companion contract", () => {+ it.each(cases.valid)("accepts stored values %#", value => { expect(companionSchema.safeParse(value).success).toBe(true); });+ it.each(cases.invalid)("rejects malformed values %#", value => { expect(companionSchema.safeParse(value).success).toBe(false); });+ it("keeps existing identities and recovers corrupt legacy metadata", () => {+ expect(resolveCompanion("research", undefined)).toEqual(defaultCompanion("research"));+ expect(resolveCompanion("research", { shape: "bad" })).toEqual(defaultCompanion("research"));+ expect(resolveCompanion("new-name", cases.valid[1]).shape).toBe("cloud");+ });+ it("keeps the requested plain black eyes on every body colour", () => {+ expect(companionEyeColors("#000000").eye).toBe("#101014");+ expect(companionEyeColors("#ffffff").eye).toBe("#101014");+ expect(defaultCompanion("new-agent").eyes).toBe("lines");+ });+ it("standardizes earlier saved size and following-distance choices", () => {+ expect(resolveCompanion("research", cases.valid[1])).toMatchObject({ shape: "cloud", sizeM: 0.5, followDistanceM: 1 });+ expect(resolveCompanion("research", cases.valid[2])).toMatchObject({ shape: "drop", sizeM: 0.5, followDistanceM: 1 });+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/companion/appearance.ts b/jarvis/ui/web/frontend/src/components/society/companion/appearance.tsnew file mode 100644index 0000000000..9c3c290948--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/companion/appearance.ts@@ -0,0 +1,39 @@+import { z } from "zod";++export const COMPANION_SHAPES = ["circle", "squircle", "pill", "triangle", "hexagon", "cloud", "drop"] as const;+export type SymbolShape = typeof COMPANION_SHAPES[number];+export const COMPANION_COLORS = ["#8b5cf6", "#c5dfd4", "#f2a65a", "#7ab6ef", "#ed91aa", "#b7cb78", "#bba7ed", "#79c7c4"] as const;+export const COMPANION_SIZE_M = 0.5;+export const COMPANION_FOLLOW_DISTANCE_M = 1;+export const companionSchema = z.object({+ shape: z.enum(COMPANION_SHAPES), color: z.string().regex(/^#[0-9a-fA-F]{6}$/),+ eyes: z.enum(["dots", "lines"]).default("lines"), enabled: z.boolean().default(true),+ // Accept earlier saved slider values, but every presentation uses one scale.+ sizeM: z.number().finite().min(0.25).max(0.8).default(COMPANION_SIZE_M).transform(() => COMPANION_SIZE_M),+ followDistanceM: z.number().finite().min(0.5).max(2).default(COMPANION_FOLLOW_DISTANCE_M).transform(() => COMPANION_FOLLOW_DISTANCE_M),+}).strict();+export type CompanionAppearance = z.infer<typeof companionSchema>;++function identityHash(identity: string): number {+ let hash = 2166136261;+ for (const character of identity) hash = Math.imul(hash ^ character.charCodeAt(0), 16777619) >>> 0;+ return hash;+}++export function defaultCompanion(identity: string): CompanionAppearance {+ return {+ shape: COMPANION_SHAPES[identityHash(`shape:${identity}`) % COMPANION_SHAPES.length]!,+ color: COMPANION_COLORS[identityHash(`color:${identity}`) % COMPANION_COLORS.length]!,+ eyes: "lines", enabled: true, sizeM: COMPANION_SIZE_M, followDistanceM: COMPANION_FOLLOW_DISTANCE_M,+ };+}++export function resolveCompanion(identity: string, stored?: unknown): CompanionAppearance {+ const parsed = companionSchema.safeParse(stored);+ return parsed.success ? parsed.data : defaultCompanion(identity);+}++/** The same plain black ink in profiles and in the map, without catchlights. */+export function companionEyeColors(_color: string): { eye: string; highlight: string } {+ return { eye: "#101014", highlight: "#101014" };+}diff --git a/jarvis/ui/web/frontend/src/components/society/companion/companionFrame.test.ts b/jarvis/ui/web/frontend/src/components/society/companion/companionFrame.test.tsnew file mode 100644index 0000000000..f1e45c9ffd--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/companion/companionFrame.test.ts@@ -0,0 +1,44 @@+import { Group, PerspectiveCamera } from "three";+import { expect, it } from "vitest";+import { createMotion } from "./kinematics";+import { createCompanionFrame, type CompanionFrameContext } from "./companionFrame";++it("finishes a single short movement in demand mode without unrelated input", () => {+ let invalidations = 0, ready = 0;+ const context: CompanionFrameContext = {+ visible: true, awake: true, reducedMotion: true, failed: false,+ root: { current: new Group() }, body: { current: new Group() }, marker: { current: document.createElement("button") },+ motion: { current: createMotion() }, player: { current: { position: [0, 0, 0], yaw: 0 } },+ target: { current: [0, 0, 0] }, scratch: { current: [0, 0, 0] },+ world: { colliders: [], getGround: () => 0 }, previousRecall: { current: 0 }, recallSequence: 0,+ route: { current: [] }, nextPlan: { current: 0 }, plannedTarget: { current: [NaN, NaN, NaN] },+ publishedPosition: { current: false }, positionRef: { current: null }, onPositionReady: () => { ready++; },+ parts: { eyes: [], mouth: undefined, arms: [] }, expression: "idle", invalidate: () => { invalidations++; },+ };+ const callback = createCompanionFrame(context);+ const frame = { camera: new PerspectiveCamera(45), clock: { elapsedTime: 100 }, size: { height: 700 } };+ frame.camera.position.set(0, 2.5, 5);+ callback(frame, 1 / 60);+ frame.clock.elapsedTime = 100.01;+ callback(frame, 1 / 60);+ expect(context.nextPlan.current).toBeCloseTo(100.51);+ expect(context.motion.current.position).toEqual([0.95, 1.15, 0.35]);+ expect(ready).toBe(1);+ invalidations = 0;+ context.player.current.position[0] += 0.1;+ frame.clock.elapsedTime = 100.02;+ callback(frame, 1 / 60);+ expect(context.motion.current.position[0]).toBeGreaterThan(0.95);+ expect(invalidations).toBeGreaterThan(0);+ let frames = 0;+ while (invalidations > 0 && frames < 200) {+ invalidations = 0;+ frame.clock.elapsedTime += 1 / 60;+ callback(frame, 1 / 60);+ frames++;+ }+ expect(frames).toBeLessThan(200);+ expect(Math.abs(context.motion.current.position[0] - 1.05)).toBeLessThan(0.004);+ expect(invalidations).toBe(0);+ expect(ready).toBe(1);+});diff --git a/jarvis/ui/web/frontend/src/components/society/companion/companionFrame.ts b/jarvis/ui/web/frontend/src/components/society/companion/companionFrame.tsnew file mode 100644index 0000000000..a94ddc7de6--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/companion/companionFrame.ts@@ -0,0 +1,79 @@+import type { Camera, Group, Object3D } from "three";+import { advanceMotion, clearAnchor, followAnchor, planLocalRoute, recoverAt, type CompanionWorld, type Expression, type Motion, type PlayerPose, type Point } from "./kinematics";++type Ref<T> = { current: T };+interface Frame { camera: Camera; clock: { elapsedTime: number }; size: { height: number } }+export interface CompanionFrameContext {+ visible: boolean; awake: boolean; reducedMotion: boolean; failed: boolean;+ root: Ref<Group | null>; body: Ref<Group | null>; marker: Ref<HTMLButtonElement | null>;+ motion: Ref<Motion>; player: Ref<PlayerPose>; target: Ref<Point>; scratch: Ref<Point>;+ destination?: Point | null; focusTarget?: Point | null;+ world: CompanionWorld; previousRecall: Ref<number>; recallSequence: number;+ route: Ref<Point[]>; nextPlan: Ref<number>; plannedTarget: Ref<Point>;+ publishedPosition: Ref<boolean>; positionRef?: Ref<Point | null>; onPositionReady?: () => void;+ parts: { eyes: (Object3D | undefined)[]; mouth: Object3D | undefined; arms: (Object3D | undefined)[] };+ expression: Expression; invalidate: () => void;+}++/** The actual useFrame callback. Test with real Three.js transforms without a GPU. */+export function createCompanionFrame(context: CompanionFrameContext) {+ const { visible, awake, root, motion, player, target, destination, world, previousRecall, recallSequence, route, nextPlan, plannedTarget, reducedMotion, scratch, publishedPosition, positionRef, onPositionReady, focusTarget, body, parts, expression, marker, failed, invalidate } = context;+ return ({ camera, clock, size }: Frame, delta: number) => {+ if (!visible || !awake || !root.current) return;+ const state = motion.current;+ followAnchor(player.current, target.current);+ if (destination) { target.current[0] = destination[0]; target.current[1] = destination[1]; target.current[2] = destination[2]; }+ const anchorReady = clearAnchor(target.current, world);+ if (previousRecall.current !== recallSequence) {+ // Recall changes presentation only and cannot resume or complete a task.+ if (anchorReady) recoverAt(state, target.current, world);+ route.current = []; nextPlan.current = 0;+ previousRecall.current = recallSequence;+ }+ const anchorChanged = target.current.some((value, axis) => value !== plannedTarget.current[axis]);+ if (state.initialized && (clock.elapsedTime >= nextPlan.current || (reducedMotion && anchorChanged))) {+ route.current = anchorReady ? planLocalRoute(state.position, target.current, world) : [];+ nextPlan.current = clock.elapsedTime + 0.5;+ plannedTarget.current[0] = target.current[0]; plannedTarget.current[1] = target.current[1]; plannedTarget.current[2] = target.current[2];+ }+ const waypoint = route.current[0];+ if (!state.initialized || waypoint) advanceMotion(state, waypoint ?? target.current, world, delta, scratch.current);+ else { state.speed = 0; state.blocked = true; }+ if (route.current.length > 1 && waypoint && Math.hypot(waypoint[0] - state.position[0], waypoint[1] - state.position[1], waypoint[2] - state.position[2]) < 0.08) route.current.shift();+ root.current.visible = state.initialized;+ if (!state.initialized) return;+ root.current.position.fromArray(state.position);+ if (positionRef) positionRef.current = state.position;+ if (!publishedPosition.current) { publishedPosition.current = true; onPositionReady?.(); }+ const glanceAtPlayer = !reducedMotion && clock.elapsedTime % 12 > 10;+ const attention = focusTarget ?? (glanceAtPlayer ? player.current.position : null);+ const yaw = Math.atan2((attention?.[0] ?? camera.position.x) - state.position[0], (attention?.[2] ?? camera.position.z) - state.position[2]);+ const angle = Math.atan2(Math.sin(yaw - state.yaw), Math.cos(yaw - state.yaw));+ state.yaw += angle * (1 - Math.exp(-6 * Math.min(delta, 0.1)));+ root.current.rotation.y = state.yaw;+ const time = clock.elapsedTime;+ if (body.current) {+ body.current.position.y = reducedMotion ? 0 : Math.sin(time * 2) * 0.012;+ body.current.rotation.z = reducedMotion ? 0 : Math.sin(time * 1.1) * 0.015;+ }+ // Independent expression never controls motion or logical outcomes.+ const blink = reducedMotion ? 1 : (time % 5.5 > 5.32 ? 0.15 : 1);+ for (const eye of parts.eyes) if (eye) eye.scale.y = blink * (expression === "listening" ? 1.08 : expression === "error" ? 0.72 : 1);+ if (parts.mouth) parts.mouth.scale.y = expression === "speaking" && !reducedMotion ? 0.9 + Math.sin(time * 12) * 0.18 : 1;+ for (let i = 0; i < parts.arms.length; i++) {+ const arm = parts.arms[i];+ if (arm) arm.rotation.z = (i === 0 ? -1 : 1) * (expression === "approval" ? 0.45 : expression === "complete" ? 0.3 : 0.15);+ }+ if (marker.current) {+ // Marker takes over only when the physical body is genuinely too small.+ const distance = camera.position.distanceTo(root.current.position);+ const fov = "fov" in camera ? Number(camera.fov) : 50;+ const pixels = 0.4 * size.height / (2 * Math.max(distance, 0.1) * Math.tan(fov * Math.PI / 360));+ marker.current.style.display = pixels < 22 || failed ? "block" : "none";+ marker.current.dataset.gigiPixels = pixels.toFixed(1);+ marker.current.dataset.gigiBlocked = String(state.blocked);+ }+ // Reduced motion still converges after a deliberate player/camera action.+ if (reducedMotion && state.speed > 0.015 && !state.blocked) invalidate();+ };+}diff --git a/jarvis/ui/web/frontend/src/components/society/companion/kinematics.test.ts b/jarvis/ui/web/frontend/src/components/society/companion/kinematics.test.tsnew file mode 100644index 0000000000..d38a2d3d9f--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/companion/kinematics.test.ts@@ -0,0 +1,59 @@+import { describe, expect, it } from "vitest";+import { advanceMotion, clearAnchor, createMotion, expressionFor, followAnchor, planLocalRoute, positionClear, recoverAt, routeClear, type CompanionWorld, type Point } from "./kinematics";++const flat: CompanionWorld = { colliders: [], getGround: () => 0 };+function simulate(hz: number) {+ const state = createMotion();+ recoverAt(state, [0, 1.15, 0], flat);+ for (let i = 0; i < hz; i++) advanceMotion(state, [4, 1.15, 0], flat, 1 / hz, [0, 0, 0]);+ return state;+}+describe("companion physical presentation", () => {+ it("finds a verifiable route around a wall instead of moving through it", () => {+ const world: CompanionWorld = { ...flat, colliders: [{ min: [1, 0, -1], max: [1.1, 3, 1] }] };+ const path = planLocalRoute([0, 1.15, 0], [3, 1.15, 0], world);+ expect(path.length).toBeGreaterThan(1);+ let previous: Point = [0, 1.15, 0];+ for (const point of path) { expect(routeClear(previous, point, world)).toBe(true); previous = point; }+ expect(previous).toEqual([3, 1.15, 0]);+ });+ it("lowers the companion below a ceiling and rejects an untraversable enclosure", () => {+ const world: CompanionWorld = { ...flat, colliders: [{ min: [-2, 1.4, -2], max: [2, 2, 2] }] };+ const anchor: Point = [0, 1.15, 0];+ expect(clearAnchor(anchor, world)).toBe(true);+ expect(anchor[1]).toBeLessThan(0.98);+ expect(planLocalRoute([0, 0.5, 0], [0, 2.5, 0], { ...world, isLoaded: p => Math.abs(p[0]) < 1 && Math.abs(p[2]) < 1 })).toEqual([]);+ });+ it("converges consistently at 30, 60 and 120 fps", () => {+ expect(simulate(30).position[0]).toBeCloseTo(simulate(60).position[0], 5);+ expect(simulate(120).position[0]).toBeCloseTo(simulate(60).position[0], 2);+ });+ it("cannot tunnel through a thin closed wall even after a long tab suspension", () => {+ const world = { ...flat, colliders: [{ min: [0.5, 0, -1] as Point, max: [0.501, 3, 1] as Point }] };+ const state = createMotion();+ recoverAt(state, [0, 1.15, 0], world);+ for (let i = 0; i < 100; i++) advanceMotion(state, [4, 1.15, 0], world, 300, [0, 0, 0]);+ expect(state.position[0]).toBeLessThanOrEqual(0.27);+ expect(state.blocked).toBe(true);+ });+ it("accounts for head clearance at low ceilings", () => {+ const world: CompanionWorld = { ...flat, colliders: [{ min: [-1, 1.4, -1], max: [1, 1.5, 1] }] };+ expect(positionClear([0, 1.15, 0], world)).toBe(false);+ expect(positionClear([0, 0.8, 0], world)).toBe(true);+ });+ it("never repositions into unloaded, underground, or invalid space", () => {+ const state = createMotion();+ expect(recoverAt(state, [1, 1, 1], { ...flat, isLoaded: () => false })).toBe(false);+ expect(recoverAt(state, [1, -1, 1], flat)).toBe(false);+ expect(recoverAt(state, [NaN, 1, 1], flat)).toBe(false);+ expect(state.initialized).toBe(false);+ });+ it("retains its player side without a camera input", () => {+ expect(followAnchor({ position: [0, 0, 0], yaw: 0 }, [0, 0, 0])).toEqual([0.95, 1.15, 0.35]);+ });+ it("does not turn stale audio into speaking after mute", () => {+ expect(expressionFor({ audio: "speaking", task: "idle", muted: true })).toBe("idle");+ expect(expressionFor({ audio: "idle", task: "error", muted: false })).toBe("error");+ expect(expressionFor({ audio: "speaking", task: "approval", muted: false })).toBe("approval");+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/companion/kinematics.ts b/jarvis/ui/web/frontend/src/components/society/companion/kinematics.tsnew file mode 100644index 0000000000..0daf00d115--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/companion/kinematics.ts@@ -0,0 +1,176 @@+/** Metre-scale companion motion. Presentation has no task or audio authority. */+export type Point = [number, number, number];+export interface PlayerPose { position: Point; yaw: number }+export interface Obstacle { min: Point; max: Point }+export interface CompanionWorld {+ colliders: readonly Obstacle[];+ getGround: (x: number, z: number) => number;+ /** False for unloaded chunks, forbidden volumes or reserved interaction space. */+ isLoaded?: (position: Point) => boolean;+}+export interface Motion {+ position: Point;+ yaw: number;+ blocked: boolean;+ initialized: boolean;+ speed: number;+}+export const BODY_HEIGHT = 0.4;+export const CLEARANCE = 0.23;+export const MAX_SPEED = 9;+const EPSILON = 0.0001;++export function createMotion(): Motion {+ return { position: [0, 0, 0], yaw: 0, blocked: false, initialized: false, speed: 0 };+}++/** Stable side of the player, independent of camera yaw. Position is body bottom. */+export function followAnchor(player: PlayerPose, out: Point): Point {+ out[0] = player.position[0] + Math.cos(player.yaw) * 0.95 + Math.sin(player.yaw) * 0.35;+ out[1] = player.position[1] + 1.15;+ out[2] = player.position[2] - Math.sin(player.yaw) * 0.95 + Math.cos(player.yaw) * 0.35;+ return out;+}++export function positionClear(p: Point, world: CompanionWorld): boolean {+ if (!p.every(Number.isFinite) || world.isLoaded?.(p) === false) return false;+ const floor = world.getGround(p[0], p[2]);+ if (!Number.isFinite(floor) || p[1] < floor + 0.03) return false;+ return !world.colliders.some((box) => p[0] > box.min[0] - CLEARANCE+ && p[0] < box.max[0] + CLEARANCE && p[2] > box.min[2] - CLEARANCE+ && p[2] < box.max[2] + CLEARANCE && p[1] > box.min[1] - BODY_HEIGHT - 0.025+ && p[1] < box.max[1] + 0.025);+}++/** Earliest contact with expanded closed geometry, including thin walls/ceilings. */+function clearFraction(start: Point, end: Point, world: CompanionWorld): number {+ let first = 1;+ for (const box of world.colliders) {+ let enter = -Infinity, leave = Infinity;+ for (let axis = 0; axis < 3; axis++) {+ const min = box.min[axis] - (axis === 1 ? BODY_HEIGHT + 0.025 : CLEARANCE);+ const max = box.max[axis] + (axis === 1 ? 0.025 : CLEARANCE);+ const delta = end[axis] - start[axis];+ if (Math.abs(delta) < 1e-12) {+ if (start[axis] <= min || start[axis] >= max) { leave = -Infinity; break; }+ } else {+ const a = (min - start[axis]) / delta, b = (max - start[axis]) / delta;+ enter = Math.max(enter, Math.min(a, b));+ leave = Math.min(leave, Math.max(a, b));+ }+ }+ if (enter >= -EPSILON && leave >= Math.max(0, enter)) first = Math.min(first, Math.max(0, enter));+ }+ return first === 1 ? 1 : Math.max(0, first - EPSILON);+}++export function routeClear(start: Point, end: Point, world: CompanionWorld): boolean {+ if (clearFraction(start, end, world) < 1) return false;+ const count = Math.max(1, Math.ceil(Math.hypot(end[0] - start[0], end[1] - start[1], end[2] - start[2]) / 0.2));+ if (count > 200) return false;+ const sample: Point = [0, 0, 0];+ for (let i = 0; i <= count; i++) {+ for (let axis = 0; axis < 3; axis++) sample[axis] = start[axis] + (end[axis] - start[axis]) * i / count;+ if (!positionClear(sample, world)) return false;+ }+ return true;+}++/** Adjust hover height under a ceiling, without forcing the body into the floor. */+export function clearAnchor(anchor: Point, world: CompanionWorld): boolean {+ const original = anchor[1];+ for (let lower = 0; lower <= 1; lower += 0.1) {+ anchor[1] = original - lower;+ if (positionClear(anchor, world)) return true;+ }+ anchor[1] = original;+ return false;+}++/** Bounded local visibility graph. Replan at most twice per second, never per frame.+ * Returns no path when the world cannot prove a route; it never invents travel.+ */+export function planLocalRoute(start: Point, end: Point, world: CompanionWorld): Point[] {+ if (!positionClear(start, world) || !positionClear(end, world)) return [];+ if (routeClear(start, end, world)) return [[...end]];+ const nodes: Point[] = [[...start], [...end]];+ for (const box of world.colliders) {+ if (box.max[1] < Math.min(start[1], end[1]) || box.min[1] > Math.max(start[1], end[1]) + BODY_HEIGHT) continue;+ if (box.max[0] < Math.min(start[0], end[0]) - 8 || box.min[0] > Math.max(start[0], end[0]) + 8+ || box.max[2] < Math.min(start[2], end[2]) - 8 || box.min[2] > Math.max(start[2], end[2]) + 8) continue;+ for (const x of [box.min[0] - CLEARANCE - 0.08, box.max[0] + CLEARANCE + 0.08]) {+ for (const z of [box.min[2] - CLEARANCE - 0.08, box.max[2] + CLEARANCE + 0.08]) {+ const candidate: Point = [x, Math.min(start[1], end[1]), z];+ if (nodes.length < 50 && positionClear(candidate, world)) nodes.push(candidate);+ }+ }+ }+ const costs = nodes.map(() => Infinity), previous = nodes.map(() => -1);+ const visited = new Set<number>();+ costs[0] = 0;+ while (visited.size < nodes.length) {+ let current = -1;+ for (let i = 0; i < nodes.length; i++) if (!visited.has(i) && Number.isFinite(costs[i]) && (current < 0 || costs[i] < costs[current])) current = i;+ if (current < 0) return [];+ if (current === 1) {+ const result: Point[] = [];+ for (let i = 1; i !== 0; i = previous[i]) result.unshift(nodes[i]);+ return result;+ }+ visited.add(current);+ for (let next = 0; next < nodes.length; next++) {+ if (visited.has(next)) continue;+ const a = nodes[current], b = nodes[next];+ const cost = costs[current] + Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]);+ if (cost < costs[next] && routeClear(a, b, world)) { costs[next] = cost; previous[next] = current; }+ }+ }+ return [];+}++/** Bounded fixed substeps; background-tab time never becomes a teleport. */+export function advanceMotion(state: Motion, target: Point, world: CompanionWorld, delta: number, scratch: Point): void {+ if (!Number.isFinite(delta) || delta <= 0 || !target.every(Number.isFinite)) return;+ if (!state.initialized) {+ if (!positionClear(target, world)) { state.blocked = true; return; }+ state.position[0] = target[0]; state.position[1] = target[1]; state.position[2] = target[2];+ state.initialized = true;+ }+ state.blocked = false;+ let remaining = Math.min(delta, 0.1);+ while (remaining > 1e-8) {+ const dt = Math.min(remaining, 1 / 60);+ remaining -= dt;+ const p = state.position;+ const dx = target[0] - p[0], dy = target[1] - p[1], dz = target[2] - p[2];+ const distance = Math.hypot(dx, dy, dz);+ const fraction = distance < 1e-8 ? 0 : Math.min(1 - Math.exp(-5 * dt), MAX_SPEED * dt / distance);+ scratch[0] = p[0] + dx * fraction; scratch[1] = p[1] + dy * fraction; scratch[2] = p[2] + dz * fraction;+ const travel = clearFraction(p, scratch, world);+ for (let axis = 0; axis < 3; axis++) scratch[axis] = p[axis] + (scratch[axis] - p[axis]) * travel;+ if (!positionClear(scratch, world)) { state.blocked = true; state.speed = 0; break; }+ state.speed = Math.hypot(scratch[0] - p[0], scratch[1] - p[1], scratch[2] - p[2]) / dt;+ p[0] = scratch[0]; p[1] = scratch[1]; p[2] = scratch[2];+ if (travel < 1) { state.blocked = true; break; }+ }+}++/** Explicit recovery only; host must provide a validated loaded anchor. */+export function recoverAt(state: Motion, anchor: Point, world: CompanionWorld): boolean {+ if (!positionClear(anchor, world)) return false;+ state.position[0] = anchor[0]; state.position[1] = anchor[1]; state.position[2] = anchor[2];+ state.initialized = true; state.blocked = false; state.speed = 0;+ return true;+}++export type Expression = "idle" | "listening" | "speaking" | "working" | "approval" | "blocked" | "error" | "complete";+export interface AssistantPresentation {+ audio: "idle" | "listening" | "speaking";+ task: "idle" | "working" | "approval" | "blocked" | "error" | "complete";+ muted: boolean;+}+export function expressionFor(state: AssistantPresentation): Expression {+ if (state.task === "error" || state.task === "blocked" || state.task === "approval") return state.task;+ if (!state.muted && state.audio !== "idle") return state.audio;+ return state.task;+}diff --git a/jarvis/ui/web/frontend/src/components/society/companion/preferences.test.ts b/jarvis/ui/web/frontend/src/components/society/companion/preferences.test.tsnew file mode 100644index 0000000000..b3e3aa3a9e--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/companion/preferences.test.ts@@ -0,0 +1,11 @@+import { expect, it } from "vitest";+import { readCompanionVisible, writeCompanionVisible } from "./preferences";++it("keeps presentation preferences separate for ordinary and swarm worlds", () => {+ writeCompanionVisible("test:ordinary", false);+ writeCompanionVisible("test:swarm:one", true);+ expect(readCompanionVisible("test:ordinary")).toBe(false);+ expect(readCompanionVisible("test:swarm:one")).toBe(true);+ localStorage.removeItem("jarvis.companion.test:ordinary.visible.v1");+ localStorage.removeItem("jarvis.companion.test:swarm:one.visible.v1");+});diff --git a/jarvis/ui/web/frontend/src/components/society/companion/preferences.ts b/jarvis/ui/web/frontend/src/components/society/companion/preferences.tsnew file mode 100644index 0000000000..daefa7936d--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/companion/preferences.ts@@ -0,0 +1,9 @@+/** Only presentation is persisted. World poses and task authority remain elsewhere. */+export function readCompanionVisible(worldKey: string): boolean {+ try { return localStorage.getItem(`jarvis.companion.${worldKey}.visible.v1`) !== "false"; }+ catch { return true; } // Storage can be unavailable in private browser profiles.+}+export function writeCompanionVisible(worldKey: string, visible: boolean): void {+ try { localStorage.setItem(`jarvis.companion.${worldKey}.visible.v1`, String(visible)); }+ catch { /* The current mounted view retains its in-memory preference. */ }+}diff --git a/jarvis/ui/web/frontend/src/components/society/companion/trail.test.ts b/jarvis/ui/web/frontend/src/components/society/companion/trail.test.tsnew file mode 100644index 0000000000..f289f58ffb--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/companion/trail.test.ts@@ -0,0 +1,42 @@+import { describe, expect, it } from "vitest";+import { advancePetTrail, createPetTrail, petDisplayPosition, recordOwner } from "./trail";++describe("footstep followers", () => {+ it("stops at its chosen gap and does not overlap a stationary owner", () => {+ const trail = createPetTrail([0, 0, 0]); recordOwner(trail, [4, 0, 0]);+ for (let i = 0; i < 120; i++) advancePetTrail(trail, 1, 1 / 60);+ expect(trail.position[0]).toBeCloseTo(3, 5);+ expect(trail.speed).toBe(0);+ });+ it("walks through the recorded corner instead of cutting through a building", () => {+ const trail = createPetTrail([0, 0, 0]);+ recordOwner(trail, [3, 0, 0]); recordOwner(trail, [3, 0, 3]);+ for (let i = 0; i < 180; i++) {+ advancePetTrail(trail, 0.5, 1 / 60);+ expect(trail.position[2] === 0 || Math.abs(trail.position[0] - 3) < 1e-6).toBe(true);+ }+ expect(trail.position).toEqual([3, 0, 2.5]);+ });+ it("inserts the verified route node when network snapshots cross a corner", () => {+ const trail = createPetTrail([0, 0, 0]); recordOwner(trail, [3, 1, 3], [3, 1, 0]);+ for (let i = 0; i < 180; i++) advancePetTrail(trail, 1, 1 / 60);+ expect(trail.position[1]).toBeCloseTo(1); expect(trail.position[2]).toBeCloseTo(2);+ });+ it("bounds background-tab catch-up and re-places discontinuities without sweeping the map", () => {+ const trail = createPetTrail([0, 0, 0]); recordOwner(trail, [5, 0, 0]); advancePetTrail(trail, 1, 600);+ expect(trail.position[0]).toBeLessThanOrEqual(0.8);+ expect(recordOwner(trail, [200, 10, 200])).toBe(false);+ expect(trail.points).toEqual([]); expect(trail.position).toEqual([200, 10, 200]);+ });+ it("rejects non-finite inputs and bounds the stored history", () => {+ const trail = createPetTrail([0, 0, 0]); expect(recordOwner(trail, [NaN, 0, 0])).toBe(false);+ for (let i = 0; i < 2000; i++) recordOwner(trail, [i * 0.1, 0, 0]);+ expect(trail.points.length).toBeLessThanOrEqual(513);+ });+ it("uses a visible shoulder only when the map proves clearance", () => {+ expect(petDisplayPosition([0, 0, 0], 0, 0.5, () => true)).toEqual([0.35, 0, 0]);+ expect(petDisplayPosition([0, 0, 0], 0, 0.5, p => p[0] < 0)).toEqual([-0.35, 0, 0]);+ expect(petDisplayPosition([0, 0, 0], 0, 0.5, () => false)).toEqual([0, 0, 0]);+ expect(petDisplayPosition([0, 0, 0], 0, 0.5)).toEqual([0, 0, 0]);+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/companion/trail.ts b/jarvis/ui/web/frontend/src/components/society/companion/trail.tsnew file mode 100644index 0000000000..0b765ad022--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/companion/trail.ts@@ -0,0 +1,56 @@+/** Follow recorded footsteps, never the straight line to a moving owner. */+export type TrailPoint = [number, number, number];+export interface PetTrail { position: TrailPoint; points: TrailPoint[]; owner: TrailPoint; yaw: number; speed: number }+const distance = (a: TrailPoint, b: TrailPoint) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]);++export function createPetTrail(owner: TrailPoint): PetTrail {+ return { position: [...owner], owner: [...owner], points: [], yaw: 0, speed: 0 };+}++/** A small shoulder offset keeps the pet visible; never leave the verified+ * route unless the host can prove ground and clearance for the whole body. */+export function petDisplayPosition(position: TrailPoint, yaw: number, size: number, clear?: (point: TrailPoint, radius: number) => boolean): TrailPoint {+ if (!clear) return position;+ const offset = Math.min(0.38, size * 0.7);+ for (const side of [1, -1]) {+ const candidate: TrailPoint = [position[0] + Math.cos(yaw) * offset * side, position[1], position[2] - Math.sin(yaw) * offset * side];+ if (clear(candidate, size / 2)) return candidate;+ }+ return position;+}++export function recordOwner(trail: PetTrail, owner: TrailPoint, via?: TrailPoint): boolean {+ if (!owner.every(Number.isFinite)) return false;+ const gap = distance(trail.owner, owner);+ if (gap < 0.025) return true;+ // A refresh, teleport or missing stretch has no proven footsteps. Re-place+ // alongside the owner instead of drawing travel through unknown geometry.+ if (gap > 12 || trail.points.length > 512) {+ trail.position = [...owner]; trail.owner = [...owner]; trail.points = []; trail.speed = 0;+ return false;+ }+ if (via && via.every(Number.isFinite) && distance(trail.owner, via) > 0.025) trail.points.push([...via]);+ trail.points.push([...owner]); trail.owner = [...owner];+ return true;+}++export function advancePetTrail(trail: PetTrail, gap: number, delta: number): void {+ if (!Number.isFinite(delta) || delta <= 0) return;+ let length = 0, last = trail.position;+ for (const point of trail.points) { length += distance(last, point); last = point; }+ const dt = Math.min(delta, 0.1);+ let budget = Math.min(Math.max(0, length - gap), Math.min(8, 2 + Math.max(0, length - gap) * 2) * dt);+ const travel = budget;+ while (budget > 1e-7 && trail.points.length) {+ const next = trail.points[0];+ const segment = distance(trail.position, next);+ if (segment < 1e-7) { trail.points.shift(); continue; }+ const fraction = Math.min(1, budget / segment);+ const dx = next[0] - trail.position[0], dz = next[2] - trail.position[2];+ if (Math.hypot(dx, dz) > 1e-7) trail.yaw = Math.atan2(dx, dz);+ for (let axis = 0; axis < 3; axis++) trail.position[axis] += (next[axis] - trail.position[axis]) * fraction;+ budget -= segment * fraction;+ if (fraction === 1) trail.points.shift();+ }+ trail.speed = (travel - budget) / dt;+}diff --git a/jarvis/ui/web/frontend/src/components/society/companion/useCompanionFocusRequests.test.tsx b/jarvis/ui/web/frontend/src/components/society/companion/useCompanionFocusRequests.test.tsxnew file mode 100644index 0000000000..788ad047b6--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/companion/useCompanionFocusRequests.test.tsx@@ -0,0 +1,41 @@+import { useCallback, useEffect, useRef } from "react";+import { act, render } from "@testing-library/react";+import { describe, expect, it } from "vitest";+import type { Point } from "./kinematics";+import { useCompanionFocusRequests } from "./useCompanionFocusRequests";+import { usePendingCompanionFocus } from "./usePendingCompanionFocus";++describe("host-owned companion focus", () => {+ it.each([false, true])("preserves intent but never replays consumed focus after renderer recreation (ready=%s)", (initiallyReady) => {+ const calls: number[] = [];+ let request: () => void = () => undefined;+ let cancel: () => void = () => undefined;+ function Renderer({ pending, ready, acknowledge }: { pending: number; ready: boolean; acknowledge: (id: number) => void }) {+ const pose = useRef<Point | null>(null);+ useEffect(() => { pose.current = ready ? [1, 2, 3] : null; }, [ready]);+ const apply = useCallback(() => { calls.push(pending); acknowledge(pending); return true; }, [pending, acknowledge]);+ usePendingCompanionFocus(pending, pose, Number(ready), apply);+ return null;+ }+ function Host({ generation, ready }: { generation: number; ready: boolean }) {+ const intent = useCompanionFocusRequests();+ request = intent.request; cancel = intent.cancel;+ return <Renderer key={generation} pending={intent.pending} acknowledge={intent.acknowledge} ready={ready} />;+ }+ const view = render(<Host generation={1} ready={initiallyReady} />);+ act(() => request());+ expect(calls).toEqual(initiallyReady ? [1] : []);+ view.rerender(<Host generation={2} ready={true} />);+ expect(calls).toEqual([1]);+ view.rerender(<Host generation={3} ready={true} />);+ expect(calls).toEqual([1]);+ act(() => request());+ expect(calls).toEqual([1, 2]);+ view.rerender(<Host generation={4} ready={false} />);+ act(() => request());+ act(() => cancel());+ view.rerender(<Host generation={5} ready={true} />);+ expect(calls).toEqual([1, 2]);+ view.unmount();+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/companion/useCompanionFocusRequests.ts b/jarvis/ui/web/frontend/src/components/society/companion/useCompanionFocusRequests.tsnew file mode 100644index 0000000000..9f26ffb378--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/companion/useCompanionFocusRequests.ts@@ -0,0 +1,11 @@+import { useCallback, useRef, useState } from "react";++/** The host owns intent across Canvas recreation; the renderer acknowledges it. */+export function useCompanionFocusRequests() {+ const sequence = useRef(0);+ const [pending, setPending] = useState(0);+ const request = useCallback(() => setPending(++sequence.current), []);+ const acknowledge = useCallback((id: number) => setPending((current) => current === id ? 0 : current), []);+ const cancel = useCallback(() => setPending(0), []);+ return { pending, request, acknowledge, cancel };+}diff --git a/jarvis/ui/web/frontend/src/components/society/companion/useCompanionPresentation.test.tsx b/jarvis/ui/web/frontend/src/components/society/companion/useCompanionPresentation.test.tsxnew file mode 100644index 0000000000..6c73b3f963--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/companion/useCompanionPresentation.test.tsx@@ -0,0 +1,74 @@+import { act, renderHook } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { afterEach, expect, it, vi } from "vitest";+import type { ReactNode } from "react";+import { useEventStore } from "@/store/events";+import { WORLD_ID, type MarsSnapshot, type CommandState } from "../mars/api";+import { useCompanionPresentation } from "./useCompanionPresentation";++const key = ["mars", WORLD_ID, "snapshot"];+function snapshot(state: CommandState, seq = 1): MarsSnapshot {+ return { world_id: WORLD_ID, schema_version: 1, layout_version: 1, seq, commands: [{+ command_id: "test-command", agent_id: "test-agent", request_id: "test-request", trace_id: "test-trace",+ world_id: WORLD_ID, state, task_ref: "test-task", result_ref: null, reason: "", cancel_requested: false,+ }] };+}+afterEach(() => { useEventStore.getState().setVoice("idle"); vi.useRealTimers(); });+function harness(initial: CommandState) {+ const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });+ client.setQueryData(key, snapshot(initial));+ const wrapper = ({ children }: { children: ReactNode }) => <QueryClientProvider client={client}>{children}</QueryClientProvider>;+ const hook = renderHook(() => useCompanionPresentation(false), { wrapper });+ return { client, ...hook };+}++it("does not replay a completion from the initial snapshot", () => {+ const h = harness("completed");+ expect(h.result.current.task).toBe("idle");+ h.unmount(); h.client.clear();+});+it.each(["unknown", "interrupted"] as const)("keeps initial %s work blocked beyond notification expiry", async (state) => {+ vi.useFakeTimers();+ const h = harness(state);+ expect(h.result.current.task).toBe("blocked");+ act(() => { vi.advanceTimersByTime(6000); useEventStore.getState().setVoice("thinking"); });+ expect(h.result.current.task).toBe("blocked");+ const mixed = snapshot(state, 2);+ mixed.commands.push({ ...snapshot("queued").commands[0], command_id: "queued-other-command" });+ await act(async () => { h.client.setQueryData(key, mixed); await vi.advanceTimersByTimeAsync(1); });+ expect(h.result.current.task).toBe("blocked");+ await act(async () => { h.client.setQueryData(key, snapshot("active", 3)); await vi.advanceTimersByTimeAsync(1); });+ expect(h.result.current.task).toBe("working");+ h.unmount(); h.client.clear();+});+it("keeps an observed unknown outcome blocked until the snapshot resolves it", async () => {+ vi.useFakeTimers();+ const h = harness("active");+ await act(async () => { h.client.setQueryData(key, snapshot("unknown", 2)); await vi.advanceTimersByTimeAsync(1); });+ expect(h.result.current.task).toBe("blocked");+ act(() => vi.advanceTimersByTime(6000));+ expect(h.result.current.task).toBe("blocked");+ await act(async () => { h.client.setQueryData(key, snapshot("completed", 3)); await vi.advanceTimersByTimeAsync(1); });+ expect(h.result.current.task).toBe("complete");+ act(() => vi.advanceTimersByTime(6000));+ expect(h.result.current.task).toBe("idle");+ h.unmount(); h.client.clear();+});+it("shows real active work and a subsequent observed failure", async () => {+ const h = harness("active");+ expect(h.result.current.task).toBe("working");+ await act(async () => { h.client.setQueryData(key, snapshot("failed", 2)); await new Promise(resolve => setTimeout(resolve, 5)); });+ expect(h.result.current.task).toBe("error");+ h.unmount(); h.client.clear();+});+it("stops speaking when the shared voice state is paused or interrupted", () => {+ const h = harness("completed");+ act(() => useEventStore.getState().setVoice("speaking"));+ expect(h.result.current.audio).toBe("speaking");+ act(() => useEventStore.getState().setVoice("paused"));+ expect(h.result.current.audio).toBe("idle");+ expect(h.result.current.muted).toBe(true);+ act(() => useEventStore.getState().setVoice("idle"));+ expect(h.result.current.audio).toBe("idle");+ h.unmount(); h.client.clear();+});diff --git a/jarvis/ui/web/frontend/src/components/society/companion/useCompanionPresentation.ts b/jarvis/ui/web/frontend/src/components/society/companion/useCompanionPresentation.tsnew file mode 100644index 0000000000..feaaeace46--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/companion/useCompanionPresentation.ts@@ -0,0 +1,45 @@+import { useEffect, useRef, useState } from "react";+import { useQuery } from "@tanstack/react-query";+import { useEventStore } from "@/store/events";+import { fetchMarsSnapshot, WORLD_ID, type CommandState } from "../mars/api";+import type { AssistantPresentation } from "./kinematics";++/** Ordinary-world adapter only. A swarm must supply its own scoped adapter. */+export function useCompanionPresentation(awake: boolean): AssistantPresentation {+ const voice = useEventStore((state) => state.voiceState);+ const [pollMs] = useState(() => 3000 + Math.floor(Math.random() * 1000));+ const snapshot = useQuery({+ queryKey: ["mars", WORLD_ID, "snapshot"],+ queryFn: ({ signal }) => fetchMarsSnapshot(signal),+ enabled: awake, refetchInterval: awake ? pollMs : false, retry: false,+ });+ const previous = useRef<Map<string, CommandState> | null>(null);+ const [terminal, setTerminal] = useState<AssistantPresentation["task"]>("idle");+ useEffect(() => {+ const commands = snapshot.data?.commands;+ if (!commands) return;+ let changed: AssistantPresentation["task"] = "idle";+ for (const command of commands) {+ // Initial history is a baseline. Reopening the world never celebrates old work.+ if (!previous.current?.has(command.command_id) || previous.current.get(command.command_id) === command.state) continue;+ if (command.state === "failed") changed = "error";+ else if (command.state === "completed" && changed === "idle") changed = "complete";+ }+ previous.current = new Map(commands.map((command) => [command.command_id, command.state]));+ if (changed !== "idle") setTerminal(changed);+ }, [snapshot.data]);+ useEffect(() => {+ if (terminal === "idle") return;+ const timeout = setTimeout(() => setTerminal("idle"), 5000);+ return () => clearTimeout(timeout);+ }, [terminal]);+ const active = snapshot.data?.commands.some((command) => command.state === "active" || command.state === "queued") ?? false;+ // Uncertain work is current state, including on initial hydration. It must+ // outlive cosmetic notification timers and take precedence over queued work.+ const blocked = snapshot.data?.commands.some((command) => command.state === "unknown" || command.state === "interrupted") ?? false;+ return {+ audio: voice === "speaking" || voice === "listening" ? voice : "idle",+ task: voice === "error" ? "error" : blocked ? "blocked" : active || voice === "thinking" ? "working" : terminal,+ muted: voice === "paused",+ };+}diff --git a/jarvis/ui/web/frontend/src/components/society/companion/usePendingCompanionFocus.test.tsx b/jarvis/ui/web/frontend/src/components/society/companion/usePendingCompanionFocus.test.tsxnew file mode 100644index 0000000000..e5065adc77--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/companion/usePendingCompanionFocus.test.tsx@@ -0,0 +1,22 @@+import { renderHook } from "@testing-library/react";+import { expect, it } from "vitest";+import type { Point } from "./kinematics";+import { usePendingCompanionFocus } from "./usePendingCompanionFocus";++it("retains the first focus request while hidden until a pose is published", () => {+ const position: { current: Point | null } = { current: null };+ const applied: Point[] = [];+ const apply = (point: Point) => { applied.push([...point]); return true; };+ const hook = renderHook(({ version, request }) => usePendingCompanionFocus(request, position, version, apply), { initialProps: { version: 0, request: 0 } });+ hook.rerender({ version: 0, request: 1 });+ expect(applied).toEqual([]);+ position.current = [1, 2, 3];+ hook.rerender({ version: 1, request: 1 });+ expect(applied).toEqual([[1, 2, 3]]);+ position.current = [4, 5, 6];+ hook.rerender({ version: 2, request: 1 });+ expect(applied).toHaveLength(1);+ hook.rerender({ version: 2, request: 2 });+ expect(applied).toEqual([[1, 2, 3], [4, 5, 6]]);+ hook.unmount();+});diff --git a/jarvis/ui/web/frontend/src/components/society/companion/usePendingCompanionFocus.ts b/jarvis/ui/web/frontend/src/components/society/companion/usePendingCompanionFocus.tsnew file mode 100644index 0000000000..3c612dc741--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/companion/usePendingCompanionFocus.ts@@ -0,0 +1,11 @@+import { useEffect, useRef, type MutableRefObject } from "react";+import type { Point } from "./kinematics";++/** Consume a request only when the host has applied it to a published pose. */+export function usePendingCompanionFocus(request: number, position: MutableRefObject<Point | null>, readyVersion: number, apply: (point: Point) => boolean): void {+ const applied = useRef(0);+ useEffect(() => {+ if (request <= applied.current || !position.current) return;+ if (apply(position.current)) applied.current = request;+ }, [request, position, readyVersion, apply]);+}diff --git a/jarvis/ui/web/frontend/src/components/society/create/CreateAgentDialog.tsx b/jarvis/ui/web/frontend/src/components/society/create/CreateAgentDialog.tsxindex 193d43bd23..57e26d0470 100644--- a/jarvis/ui/web/frontend/src/components/society/create/CreateAgentDialog.tsx+++ b/jarvis/ui/web/frontend/src/components/society/create/CreateAgentDialog.tsx@@ -60,6 +60,8 @@ import {} from "./brainPicker";import { modelSeats } from "../chat/modelChoices";import { useCreateAgent, type PermissionCeiling } from "../data";+import { CompanionEditor } from "../companion/CompanionEditor";+import { resolveCompanion } from "../companion/appearance";import { AgentFigureViewer } from "../figures/AgentFigureViewer";import {EDITABLE_CELLS,@@ -120,6 +122,7 @@ export function CreateAgentDialog({ open, onClose, onCreated }: CreateAgentDialoconst [title, setTitle] = useState("");const [description, setDescription] = useState("");const [recipe, setRecipe] = useState<FigureRecipe>(() => defaultRecipe(DEFAULT_STYLE));+ const [appearanceTab, setAppearanceTab] = useState<"character" | "companion">("character");const [style, setStyle] = useState<string>(DEFAULT_STYLE);const [providerId, setProviderId] = useState("");const [model, setModel] = useState("");@@ -144,8 +147,8 @@ export function CreateAgentDialog({ open, onClose, onCreated }: CreateAgentDialo// joined with the Agents tab's credential truth exactly as the chat's// composer joins it, plus the subscription logins stored per CLI.const catalog = useQuery({- queryKey: ["agent-chat", "catalog", "society"],- queryFn: () => fetchAgentChatCatalog("society"),+ queryKey: ["agent-chat", "catalog", "society", accountId],+ queryFn: () => fetchAgentChatCatalog("society", { accountId }),enabled: open,staleTime: 60_000,});@@ -356,7 +359,7 @@ export function CreateAgentDialog({ open, onClose, onCreated }: CreateAgentDialoname,title: title.trim() || t("society.create.title_fallback"),description,- figure: recipe,+ figure: { ...recipe, companion: resolveCompanion(name.trim(), recipe.companion) },palette: { primary: palette.primary, secondary: palette.secondary, accent: palette.accent },provider: seat?.provider.id ?? "",providerLabel: seat?.provider.label ?? t("society.create.provider_unknown"),@@ -642,7 +645,11 @@ export function CreateAgentDialog({ open, onClose, onCreated }: CreateAgentDialo</ScrollArea>{/* ---- right: the character, live ---- */}- <div className="flex min-h-0 flex-col">+ <div className="flex min-h-0 flex-col overflow-y-auto">+ <div className="flex shrink-0 gap-2 border-b border-border p-3" role="tablist" aria-label={t("society.companion.appearance")}>+ {(["character", "companion"] as const).map(tab => <button key={tab} type="button" role="tab" aria-selected={appearanceTab === tab} onClick={() => setAppearanceTab(tab)} className={`rounded-md px-3 py-2 text-sm ${appearanceTab === tab ? "bg-secondary text-foreground" : "text-muted-foreground"}`}>{t(`society.companion.${tab}`)}</button>)}+ </div>+ {appearanceTab === "companion" ? <CompanionEditor value={resolveCompanion(name.trim(), recipe.companion)} onChange={companion => setRecipe(r => ({ ...r, companion }))} disabled={submitting} /> : <><div className="society-figure-column relative min-h-[240px] flex-1"><AgentFigureViewer recipe={recipe} quiet /></div>@@ -823,6 +830,7 @@ export function CreateAgentDialog({ open, onClose, onCreated }: CreateAgentDialo</div></div></div>+ </> }</div></div></Dialog.Content>diff --git a/jarvis/ui/web/frontend/src/components/society/figures/figureRecipe.ts b/jarvis/ui/web/frontend/src/components/society/figures/figureRecipe.tsindex 5d6b546e7c..2d23121db1 100644--- a/jarvis/ui/web/frontend/src/components/society/figures/figureRecipe.ts+++ b/jarvis/ui/web/frontend/src/components/society/figures/figureRecipe.ts@@ -11,6 +11,7 @@*/import { basesForStyle, catalogBaseFor } from "./figureRegistry";+import type { CompanionAppearance } from "../companion/appearance";export const PALETTE_CELLS = ["skin",@@ -37,6 +38,8 @@ export type Palette = Record<PaletteCell, string>;export type FigureArchetype = "biped" | "quadruped" | "spirit";export interface FigureRecipe {+ /** Independent profile identity and world follower; older recipes derive defaults. */+ companion?: CompanionAppearance;contract: 1;archetype: FigureArchetype;/** Catalog base id: "rogue" | "knight" | "mage" | "barbarian" …; an animal id for a quadruped. */diff --git a/jarvis/ui/web/frontend/src/components/society/mars/MarsAgents.tsx b/jarvis/ui/web/frontend/src/components/society/mars/MarsAgents.tsxnew file mode 100644index 0000000000..8c72bbefc2--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/mars/MarsAgents.tsx@@ -0,0 +1,113 @@+import { useEffect, useMemo, useRef } from "react";+import { Html } from "@react-three/drei";+import { useFrame, useThree } from "@react-three/fiber";+import { Group, Vector3 } from "three";+import { useT } from "@/i18n";+import { type NavigationRecord } from "./navigationApi";+import { useSocietyRoster, type SocietyAgent } from "../data";+import { FigureRig, type FigureDrive } from "../figures/FigureRig";+import { AgentFollower } from "../companion/AgentFollower";+import { resolveCompanion } from "../companion/appearance";+import type { TrailPoint } from "../companion/trail";+import { WORLD, BUILDING_COLLIDERS, surfaceHeight } from "./world";+import { useReducedMotion } from "framer-motion";++function companionClear(point: TrailPoint, radius: number): boolean {+ // Corners of the footprint must stay on the same floor/bridge. Expanded+ // obstacle boxes keep the offset clear of walls, rails and door jambs.+ for (const x of [point[0] - radius, point[0] + radius]) {+ for (const z of [point[2] - radius, point[2] + radius]) {+ if (Math.abs(surfaceHeight(x, z) - point[1]) > 0.3) return false;+ }+ }+ return !BUILDING_COLLIDERS.some(box => point[0] > box.min[0] - radius && point[0] < box.max[0] + radius+ && point[2] > box.min[2] - radius && point[2] < box.max[2] + radius+ && point[1] + 0.08 < box.max[1] && point[1] + radius * 2 > box.min[1]);+}++function companionStart(record: NavigationRecord, gap: number): TrailPoint {+ const current = WORLD.navigation.nodes.find(node => node.id === record.current_node);+ if (!current) return [...record.position];+ let anchor = current.position;+ if (Math.hypot(anchor[0] - record.position[0], anchor[2] - record.position[2]) < 0.05) {+ const edge = WORLD.navigation.edges.find(e => e.from === current.id || e.to === current.id);+ const other = edge && WORLD.navigation.nodes.find(n => n.id === (edge.from === current.id ? edge.to : edge.from));+ if (other) anchor = other.position;+ }+ const distance = Math.hypot(...anchor.map((value, i) => value - record.position[i]));+ const fraction = distance > 0 ? Math.min(1, gap / distance) : 0;+ return record.position.map((value, i) => value + (anchor[i] - value) * fraction) as TrailPoint;+}++function AgentLocation({ record, agent, name, stale, awake, onSelect, following, followAvailable, onFollow, onStopFollow }: {+ record: NavigationRecord; agent?: SocietyAgent; name: string; stale: boolean; awake: boolean; onSelect?: (id: string) => void;+ following: boolean; followAvailable: boolean; onFollow: (id: string) => void; onStopFollow: () => void;+}) {+ const t = useT();+ const reduced = useReducedMotion() ?? false;+ const appearance = resolveCompanion(record.agent_id, agent?.figure?.companion);+ const group = useRef<Group>(null);+ const drive = useRef<FigureDrive>({ mode: "idle", speed: 0 });+ const heading = useRef(0);+ const corner = useRef<TrailPoint | null>(null);+ const initialPosition = useRef(record.position);+ const previous = useRef(record);+ const remaining = useRef(0);+ const target = useRef(new Vector3(...record.position));+ const { invalidate } = useThree();+ useEffect(() => {+ const old = previous.current;+ target.current.fromArray(record.position);+ const dx = record.position[0] - old.position[0], dz = record.position[2] - old.position[2];+ if (Math.hypot(dx, dz) > 0.025) heading.current = Math.atan2(dx, dz);+ if (old.edge_id !== record.edge_id) {+ const node = WORLD.navigation.nodes.find(n => n.id === record.current_node);+ corner.current = node ? [...node.position] as TrailPoint : null;+ }+ drive.current = { mode: record.state === "moving" && !stale ? "walk" : "idle", speed: Math.hypot(dx, dz) / 0.25 };+ // Interpolate only on the same verified segment. A straight shortcut across+ // a corner could pass through geometry; new segments use reported placement.+ remaining.current = !stale && old.edge_id !== null && old.edge_id === record.edge_id && old.current_node === record.current_node ? 0.18 : 0;+ if (!remaining.current) group.current?.position.copy(target.current);+ previous.current = record; invalidate();+ }, [record, stale, awake, invalidate]);+ useFrame((_state, delta) => {+ if (group.current) group.current.rotation.y = heading.current;+ if (!awake || !group.current || remaining.current <= 0) return;+ const step = Math.min(Math.max(delta, 0), remaining.current);+ group.current.position.lerp(target.current, step / remaining.current);+ remaining.current -= step;+ if (remaining.current > 0) invalidate();+ });+ return <><group ref={group} position={initialPosition.current} userData={{ agentId: record.agent_id }}>+ {agent?.figure && <FigureRig recipe={agent.figure} drive={drive} paused={stale || !awake || reduced} />}+ <Html center position={[0, 2.2, 0]} zIndexRange={[16, 1]}>+ <div className="flex items-center gap-1" data-mars-ui>+ <button type="button" data-mars-ui onClick={(event) => { event.stopPropagation(); onSelect?.(record.agent_id); }}+ className="whitespace-nowrap rounded-md border border-border bg-popover px-2 py-1 text-xs text-popover-foreground shadow-sm">+ <strong>{name}</strong><span className="ml-2 text-muted-foreground">{t(stale ? "society.mars.last_known_position" : `society.mars.move_state_${record.state}`)}</span>+ </button>+ <button type="button" aria-label={t(following ? "society.mars.stop_follow_agent" : "society.mars.follow_named_agent").replace("{0}", name)} aria-pressed={following}+ disabled={!following && !followAvailable} onClick={(event) => { event.stopPropagation(); if (following) onStopFollow(); else onFollow(record.agent_id); }}+ className="whitespace-nowrap rounded-md border border-border bg-popover px-2 py-1 text-xs text-popover-foreground shadow-sm disabled:opacity-50">+ {t(following ? "society.mars.stop_follow" : "society.mars.follow")}+ </button>+ </div>+ </Html>+ </group>+ {agent && <AgentFollower owner={group} appearance={appearance} paused={stale || !awake} lead={agent.tier === "lead"} waypoint={corner} initialPosition={companionStart(record, appearance.followDistanceM)} clear={companionClear} />}+ </>;+}++/** Stored characters and their independent companions share authoritative placement. */+export function MarsAgents({ records, names, stale, awake, onSelect, followAgentId, followAvailable, onFollow, onStopFollow }: {+ records: NavigationRecord[]; names: ReadonlyMap<string, string>; stale: boolean; awake: boolean; onSelect?: (id: string) => void;+ followAgentId: string | null; followAvailable: boolean; onFollow: (id: string) => void; onStopFollow: () => void;+}) {+ const roster = useSocietyRoster();+ const agents = useMemo(() => new Map((roster.data?.agents ?? []).map(agent => [agent.agentId, agent])), [roster.data]);+ return <group>{records.filter((row) => row.presence === "placed" && agents.has(row.agent_id)).slice(0, 64).map((record) =>+ <AgentLocation key={record.agent_id} record={record} agent={agents.get(record.agent_id)} name={names.get(record.agent_id) ?? record.agent_id} stale={stale} awake={awake} onSelect={onSelect}+ following={followAgentId === record.agent_id} followAvailable={followAvailable && names.has(record.agent_id)} onFollow={onFollow} onStopFollow={onStopFollow} />,+ )}</group>;+}diff --git a/jarvis/ui/web/frontend/src/components/society/mars/MarsBackgroundControl.tsx b/jarvis/ui/web/frontend/src/components/society/mars/MarsBackgroundControl.tsxnew file mode 100644index 0000000000..90d2482f6e--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/mars/MarsBackgroundControl.tsx@@ -0,0 +1,52 @@+import { useState } from "react";+import { useQuery, useQueryClient } from "@tanstack/react-query";+import { useT } from "@/i18n";+import { z } from "zod";++export const BACKGROUND_MODES = ["foreground", "background", "stopping", "stopped"] as const;+const backgroundSchema = z.object({+ available: z.boolean(), reason: z.string().nullable(), enabled: z.boolean(),+ mode: z.enum(BACKGROUND_MODES), window_open: z.boolean(),+});+const KEY = ["desktop", "background"];++export function MarsBackgroundControl() {+ const t = useT(), client = useQueryClient();+ const [busy, setBusy] = useState(false);+ const [failed, setFailed] = useState(false);+ const state = useQuery({+ queryKey: KEY,+ queryFn: async ({ signal }) => {+ const response = await fetch("/api/window/background", { signal });+ if (!response.ok) throw new Error("background_status_unavailable");+ return backgroundSchema.parse(await response.json());+ },+ refetchInterval: 5000, retry: false,+ });+ const toggle = async () => {+ if (busy || !state.data?.available) return;+ setBusy(true); setFailed(false);+ try {+ const response = await fetch("/api/window/background", {+ method: "POST", headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ enabled: !state.data.enabled }),+ });+ if (!response.ok) throw new Error("background_change_failed");+ const next = backgroundSchema.parse(await response.json());+ client.setQueryData(KEY, next);+ if (next.enabled === state.data.enabled) setFailed(true);+ } catch { setFailed(true); }+ finally { setBusy(false); }+ };+ const headless = state.data?.reason === "headless_host";+ return (+ <div className="flex flex-wrap items-center gap-2 text-xs" data-mars-ui>+ <button type="button" className="mars-use-station disabled:opacity-50" aria-pressed={state.data?.enabled ?? false} disabled={busy || !state.data?.available} onClick={() => void toggle()}>+ {t(headless ? "society.mars.headless_background" : state.data?.enabled ? "society.mars.background_on" : "society.mars.background_off")}+ </button>+ <span role="status" className="text-muted-foreground">+ {t(failed ? "society.mars.background_failed" : headless ? "society.mars.headless_hint" : state.isError || !state.data?.available ? "society.mars.background_unavailable" : state.data?.enabled ? "society.mars.background_hint" : "society.mars.background_enable_hint")}+ </span>+ </div>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/society/mars/MarsNavigationPanel.tsx b/jarvis/ui/web/frontend/src/components/society/mars/MarsNavigationPanel.tsxnew file mode 100644index 0000000000..0ed8f35b0f--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/mars/MarsNavigationPanel.tsx@@ -0,0 +1,73 @@+import { useEffect, useRef, useState } from "react";+import { useQueryClient } from "@tanstack/react-query";+import { useT } from "@/i18n";+import { MarsApiError } from "./api";+import { cancelMove, clearMoveAttempt, currentRoverRide, latestNavigationRecords, readMoveAttempt, saveMoveAttempt, submitMove, type MoveAttempt } from "./navigationApi";+import { MarsRoverPanel } from "./MarsRoverPanel";+import { NAVIGATION_KEY, useMarsNavigation } from "./useMarsNavigation";++export const VISIT_DESTINATIONS = ["communications-console", "outpost-bridge-staging", "outpost-approach"] as const;++/** Moving and stopping here changes physical location, never the agent's real task. */+export function MarsNavigationPanel({ agentId, active = false }: { agentId: string; active?: boolean }) {+ const t = useT();+ const query = useMarsNavigation();+ const client = useQueryClient();+ const pending = useRef<MoveAttempt | null>(readMoveAttempt());+ const [destination, setDestination] = useState(pending.current?.station_id ?? "communications-console");+ const [busy, setBusy] = useState(false), [failed, setFailed] = useState(false);+ const record = latestNavigationRecords(query.data).find((row) => row.agent_id === agentId);+ const riding = !!currentRoverRide(query.data, agentId);+ const inMotion = record && !["arrived", "unreachable", "canceled"].includes(record.state);+ useEffect(() => {+ const attempt = pending.current;+ if (!attempt || busy || query.isError) return;+ if (query.data?.commands.some((row) => row.agent_id === attempt.agent_id && row.request_id === attempt.request_id)) {+ clearMoveAttempt(attempt.request_id); pending.current = null; setFailed(false);+ }+ }, [query.data, query.isError, busy]);+ const move = async (target = destination) => {+ if (busy || !agentId || riding) return;+ const attempt = pending.current ?? { request_id: crypto.randomUUID(), agent_id: agentId, station_id: target };+ pending.current = attempt; saveMoveAttempt(attempt); setBusy(true); setFailed(false);+ try {+ await submitMove(attempt);+ clearMoveAttempt(attempt.request_id);+ if (pending.current?.request_id === attempt.request_id) pending.current = null;+ await client.invalidateQueries({ queryKey: NAVIGATION_KEY });+ } catch (error) {+ if (error instanceof MarsApiError && [400, 401, 403, 404, 409, 422].includes(error.status)) {+ clearMoveAttempt(attempt.request_id); pending.current = null;+ }+ setFailed(true);+ } finally { setBusy(false); }+ };+ const stop = async () => {+ if (!record || busy) return;+ setBusy(true); setFailed(false);+ try { await cancelMove(record); await client.invalidateQueries({ queryKey: NAVIGATION_KEY }); }+ catch { setFailed(true); }+ finally { setBusy(false); }+ };+ return <><section className="grid gap-2 border-t border-border pt-3" aria-label={t("society.mars.visits")} data-mars-ui>+ <h3 className="text-sm font-semibold">{t("society.mars.visits")}</h3>+ <p className="text-xs text-muted-foreground">{t("society.mars.visit_scope")}</p>+ {pending.current && <p className="text-xs text-muted-foreground">{t("society.mars.pending_visit")}: {pending.current.agent_id} · {t(`society.mars.destination_${pending.current.station_id}`)}</p>}+ <label className="grid gap-1 text-sm">{t("society.mars.destination")}+ <select value={destination} disabled={busy || !!pending.current} onChange={(event) => setDestination(event.target.value)} className="rounded border border-border bg-background p-2">+ {VISIT_DESTINATIONS.map((id) => <option key={id} value={id}>{t(`society.mars.destination_${id}`)}</option>)}+ </select>+ </label>+ {destination === "outpost-approach" && <p className="text-xs text-muted-foreground">{t("society.mars.approach_hint")}</p>}+ <div className="flex flex-wrap gap-2 text-sm">+ <button type="button" disabled={busy || riding || !agentId || (!pending.current && !!inMotion)} onClick={() => void move()} className="rounded border border-border px-2 py-1 disabled:opacity-50">{t(pending.current ? "society.mars.retry_visit" : "society.mars.start_visit")}</button>+ {inMotion && !riding && <button type="button" disabled={busy} onClick={() => void stop()} className="rounded border border-border px-2 py-1 disabled:opacity-50">{t("society.mars.stop_visit")}</button>}+ {record?.presence === "placed" && !inMotion && !riding && record.station_id !== "outpost-bridge-staging" && <button type="button" disabled={busy || !!pending.current} onClick={() => void move("outpost-bridge-staging")} className="rounded border border-border px-2 py-1 disabled:opacity-50">{t("society.mars.park_by_bridge")}</button>}+ </div>+ {record && <p role="status" className="text-sm">{t(`society.mars.move_state_${record.state}`)}{record.presence === "spawn_queue" ? ` · ${t("society.mars.waiting_entry")}` : ""}</p>}+ {record?.state === "canceled" && record.presence === "placed" && <p className="text-xs text-muted-foreground">{t("society.mars.stopped_in_place")}</p>}+ {query.isError && <p role="status" className="text-sm">{t("society.mars.positions_offline")}</p>}+ {failed && <p role="alert" className="text-sm">{t(pending.current ? "society.mars.visit_uncertain" : "society.mars.request_failed")}</p>}+ </section><MarsRoverPanel agentId={agentId} active={active} snapshot={query.data}+ online={query.isSuccess && query.isFetchedAfterMount && !query.isError && query.fetchStatus !== "paused"} /></>;+}diff --git a/jarvis/ui/web/frontend/src/components/society/mars/MarsRoverPanel.test.tsx b/jarvis/ui/web/frontend/src/components/society/mars/MarsRoverPanel.test.tsxnew file mode 100644index 0000000000..6d46759bac--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/mars/MarsRoverPanel.test.tsx@@ -0,0 +1,79 @@+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";+import { MarsRoverPanel } from "./MarsRoverPanel";+import { readRoverAttempt, saveRoverAttempt } from "./roverApi";+import { roverRide, roverSnapshot } from "./roverFixtures.test-support";++vi.mock("@/i18n", () => ({ useT: () => (key: string) => key }));+vi.mock("@tanstack/react-query", () => ({ useQueryClient: () => ({ invalidateQueries: async () => undefined }) }));+afterEach(() => { cleanup(); sessionStorage.clear(); vi.unstubAllGlobals(); });++describe("explicit server-authorized rover controls", () => {+ it("does not board from arrival or stale display state without an explicit action", async () => {+ const fetcher = vi.fn(async () => new Response(JSON.stringify(roverRide)));+ vi.stubGlobal("fetch", fetcher);+ const view = render(<MarsRoverPanel agentId="agent-one" active snapshot={roverSnapshot()} online={false} />);+ const board = screen.getByRole("button", { name: "society.mars.rover_board" }) as HTMLButtonElement;+ expect(board.disabled).toBe(true);+ fireEvent.click(board);+ expect(fetcher).not.toHaveBeenCalled();+ view.rerender(<MarsRoverPanel agentId="agent-one" active snapshot={roverSnapshot()} online />);+ expect(fetcher).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole("button", { name: "society.mars.rover_board" }));+ await waitFor(() => expect(fetcher).toHaveBeenCalledTimes(1));+ const [path] = fetcher.mock.calls[0] as unknown as [string, RequestInit];+ expect(path).toContain("/agents/agent-one/rides/ride-one/board");+ await waitFor(() => expect(readRoverAttempt()).toBeNull());+ });++ it("retains the exact unacknowledged action through unmount and explicit retry", async () => {+ const fetcher = vi.fn().mockRejectedValueOnce(new Error("lost connection"))+ .mockResolvedValue(new Response(JSON.stringify(roverRide)));+ vi.stubGlobal("fetch", fetcher);+ const first = render(<MarsRoverPanel agentId="agent-one" active snapshot={roverSnapshot()} online />);+ fireEvent.click(screen.getByRole("button", { name: "society.mars.rover_board" }));+ await screen.findByRole("alert");+ const pending = readRoverAttempt();+ expect(pending?.action).toBe("board");+ first.unmount();+ render(<MarsRoverPanel agentId="agent-one" active snapshot={roverSnapshot()} online />);+ expect(fetcher).toHaveBeenCalledTimes(1);+ fireEvent.click(screen.getByRole("button", { name: "society.mars.rover_retry" }));+ await waitFor(() => expect(fetcher).toHaveBeenCalledTimes(2));+ expect(fetcher.mock.calls[1]).toEqual(fetcher.mock.calls[0]);+ await waitFor(() => expect(readRoverAttempt()).toBeNull());+ });++ it("scopes a selected route to the attached agent and blocks inactive-agent controls", async () => {+ const fetcher = vi.fn(async () => new Response(JSON.stringify(roverRide)));+ vi.stubGlobal("fetch", fetcher);+ const snapshot = roverSnapshot([{ ...roverRide, state: "boarded", attached: true }]);+ const view = render(<MarsRoverPanel agentId="agent-one" active={false} snapshot={snapshot} online />);+ const travel = screen.getByRole("button", { name: "society.mars.rover_travel" }) as HTMLButtonElement;+ expect(travel.disabled).toBe(true);+ view.rerender(<MarsRoverPanel agentId="agent-one" active snapshot={snapshot} online />);+ fireEvent.click(screen.getByRole("button", { name: "society.mars.rover_travel" }));+ await waitFor(() => expect(fetcher).toHaveBeenCalledTimes(1));+ const [path, init] = fetcher.mock.calls[0] as unknown as [string, RequestInit];+ expect(path).toBe("/api/society/mars/agents/agent-one/rides/ride-one/travel");+ expect(JSON.parse(init.body as string).destination_dock_id).toBe("outpost-b");+ await waitFor(() => expect(readRoverAttempt()).toBeNull());+ });++ it("recovers an exact saved action after its actor is archived without granting new actions", async () => {+ const pending = { action: "exit" as const, agent_id: "archived-agent", ride_id: "old-ride", request_id: crypto.randomUUID() };+ saveRoverAttempt(pending);+ const fetcher = vi.fn(async () => new Response(JSON.stringify({ ...roverRide, state: "completed", attached: false })));+ vi.stubGlobal("fetch", fetcher);+ render(<MarsRoverPanel agentId="" active={false} snapshot={roverSnapshot([], [])} online />);+ const retry = screen.getByRole("button", { name: "society.mars.rover_retry" }) as HTMLButtonElement;+ expect(retry.disabled).toBe(false);+ fireEvent.click(retry);+ await waitFor(() => expect(fetcher).toHaveBeenCalledTimes(1));+ const [path, init] = fetcher.mock.calls[0] as unknown as [string, RequestInit];+ expect(path).toBe("/api/society/mars/agents/archived-agent/rides/old-ride/exit");+ expect(JSON.parse(init.body as string)).toEqual({ request_id: pending.request_id });+ await waitFor(() => expect(readRoverAttempt()).toBeNull());+ expect((screen.getByRole("button", { name: "society.mars.rover_reserve" }) as HTMLButtonElement).disabled).toBe(true);+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/mars/MarsRoverPanel.tsx b/jarvis/ui/web/frontend/src/components/society/mars/MarsRoverPanel.tsxnew file mode 100644index 0000000000..70f458016c--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/mars/MarsRoverPanel.tsx@@ -0,0 +1,103 @@+import { useEffect, useRef, useState } from "react";+import { useQueryClient } from "@tanstack/react-query";+import { useT } from "@/i18n";+import { MarsApiError } from "./api";+import { currentRoverRide, type NavigationSnapshot } from "./navigationApi";+import { clearRoverAttempt, readRoverAttempt, saveRoverAttempt, submitRoverAction, type RoverAttempt } from "./roverApi";+import { NAVIGATION_KEY } from "./useMarsNavigation";+import { WORLD } from "./world";++const buttonClass = "rounded border border-border px-2 py-1 disabled:opacity-50";++/** Rides move actual agents. The local player capsule has no server ride authority. */+export function MarsRoverPanel({ agentId, active, snapshot, online }: {+ agentId: string; active: boolean; snapshot?: NavigationSnapshot; online: boolean;+}) {+ const t = useT();+ const client = useQueryClient();+ const [pending, setPending] = useState(readRoverAttempt);+ const [busy, setBusy] = useState(false), [failed, setFailed] = useState(false);+ const sending = useRef(false);+ const [vehicleId, setVehicleId] = useState(WORLD.navigation.rovers[0]?.id ?? "");+ const [destination, setDestination] = useState("");+ const ride = currentRoverRide(snapshot, agentId);+ const vehicle = snapshot?.vehicles.find((row) => row.vehicle_id === (ride?.vehicle_id ?? vehicleId));+ const dock = WORLD.navigation.rover_docks.find((row) => row.node_id === vehicle?.current_node && !vehicle?.edge_id);+ const destinations = WORLD.navigation.rover_docks.filter((row) => row.id !== dock?.id);+ const selectedDestination = destinations.some((row) => row.id === destination) ? destination : destinations[0]?.id ?? "";+ const enabled = online && active && !!agentId && !busy;+ const available = !!vehicle && vehicle.presence === "placed" && !vehicle.ride_id && !!dock;+ const travelReady = ride?.attached && ["boarded", "arrived", "stopped", "exit_blocked"].includes(ride.state);+ const exitReady = travelReady;++ useEffect(() => {+ // Only reservation identities are represented in ride receipts. Never infer+ // acknowledgement of a later action from a coincidentally matching state.+ if (!online || busy || pending?.action !== "reserve") return;+ if (snapshot?.rides.some((row) => row.agent_id === pending.agent_id && row.request_id === pending.request_id)) {+ clearRoverAttempt(pending.request_id); setPending(null); setFailed(false);+ }+ }, [snapshot, online, busy, pending]);++ const send = async (attempt: RoverAttempt, recovery = false) => {+ if (sending.current || busy || !online) return;+ // Exact replay can recover a lost acknowledgement even after the original+ // agent is archived. The server replays accepted identities before checking+ // current authority; an unaccepted request still has to pass that authority.+ if (!recovery && (!enabled || pending || attempt.agent_id !== agentId)) return;+ sending.current = true; setBusy(true); setFailed(false); setPending(attempt); saveRoverAttempt(attempt);+ try {+ await submitRoverAction(attempt);+ clearRoverAttempt(attempt.request_id); setPending(null);+ await client.invalidateQueries({ queryKey: NAVIGATION_KEY });+ } catch (error) {+ if (error instanceof MarsApiError && [400, 401, 403, 404, 409, 422].includes(error.status)) {+ clearRoverAttempt(attempt.request_id); setPending(null);+ await client.invalidateQueries({ queryKey: NAVIGATION_KEY });+ }+ setFailed(true);+ } finally { sending.current = false; setBusy(false); }+ };+ const action = (kind: "board" | "travel" | "cancel" | "exit") => {+ if (!ride || pending) return;+ const base = { request_id: crypto.randomUUID(), agent_id: agentId, ride_id: ride.ride_id };+ void send(kind === "travel" ? { ...base, action: kind, destination_dock_id: selectedDestination } : { ...base, action: kind });+ };+ return <section className="grid gap-2 border-t border-border pt-3" aria-label={t("society.mars.rover_title")} data-mars-ui>+ <h3 className="text-sm font-semibold">{t("society.mars.rover_title")}</h3>+ <p className="text-xs text-muted-foreground">{t("society.mars.rover_scope")}</p>+ {!active && <p role="status" className="text-xs">{t("society.mars.rover_active_required")}</p>}+ {pending && <div className="grid gap-2 text-sm">+ <p>{t("society.mars.rover_pending")} · {pending.agent_id} · {t(`society.mars.rover_action_${pending.action}`)}</p>+ <button type="button" disabled={!online || busy} className={buttonClass} onClick={() => void send(pending, true)}>{t("society.mars.rover_retry")}</button>+ {pending.agent_id !== agentId && <p className="text-xs text-muted-foreground">{t("society.mars.rover_pending_other")}</p>}+ </div>}+ {!ride && <>+ <label className="grid gap-1 text-sm">{t("society.mars.rover_vehicle")}+ <select value={vehicleId} disabled={!enabled || !!pending} onChange={(event) => setVehicleId(event.target.value)} className="rounded border border-border bg-background p-2">+ {WORLD.navigation.rovers.map((row) => <option key={row.id} value={row.id}>{t(`society.mars.rover_vehicle_${row.id}`)}</option>)}+ </select>+ </label>+ <button type="button" disabled={!enabled || !!pending || !available} className={buttonClass} onClick={() => void send({ action: "reserve", agent_id: agentId, request_id: crypto.randomUUID(), vehicle_id: vehicleId })}>{t("society.mars.rover_reserve")}</button>+ {online && !available && <p role="status" className="text-xs">{t("society.mars.rover_unavailable")}</p>}+ </>}+ {ride && <>+ <p role="status" className="text-sm">{t(`society.mars.rover_state_${ride.state}`)}</p>+ {ride.attached && <p className="text-xs text-muted-foreground">{t("society.mars.rover_attached")}</p>}+ <label className="grid gap-1 text-sm">{t("society.mars.rover_route")}+ <select value={selectedDestination} disabled={!enabled || !!pending || !travelReady} onChange={(event) => setDestination(event.target.value)} className="rounded border border-border bg-background p-2">+ {destinations.map((row) => <option key={row.id} value={row.id}>{t(`society.mars.rover_dock_${row.id}`)}</option>)}+ </select>+ </label>+ <div className="flex flex-wrap gap-2 text-sm">+ {ride.state === "ready_to_board" && <button type="button" disabled={!enabled || !!pending} className={buttonClass} onClick={() => action("board")}>{t("society.mars.rover_board")}</button>}+ {travelReady && <button type="button" disabled={!enabled || !!pending || !selectedDestination} className={buttonClass} onClick={() => action("travel")}>{t("society.mars.rover_travel")}</button>}+ <button type="button" disabled={!enabled || !!pending || ride.state === "stopped"} className={buttonClass} onClick={() => action("cancel")}>{t(ride.attached ? "society.mars.rover_stop" : "society.mars.rover_cancel")}</button>+ {exitReady && <button type="button" disabled={!enabled || !!pending} className={buttonClass} onClick={() => action("exit")}>{t("society.mars.rover_exit")}</button>}+ </div>+ {ride.state === "exit_blocked" && <p className="text-xs text-muted-foreground">{t("society.mars.rover_exit_blocked")}</p>}+ </>}+ {!online && <p role="status" className="text-sm">{t("society.mars.rover_offline")}</p>}+ {failed && <p role="alert" className="text-sm">{t(pending ? "society.mars.rover_uncertain" : "society.mars.request_failed")}</p>}+ </section>;+}diff --git a/jarvis/ui/web/frontend/src/components/society/mars/MarsRovers.tsx b/jarvis/ui/web/frontend/src/components/society/mars/MarsRovers.tsxnew file mode 100644index 0000000000..e66a591f49--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/mars/MarsRovers.tsx@@ -0,0 +1,30 @@+import { Html } from "@react-three/drei";+import { useT } from "@/i18n";+import type { RoverRideRecord, VehicleRecord } from "./navigationApi";++/** Confirmed vehicle locations, not final rover geometry or client simulation. */+export function MarsRovers({ vehicles, rides, names, stale, followAgentId, followAvailable, onFollow, onStopFollow }: {+ vehicles: VehicleRecord[]; rides: RoverRideRecord[]; names: ReadonlyMap<string, string>; stale: boolean;+ followAgentId: string | null; followAvailable: boolean; onFollow: (id: string) => void; onStopFollow: () => void;+}) {+ const t = useT();+ return <group>{vehicles.filter((vehicle) => vehicle.presence === "placed").map((vehicle) => {+ const rider = rides.find((ride) => ride.attached && ride.ride_id === vehicle.ride_id && ride.vehicle_id === vehicle.vehicle_id);+ const name = rider ? names.get(rider.agent_id) ?? rider.agent_id : "";+ const following = !!rider && followAgentId === rider.agent_id;+ return <group key={vehicle.vehicle_id} position={vehicle.position}>+ <Html center position={[0, 3, 0]} zIndexRange={[16, 1]}>+ <div className="grid gap-1 whitespace-nowrap rounded-md border border-border bg-popover px-2 py-1 text-xs text-popover-foreground shadow-sm" data-mars-ui>+ <strong>{t(`society.mars.rover_vehicle_${vehicle.vehicle_id}`)}</strong>+ <span className="text-muted-foreground">{t(stale ? "society.mars.last_known_position" : "society.mars.rover_marker")}</span>+ {rider && <span>{name} · {t(`society.mars.rover_state_${rider.state}`)}</span>}+ {rider && <button type="button" aria-pressed={following} disabled={!following && (!followAvailable || !names.has(rider.agent_id))}+ onClick={(event) => { event.stopPropagation(); if (following) onStopFollow(); else onFollow(rider.agent_id); }}+ className="rounded border border-border px-2 py-1 disabled:opacity-50">+ {t(following ? "society.mars.stop_follow_agent" : "society.mars.follow_named_agent").replace("{0}", name)}+ </button>}+ </div>+ </Html>+ </group>;+ })}</group>;+}diff --git a/jarvis/ui/web/frontend/src/components/society/mars/MarsScene.tsx b/jarvis/ui/web/frontend/src/components/society/mars/MarsScene.tsxnew file mode 100644index 0000000000..7e638b30a8--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/mars/MarsScene.tsx@@ -0,0 +1,345 @@+import { useCallback, useEffect, useMemo, useRef, useState, type RefObject } from "react";+import { useFrame, useThree, type ThreeEvent } from "@react-three/fiber";+import { Html, OrbitControls } from "@react-three/drei";+import { Group, Mesh, Object3D, PerspectiveCamera, Vector3 } from "three";+import { useT } from "@/i18n";+import { roadOrientation } from "./roadGeometry";+import { OutpostReference } from "./OutpostReference";+import type { OrbitControls as OrbitControlsInstance } from "three-stdlib";+import { advancePlayer, createPlayer } from "./controller";+import { bindPlayerInput, NO_INPUT } from "./input";+import { avoidCameraCollision, frameInspectionBounds, MAX_POLAR, MIN_POLAR } from "./camera";+import { constrainOrbitPose, orbitLensIsClear } from "./orbitCamera";+import { VIEW_DIRECTIONS, type CameraPose, type Viewpoint, type CameraMode } from "./viewPreferences";+import { MarsAgents } from "./MarsAgents";+import { MarsRovers } from "./MarsRovers";+import type { NavigationRecord, RoverRideRecord, VehicleRecord } from "./navigationApi";+import type { AgentFollowTarget } from "./useAgentFollowTarget";+import { createAgentFollowPose } from "./agentFollowCamera";+import { GigiCompanion } from "../companion/GigiCompanion";+import type { AssistantPresentation } from "../companion/kinematics";+import { usePendingCompanionFocus } from "../companion/usePendingCompanionFocus";+import { OUTPOST_SHADOW, SHADOW_MAP_SIZE, SUN_POSITION, SUN_TARGET } from "./shadows";+import {+ BUILDING_COLLIDERS, createTerrainGeometry, outpostBounds, outpostCloseBounds, PLAYER_SPAWN,+ ROADS, terrainHeight, surfaceHeight, WORLD, WORLD_BOUNDS, type Collider, type Road, type Vec3,+} from "./world";++export type { CameraMode } from "./viewPreferences";+export interface MarsSceneProps {+ hostRef: RefObject<HTMLDivElement>;+ mode: CameraMode;+ neutral: boolean;+ shadows: boolean;+ viewpoint: Viewpoint;+ initialPose: CameraPose | null;+ onSavePose: (pose: CameraPose) => void;+ awake: boolean;+ selected: string | null;+ onSelect: (id: string) => void;+ onOrbit: () => void;+ onOpenStation?: () => void;+ reset: number;+ navigationRecords: NavigationRecord[];+ vehicles: VehicleRecord[];+ rides: RoverRideRecord[];+ agentNames: ReadonlyMap<string, string>;+ navigationStale: boolean;+ onSelectAgent?: (id: string | null) => void;+ followTarget: AgentFollowTarget | null;+ followAgentId: string | null;+ followAvailable: boolean;+ onFollowAgent: (id: string) => void;+ onStopFollow: () => void;+ gigiVisible: boolean;+ gigiFocus: number;+ onGigiFocusApplied: (id: number) => void;+ gigiRecall: number;+ reducedMotion: boolean;+ gigiPresentation: AssistantPresentation;+ onOpenAssistant: () => void;+ onFocusGigi: () => void;+}++function ColliderMesh({ collider, onClick }: { collider: Collider; onClick?: (event: ThreeEvent<MouseEvent>) => void }) {+ const size = collider.max.map((v, index) => v - collider.min[index]) as Vec3;+ const position = collider.min.map((v, index) => v + size[index] / 2) as Vec3;+ return (+ <mesh position={position} onClick={onClick} castShadow receiveShadow>+ <boxGeometry args={size} />+ <meshStandardMaterial color={collider.id.startsWith("operations") ? "#c1beb0" : "#b3a998"} roughness={0.95} />+ </mesh>+ );+}++function RoadMesh({ road }: { road: Road }) {+ const midpoint = road.start.map((v, i) => (v + road.end[i]) / 2) as Vec3;+ const delta = new Vector3(...road.end).sub(new Vector3(...road.start));+ const length = delta.length();+ const orientation = roadOrientation(road.start, road.end);+ const bridge = road.kind === "bridge";+ const supports = bridge ? [0.2, 0.5, 0.8] : [];+ return (+ <group>+ <group position={midpoint} quaternion={orientation}>+ <mesh position={[0, -0.27, 0]} receiveShadow castShadow={bridge}>+ <boxGeometry args={[road.width, 0.7, length + 0.12]} />+ <meshStandardMaterial color={bridge ? "#787975" : "#9e8c70"} roughness={0.92} />+ </mesh>+ {bridge && [-1, 1].map((side) => (+ <mesh key={side} position={[side * (road.width / 2 - 0.12), 0.75, 0]} castShadow>+ <boxGeometry args={[0.24, 1.35, length]} />+ <meshStandardMaterial color="#666a65" roughness={0.85} />+ </mesh>+ ))}+ </group>+ {supports.map((t) => {+ const x = road.start[0] + (road.end[0] - road.start[0]) * t;+ const z = road.start[2] + (road.end[2] - road.start[2]) * t;+ const deck = road.start[1] + (road.end[1] - road.start[1]) * t - 0.62;+ const floor = terrainHeight(x, z);+ if (deck <= floor) return null;+ return (+ <mesh key={t} position={[x, (deck + floor) / 2, z]} castShadow receiveShadow>+ <boxGeometry args={[2.4, deck - floor, 2.4]} />+ <meshStandardMaterial color="#77776e" roughness={1} />+ </mesh>+ );+ })}+ </group>+ );+}++function Terrain() {+ const geometry = useMemo(createTerrainGeometry, []);+ useEffect(() => () => geometry.dispose(), [geometry]);+ return <mesh geometry={geometry} receiveShadow><meshStandardMaterial vertexColors roughness={1} /></mesh>;+}++/** Static blockout is deliberately separate from input and per-frame simulation. */+function ColonyBlockout({ onSelect, outpostReady, labels }: { onSelect: (id: string) => void; outpostReady: boolean; labels: boolean }) {+ const t = useT();+ return (+ <group>+ <Terrain />+ {ROADS.filter((road) => !outpostReady || !["route-01", "route-02", "route-03", "route-04", "route-05"].includes(road.id)).map((road) => <RoadMesh key={road.id} road={road} />)}+ {BUILDING_COLLIDERS.filter((collider) => !outpostReady || !collider.id.startsWith("outpost:")).map((collider) => (+ <ColliderMesh key={collider.id} collider={collider} onClick={(event) => {+ if (event.delta > 4) return;+ event.stopPropagation(); onSelect(collider.id.startsWith("outpost:operations-") ? "operations" : collider.id.replace("outpost:", ""));+ }} />+ ))}+ {/* Neutral massing markers reserve every district, including the northern skyline. */}+ {WORLD.districts.filter((district) => !WORLD.buildings.some((building) => building.district_id === district.id)).map((district) => (+ <mesh key={district.id} position={[district.center[0], district.center[1] + district.landmark_height / 2, district.center[2]]}>+ <boxGeometry args={[district.size[0] * 0.28, district.landmark_height, district.size[1] * 0.28]} />+ <meshStandardMaterial color="#ac9c83" roughness={1} wireframe />+ </mesh>+ ))}+ {labels && WORLD.districts.map((district) => (+ <Html key={district.id} center position={[district.center[0], district.center[1] + district.landmark_height + 10, district.center[2]]} zIndexRange={[12, 0]} style={{ pointerEvents: "none" }}>+ <div className="mars-district-label"><strong>{district.name}</strong><span>{t(district.id === "communications-outpost" && outpostReady ? "society.mars.reference_pending" : "society.mars.district_blockout")}</span></div>+ </Html>+ ))}+ {labels && <Html center position={[294, 61.8, 74]} zIndexRange={[12, 0]} style={{ pointerEvents: "none" }}>+ <div className="mars-door-label">{t("society.mars.entrance")}</div>+ </Html>}+ {!outpostReady && <mesh position={[294, 58.6, 63]}><boxGeometry args={[2, 1.1, 0.8]} /><meshStandardMaterial color="#ceab56" roughness={0.7} /></mesh>}+ </group>+ );+}++export function MarsScene({ hostRef, mode, neutral, shadows, viewpoint, initialPose, onSavePose, awake, selected, onSelect, onOrbit, onOpenStation, reset, navigationRecords, vehicles, rides, agentNames, navigationStale, onSelectAgent, followTarget, followAgentId, followAvailable, onFollowAgent, onStopFollow, gigiVisible, gigiFocus, onGigiFocusApplied, gigiRecall, reducedMotion, gigiPresentation, onOpenAssistant, onFocusGigi }: MarsSceneProps) {+ const t = useT();+ const gigiPosition = useRef<Vec3 | null>(null);+ const [gigiPoseVersion, setGigiPoseVersion] = useState(0);+ const gigiPositionReady = useCallback(() => setGigiPoseVersion((value) => value + 1), []);+ const sunTarget = useMemo(() => {+ const target = new Object3D(); target.position.fromArray(SUN_TARGET); return target;+ }, []);+ const [outpostReady, setOutpostReady] = useState(false);+ const referenceReady = useCallback((ready: boolean) => {+ setOutpostReady(ready);+ if (hostRef.current) hostRef.current.dataset.marsReference = ready ? "loaded-unapproved" : "unavailable";+ }, [hostRef]);+ const controls = useRef<OrbitControlsInstance>(null);+ const figure = useRef<Group>(null);+ const marker = useRef<Mesh>(null);+ const player = useRef(createPlayer());+ const input = useRef<ReturnType<typeof bindPlayerInput> | null>(null);+ const frameCount = useRef(0), lastTelemetry = useRef(0);+ const { camera, size, invalidate, gl } = useThree();+ const followPose = useMemo(() => followTarget ? createAgentFollowPose(followTarget.position) : null, [followTarget]);+ const orbitYaw = useRef(0.7);+ const followHeight = useRef(2.15);+ const restored = useRef(false);+ const lastCameraPose = useRef<CameraPose | null>(null);+ const rememberCamera = useCallback(() => {+ const value = controls.current;+ if (!value) return null;+ const pose: CameraPose = { position: camera.position.toArray() as Vec3, target: value.target.toArray() as Vec3 };+ lastCameraPose.current = pose;+ return pose;+ }, [camera]);+ const constrainOrbit = useCallback(() => {+ const value = controls.current;+ if (!value) return null;+ const wanted: CameraPose = { position: camera.position.toArray() as Vec3, target: value.target.toArray() as Vec3 };+ const safe = constrainOrbitPose(lastCameraPose.current ?? wanted, wanted);+ camera.position.fromArray(safe.position); value.target.fromArray(safe.target); camera.lookAt(value.target);+ lastCameraPose.current = safe;+ return safe;+ }, [camera]);+ const applyGigiFocus = useCallback((position: Vec3) => {+ if (!controls.current || mode === "follow") return false;+ const target: Vec3 = [position[0], position[1] + 0.2, position[2]];+ const desired: Vec3 = [position[0] - 1.05, position[1] + 0.6, position[2] + 1.8];+ camera.position.fromArray(avoidCameraCollision(target, desired));+ controls.current.target.fromArray(target); controls.current.update();+ rememberCamera(); onSavePose({ position: camera.position.toArray() as Vec3, target }); invalidate();+ onGigiFocusApplied(gigiFocus);+ return true;+ }, [camera, invalidate, onSavePose, gigiFocus, onGigiFocusApplied, mode, rememberCamera]);+ usePendingCompanionFocus(gigiFocus, gigiPosition, gigiPoseVersion, applyGigiFocus);++ useEffect(() => {+ const host = hostRef.current;+ if (!host || mode !== "player" || !awake) { input.current?.clear(); return; }+ const binding = bindPlayerInput(host, invalidate, () => { host.blur(); }, (dx, dy) => {+ orbitYaw.current -= dx * 0.005;+ followHeight.current = Math.max(0.5, Math.min(7, followHeight.current + dy * 0.025));+ }, () => {+ const [x, y, z] = player.current.position;+ if (Math.hypot(x - 294, y - 58, z - 64) <= 4) onOpenStation?.();+ });+ input.current = binding;+ return () => { binding.dispose(); input.current = null; };+ }, [hostRef, mode, awake, invalidate, onOpenStation]);++ useEffect(() => {+ const value = controls.current;+ if (!value || !(camera instanceof PerspectiveCamera)) return;+ if (mode === "player") {+ orbitYaw.current = Math.atan2(camera.position.x - value.target.x, camera.position.z - value.target.z);+ invalidate(); return;+ }+ if (mode === "orbit" || mode === "follow") {+ if (!restored.current && initialPose) {+ const safe = orbitLensIsClear(initialPose.position) ? initialPose : frameInspectionBounds(outpostCloseBounds(), size.width / Math.max(1, size.height));+ value.target.fromArray(safe.target);+ camera.position.fromArray(safe.position);+ value.update(); rememberCamera(); invalidate();+ }+ restored.current = true;+ return;+ }+ restored.current = true;+ const bounds = mode === "overview" ? WORLD_BOUNDS : viewpoint === "close_reference" ? outpostCloseBounds() : outpostBounds();+ const frame = frameInspectionBounds(bounds, size.width / Math.max(1, size.height), WORLD.view.overview_padding,+ mode === "outpost" ? VIEW_DIRECTIONS[viewpoint] : VIEW_DIRECTIONS.reference);+ camera.position.fromArray(frame.position);+ camera.far = Math.max(8000, frame.distance * 4);+ camera.updateProjectionMatrix();+ value.target.fromArray(frame.target);+ value.update(); rememberCamera(); invalidate();+ }, [camera, size.width, size.height, mode, reset, invalidate, viewpoint, initialPose, rememberCamera]);++ useEffect(() => {+ const value = controls.current;+ if (mode !== "follow" || !awake || !value || !followPose) return;+ value.target.fromArray(followPose.target); value.update();+ camera.position.fromArray(followPose.position); camera.lookAt(...followPose.target);+ rememberCamera(); onSavePose(followPose); invalidate();+ }, [mode, awake, followPose, camera, invalidate, onSavePose, rememberCamera]);++ useEffect(() => {+ const value = controls.current;+ const building = WORLD.buildings.find((item) => item.id === selected);+ if (!value || !building) return;+ const [x, y, z] = building.position, [w, h, d] = building.size;+ // Aim outside the facade rather than putting the orbit pivot inside solid geometry.+ value.target.set(x, y + Math.min(2.4, h / 2), z + d / 2 + 1.2);+ camera.position.set(x + w * 0.6, y + h + 12, z + d + 24);+ value.update(); rememberCamera(); invalidate();+ }, [selected, camera, invalidate, rememberCamera]);++ useFrame(({ clock }, delta) => {+ const value = controls.current;+ if (!value || !awake) return;+ const command = mode === "player" ? input.current?.read() ?? NO_INPUT : NO_INPUT;+ const steps = advancePlayer(player.current, command, orbitYaw.current, delta);+ if (steps > 0) input.current?.consume();+ if (figure.current) { figure.current.position.fromArray(player.current.position); figure.current.rotation.y = player.current.yaw; }+ if (marker.current) marker.current.visible = mode !== "player";+ if (mode === "player") {+ const [x, y, z] = player.current.position;+ const target: Vec3 = [x, y + 1.45, z];+ const desired: Vec3 = [x + Math.sin(orbitYaw.current) * 6, y + 1.45 + followHeight.current, z + Math.cos(orbitYaw.current) * 6];+ const position = avoidCameraCollision(target, desired);+ camera.position.fromArray(position);+ value.target.fromArray(target); camera.lookAt(...target);+ } else if (mode === "follow" && followPose) {+ // Controls update first. Reapply the collision-safe lens after their zoom+ // limits, which must not push a short obstructed sightline through a wall.+ camera.position.fromArray(followPose.position);+ value.target.fromArray(followPose.target); camera.lookAt(...followPose.target);+ } else if (mode === "orbit") {+ constrainOrbit();+ }+ rememberCamera();+ frameCount.current++;+ if (clock.elapsedTime - lastTelemetry.current > 0.25) {+ lastTelemetry.current = clock.elapsedTime;+ const host = hostRef.current;+ if (host) {+ host.dataset.marsPlayer = player.current.position.map((v) => v.toFixed(3)).join(",");+ host.dataset.marsGrounded = String(player.current.grounded);+ host.dataset.marsFrames = String(frameCount.current);+ host.dataset.marsDrawCalls = String(gl.info.render.calls);+ host.dataset.marsTriangles = String(gl.info.render.triangles);+ host.dataset.marsCamera = camera.position.toArray().map((v) => v.toFixed(2)).join(",");+ host.dataset.marsTarget = value.target.toArray().map((v) => v.toFixed(2)).join(",");+ host.dataset.gigiPosition = gigiPosition.current?.map((v) => v.toFixed(3)).join(",") ?? "pending";+ }+ }+ // Reduced-motion scenes redraw only for deliberate input, gravity or camera interaction.+ if (mode === "player" && (command.forward || command.right || command.jump || !player.current.grounded)) invalidate();+ });++ return (+ <>+ <color attach="background" args={[neutral ? "#d0d1cd" : "#b8a394"]} />+ <hemisphereLight args={[neutral ? "#ffffff" : "#e4d6c0", "#584333", neutral ? 1.25 : 0.85]} />+ <primitive object={sunTarget} />+ <directionalLight target={sunTarget} position={SUN_POSITION} intensity={neutral ? 2 : 3.4} color={neutral ? "#ffffff" : "#ffdfb0"} castShadow={shadows}+ shadow-mapSize={[SHADOW_MAP_SIZE, SHADOW_MAP_SIZE]} shadow-camera-left={OUTPOST_SHADOW.left} shadow-camera-right={OUTPOST_SHADOW.right}+ shadow-camera-top={OUTPOST_SHADOW.top} shadow-camera-bottom={OUTPOST_SHADOW.bottom} shadow-camera-near={OUTPOST_SHADOW.near}+ shadow-camera-far={OUTPOST_SHADOW.far} shadow-bias={OUTPOST_SHADOW.bias} shadow-normalBias={OUTPOST_SHADOW.normalBias} />+ <ColonyBlockout onSelect={onSelect} outpostReady={outpostReady} labels={mode === "overview"} />+ <OutpostReference onSelect={onSelect} onReady={referenceReady} />+ <MarsAgents records={navigationRecords} names={agentNames} stale={navigationStale} awake={awake} onSelect={onSelectAgent}+ followAgentId={followAgentId} followAvailable={followAvailable} onFollow={onFollowAgent} onStopFollow={onStopFollow} />+ <MarsRovers vehicles={vehicles} rides={rides} names={agentNames} stale={navigationStale}+ followAgentId={followAgentId} followAvailable={followAvailable} onFollow={onFollowAgent} onStopFollow={onStopFollow} />+ <GigiCompanion player={player} colliders={BUILDING_COLLIDERS} getGround={surfaceHeight} awake={awake}+ reducedMotion={reducedMotion} visible={gigiVisible} presentation={gigiPresentation}+ recallSequence={gigiRecall} positionRef={gigiPosition} onPositionReady={gigiPositionReady}+ onOpenAssistant={onOpenAssistant} onFocus={onFocusGigi}+ markerLabel={t("society.mars.gigi_focus")} unavailableLabel={t("society.mars.gigi_unavailable")} />+ <group ref={figure} position={PLAYER_SPAWN}>+ <mesh position={[0, 0.9, 0]} castShadow><capsuleGeometry args={[0.32, 1.15, 5, 12]} /><meshStandardMaterial color="#f0c75c" roughness={0.8} /></mesh>+ <mesh position={[0, 1.25, 0.31]}><boxGeometry args={[0.32, 0.15, 0.1]} /><meshStandardMaterial color="#393a38" /></mesh>+ <mesh ref={marker} position={[0, 4, 0]}><coneGeometry args={[0.75, 2, 8]} /><meshBasicMaterial color="#f0c75c" /></mesh>+ </group>+ <OrbitControls+ ref={controls} makeDefault enabled={mode !== "player" && awake} enableDamping={false}+ minPolarAngle={MIN_POLAR} maxPolarAngle={MAX_POLAR} minDistance={WORLD.view.near_inspection_m}+ maxDistance={6000} screenSpacePanning zoomToCursor zoomSpeed={0.65} panSpeed={0.8} rotateSpeed={0.65} onStart={onOrbit}+ onEnd={() => {+ const safe = constrainOrbit();+ if (safe) onSavePose(safe);+ }}+ />+ </>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/society/mars/MarsStationPanel.tsx b/jarvis/ui/web/frontend/src/components/society/mars/MarsStationPanel.tsxnew file mode 100644index 0000000000..68dc0a9a12--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/mars/MarsStationPanel.tsx@@ -0,0 +1,130 @@+import { useEffect, useRef, useState } from "react";+import { useQuery, useQueryClient } from "@tanstack/react-query";+import { useLocaleChunk, useT } from "@/i18n";+import { containsCredential } from "./credentialInput";+import { MarsNavigationPanel } from "./MarsNavigationPanel";+import {+ WORLD_ID, cancelMarsCommand, fetchMarsRoster, fetchMarsSnapshot, submitMarsDraft,+ readDraftAttempt, saveDraftAttempt, clearDraftAttempt, MarsApiError,+ type DraftAttempt, type MarsCommand,+} from "./api";++const SNAPSHOT_KEY = ["mars", WORLD_ID, "snapshot"];++/** Operator control remains available independently of player travel or graphics. */+export function MarsStationPanel({ onClose, onOpenAgent }: {+ onClose: () => void; onOpenAgent?: (id: string) => void;+}) {+ const t = useT();+ const ready = useLocaleChunk("society");+ const client = useQueryClient();+ const attempt = useRef<DraftAttempt | null>(readDraftAttempt());+ const [agentId, setAgentId] = useState(attempt.current?.agent_id ?? "");+ const [draft, setDraft] = useState(attempt.current?.draft ?? "");+ const [busy, setBusy] = useState(false);+ const [failed, setFailed] = useState(false);+ const [credentialInput, setCredentialInput] = useState(false);+ const snapshot = useQuery({+ queryKey: SNAPSHOT_KEY,+ queryFn: ({ signal }) => fetchMarsSnapshot(signal),+ refetchInterval: 2500, retry: false,+ });+ const roster = useQuery({+ queryKey: ["mars", WORLD_ID, "roster"],+ queryFn: ({ signal }) => fetchMarsRoster(signal),+ retry: false,+ });+ const activeAgents = (roster.data ?? []).filter((agent) => agent.state === "active");+ const selectedAgent = agentId || activeAgents[0]?.agent_id || "";+ useEffect(() => {+ const pending = attempt.current;+ if (!pending || busy || snapshot.isError) return;+ const recorded = snapshot.data?.commands.some(+ (command) => command.request_id === pending.request_id && command.agent_id === pending.agent_id,+ );+ if (recorded) {+ clearDraftAttempt(pending.request_id);+ attempt.current = null; setDraft(""); setFailed(false);+ }+ }, [snapshot.data, snapshot.isError, busy]);+ const submit = async () => {+ if (busy || (!attempt.current && (!selectedAgent || !draft.trim()))) return;+ if (containsCredential(attempt.current?.draft ?? draft)) {+ if (attempt.current) clearDraftAttempt(attempt.current.request_id);+ attempt.current = null; setDraft(""); setCredentialInput(true); setFailed(true);+ return;+ }+ if (!attempt.current) {+ attempt.current = { request_id: crypto.randomUUID(), agent_id: selectedAgent, draft: draft.trim() };+ saveDraftAttempt(attempt.current);+ }+ const submitted = attempt.current;+ setBusy(true); setFailed(false); setCredentialInput(false);+ try {+ await submitMarsDraft(submitted);+ clearDraftAttempt(submitted.request_id);+ if (attempt.current?.request_id === submitted.request_id) { attempt.current = null; setDraft(""); }+ await client.invalidateQueries({ queryKey: SNAPSHOT_KEY });+ } catch (error) {+ // Confirmed validation/access failures committed no task. Uncertain delivery keeps its ID.+ if (error instanceof MarsApiError && [400, 401, 403, 404, 422].includes(error.status)) {+ clearDraftAttempt(submitted.request_id);+ if (attempt.current?.request_id === submitted.request_id) attempt.current = null;+ setCredentialInput(error.credentialInput);+ if (error.credentialInput) setDraft("");+ }+ setFailed(true);+ } finally { setBusy(false); }+ };+ const cancel = async (command: MarsCommand) => {+ if (busy) return;+ setBusy(true); setFailed(false);+ try {+ await cancelMarsCommand(command);+ await client.invalidateQueries({ queryKey: SNAPSHOT_KEY });+ } catch { setFailed(true); }+ finally { setBusy(false); }+ };+ if (!ready) return null;+ return (+ <aside+ aria-label={t("society.mars.station_title")} data-mars-ui data-mars-station+ className="flex w-full flex-col gap-3 rounded-xl border border-border bg-popover p-4 text-foreground shadow-float"+ >+ <div className="flex items-center justify-between gap-3">+ <h2 className="font-semibold">{t("society.mars.station_title")}</h2>+ <button type="button" onClick={onClose} className="rounded px-2 py-1 hover:bg-accent">{t("society.mars.close")}</button>+ </div>+ <p className="text-sm text-muted-foreground">{t("society.mars.station_scope")}</p>+ <label className="grid gap-1 text-sm">+ {t("society.mars.agent")}+ <select value={selectedAgent} disabled={busy || !!attempt.current} onChange={(event) => setAgentId(event.target.value)} className="rounded border border-border bg-background p-2">+ {activeAgents.map((agent) => <option key={agent.agent_id} value={agent.agent_id}>{agent.name}</option>)}+ </select>+ </label>+ {!activeAgents.length && <p role="status" className="text-sm">{t(roster.isError ? "society.mars.offline" : "society.mars.no_agents")}</p>}+ <label className="grid gap-1 text-sm">+ {t("society.mars.draft")}+ <textarea value={draft} maxLength={4000} rows={4} disabled={busy || !!attempt.current} onChange={(event) => setDraft(event.target.value)} className="resize-y rounded border border-border bg-background p-2" />+ </label>+ <button type="button" disabled={busy || (!attempt.current && (!selectedAgent || !draft.trim()))} onClick={() => void submit()} className="rounded border border-border bg-primary px-3 py-2 text-primary-foreground disabled:opacity-50">+ {t(attempt.current ? "society.mars.retry_same" : "society.mars.prepare_draft")}+ </button>+ {failed && <p role="alert" className="text-sm">{t(credentialInput ? "society.mars.credential_input" : attempt.current ? "society.mars.uncertain" : "society.mars.request_failed")}</p>}+ <MarsNavigationPanel agentId={selectedAgent} active={roster.isSuccess && !roster.isError && roster.fetchStatus !== "paused" && activeAgents.some((agent) => agent.agent_id === selectedAgent)} />+ <h3 className="text-sm font-semibold">{t("society.mars.recorded_work")}</h3>+ {snapshot.isError && <p role="status" className="text-sm">{t("society.mars.offline")}</p>}+ {!snapshot.isError && (snapshot.data?.commands ?? []).slice(0, 12).map((command) => (+ <article key={command.command_id} className="rounded border border-border bg-background p-2 text-sm">+ <p>{activeAgents.find((agent) => agent.agent_id === command.agent_id)?.name ?? command.agent_id} · {t(`society.mars.state_${command.state}`)}</p>+ <p className="break-all font-mono text-[10px] text-muted-foreground">{command.command_id}</p>+ {command.reason && <p className="text-xs">{t("society.mars.inspect_reason")}</p>}+ <div className="mt-2 flex flex-wrap gap-2">+ {onOpenAgent && <button type="button" onClick={() => onOpenAgent(command.agent_id)} className="rounded border border-border px-2 py-1">{t("society.mars.open_conversation")}</button>}+ {!["completed", "failed", "canceled"].includes(command.state) && <button type="button" disabled={busy || command.cancel_requested} onClick={() => void cancel(command)} className="rounded border border-border px-2 py-1 disabled:opacity-50">{t(command.cancel_requested ? "society.mars.stopping" : "society.mars.stop")}</button>}+ </div>+ </article>+ ))}+ </aside>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/society/mars/MarsWorldStage.test.tsx b/jarvis/ui/web/frontend/src/components/society/mars/MarsWorldStage.test.tsxnew file mode 100644index 0000000000..62a2d4c3b0--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/mars/MarsWorldStage.test.tsx@@ -0,0 +1,132 @@+import { cleanup, fireEvent, render, screen } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { ReactNode } from "react";+import type { MarsSceneProps } from "./MarsScene";+import { MarsWorldStage } from "./MarsWorldStage";+import { navigationSnapshotSchema } from "./navigationApi";+import { VIEW_KEY } from "./viewPreferences";+import { WORLD } from "./world";++const queries = vi.hoisted(() => ({ navigation: {} as Record<string, unknown>, roster: {} as Record<string, unknown>, rosterOptions: {} as Record<string, unknown> }));+vi.mock("@/i18n", () => ({ useT: () => (key: string) => key, useLocaleChunk: () => true }));+vi.mock("@tanstack/react-query", () => ({ useQuery: (options: Record<string, unknown>) => { queries.rosterOptions = options; return queries.roster; } }));+vi.mock("@react-three/fiber", () => ({ Canvas: ({ children }: { children: ReactNode }) => <>{children}</> }));+vi.mock("framer-motion", () => ({ useReducedMotion: () => true }));+vi.mock("@/hooks/useCanvasAwake", () => ({ useCanvasAwake: () => true }));+vi.mock("@/hooks/useWebglSurface", () => ({ useWebglSurface: () => ({ generation: 0 }) }));+vi.mock("@/lib/graphDimension", () => ({ useWebglSupported: () => true }));+vi.mock("../companion/useCompanionPresentation", () => ({ useCompanionPresentation: () => "idle" }));+vi.mock("./MarsBackgroundControl", () => ({ MarsBackgroundControl: () => null }));+vi.mock("./useMarsNavigation", async () => {+ const { createContext } = await import("react");+ return { MarsNavigationContext: createContext(null), useMarsNavigation: () => queries.navigation };+});+vi.mock("./MarsScene", () => ({ MarsScene: (props: MarsSceneProps) => <div data-testid="scene" data-focus={props.gigiFocus} data-target={JSON.stringify(props.followTarget)}>+ <button onClick={props.onOrbit}>Manual orbit</button>+ <button onClick={() => props.onSelect("operations")}>Select building</button>+ <button onClick={() => props.onSelectAgent?.("one")}>Inspect agent</button>+ <button onClick={() => props.onSavePose({ position: [300, 82, 130], target: [290, 70, 110] })}>Save camera</button>+</div> }));++const record = {+ command_id: "first", request_id: "request", agent_id: "one", trace_id: "trace",+ world_id: "mars:ordinary", station_id: "communications-console", mode: "pedestrian",+ graph_version: 1, graph_signature: "a".repeat(64), state: "moving", presence: "placed",+ position: [268, 58, 68], current_node: "outpost-arrival", edge_id: "route-03",+ next_node: "console-approach", edge_progress: 0.3, reason: "",+};+function navigation(commands = [record]) {+ return navigationSnapshotSchema.parse({ world_id: WORLD.world_id, schema_version: 1, graph_version: 1,+ graph_signature: "a".repeat(64), seq: 1, commands, occupancies: [] });+}+function stage() { return document.querySelector("[data-mars-world]") as HTMLElement; }+function start() { fireEvent.change(screen.getByRole("combobox", { name: "society.mars.follow_agent" }), { target: { value: "one" } }); }+function saved() { return JSON.parse(localStorage.getItem(VIEW_KEY) ?? "null"); }+beforeEach(() => {+ localStorage.clear();+ queries.navigation = { data: navigation(), isSuccess: true, isFetchedAfterMount: true, isError: false, fetchStatus: "idle" };+ queries.roster = { data: [{ agent_id: "one", name: "Worker", state: "idle" }], isSuccess: true, isFetchedAfterMount: true, isError: false, fetchStatus: "idle" };+});+afterEach(() => { cleanup(); localStorage.clear(); });++describe("Mars stage follow arbitration", () => {+ it("keeps inspection independent, starts follow accessibly, and refreshes only the active roster", () => {+ const inspect = vi.fn(); render(<MarsWorldStage onOpenLedger={() => undefined} onSelectAgent={inspect} />);+ expect(queries.rosterOptions.refetchInterval).toBe(false);+ fireEvent.click(screen.getByText("Inspect agent")); expect(inspect).toHaveBeenCalledWith("one");+ expect(stage().dataset.marsMode).toBe("overview");+ start();+ expect(stage().dataset.marsMode).toBe("follow");+ expect(stage().dataset.marsFollowAgent).toBe("one");+ expect(document.activeElement).toBe(screen.getByRole("application"));+ expect(saved().followAgentId).toBe("one");+ const interval = queries.rosterOptions.refetchInterval as () => number;+ expect(interval()).toBeGreaterThanOrEqual(2500); expect(interval()).toBeLessThan(3000);+ });++ it.each(["Manual orbit", "society.mars.stop_follow", "society.mars.overview", "society.mars.outpost", "society.mars.walk", "Select building"])("%s takes ownership from follow and preserves the last saved pose", (action) => {+ render(<MarsWorldStage onOpenLedger={() => undefined} />); start();+ fireEvent.click(screen.getByText("Save camera")); const pose = saved().pose;+ fireEvent.click(screen.getByRole("button", { name: action }));+ expect(stage().dataset.marsMode).not.toBe("follow");+ expect(stage().dataset.marsFollowAgent).toBe("");+ expect(saved().pose).toEqual(pose); expect(saved().followAgentId).toBeNull();+ expect(queries.rosterOptions.refetchInterval).toBe(false);+ });++ it("cancels pending Gigi focus when following, and gives a new Gigi request camera ownership", () => {+ render(<MarsWorldStage onOpenLedger={() => undefined} />);+ fireEvent.click(screen.getByRole("button", { name: "society.mars.gigi_focus" }));+ expect(screen.getByTestId("scene").dataset.focus).toBe("1");+ start(); expect(screen.getByTestId("scene").dataset.focus).toBe("0");+ fireEvent.click(screen.getByRole("button", { name: "society.mars.gigi_focus" }));+ expect(stage().dataset.marsMode).toBe("orbit"); expect(stage().dataset.marsFollowAgent).toBe("");+ expect(screen.getByTestId("scene").dataset.focus).toBe("2");+ });++ it("holds confirmed placement offline, resumes after reconnect, and cancels confirmed deletion", () => {+ const view = render(<MarsWorldStage onOpenLedger={() => undefined} />); start();+ fireEvent.click(screen.getByText("Save camera"));+ const target = screen.getByTestId("scene").dataset.target;+ queries.navigation = { ...queries.navigation, data: undefined, isSuccess: false, isError: true };+ view.rerender(<MarsWorldStage onOpenLedger={() => undefined} />);+ expect(stage().dataset.marsMode).toBe("follow"); expect(stage().dataset.marsFollowState).toBe("offline");+ expect(screen.getByTestId("scene").dataset.target).toBe(target);+ expect(screen.getByText("society.mars.follow_offline")).toBeTruthy();+ queries.navigation = { ...queries.navigation, data: navigation([{ ...record, command_id: "replacement", position: [274, 58, 72] }]), isSuccess: true, isError: false };+ view.rerender(<MarsWorldStage onOpenLedger={() => undefined} />);+ expect(stage().dataset.marsFollowState).toBe("live");+ expect(JSON.parse(screen.getByTestId("scene").dataset.target ?? "null").position).toEqual([274, 58, 72]);+ queries.roster = { ...queries.roster, data: [] };+ view.rerender(<MarsWorldStage onOpenLedger={() => undefined} />);+ expect(stage().dataset.marsMode).toBe("orbit"); expect(stage().dataset.marsFollowAgent).toBe("");+ expect(screen.getByTestId("scene").dataset.target).toBe("null");+ });++ it.each([true, false])("waits on restoration and uses a safe fallback when the persisted agent is absent (pose=%s)", (hasPose) => {+ localStorage.setItem(VIEW_KEY, JSON.stringify({ world_id: WORLD.world_id, layout_version: WORLD.layout_version,+ mode: "follow", followAgentId: "one", viewpoint: "reference", neutral: false, shadows: true,+ pose: hasPose ? { position: [300, 82, 130], target: [290, 70, 110] } : null }));+ queries.navigation = { ...queries.navigation, data: undefined, isSuccess: false, isFetchedAfterMount: false };+ queries.roster = { ...queries.roster, isFetchedAfterMount: false };+ const view = render(<MarsWorldStage onOpenLedger={() => undefined} />);+ expect(stage().dataset.marsMode).toBe("follow"); expect(stage().dataset.marsFollowState).toBe("waiting");+ expect(screen.getByTestId("scene").dataset.target).toBe("null");+ queries.navigation = { ...queries.navigation, data: navigation([]), isSuccess: true, isFetchedAfterMount: true };+ view.rerender(<MarsWorldStage onOpenLedger={() => undefined} />);+ expect(stage().dataset.marsMode).toBe(hasPose ? "orbit" : "overview");+ });++ it("handles viewport Escape without taking Escape from a form or player mode", () => {+ const view = render(<MarsWorldStage onOpenLedger={() => undefined} />); start();+ const viewport = screen.getByRole("application");+ const input = document.createElement("input"); viewport.append(input); input.focus();+ fireEvent.keyDown(input, { key: "Escape" }); expect(stage().dataset.marsMode).toBe("follow");+ viewport.focus(); expect(fireEvent.keyDown(viewport, { key: "Escape" })).toBe(false);+ expect(stage().dataset.marsMode).toBe("orbit");+ fireEvent.click(screen.getByRole("button", { name: "society.mars.walk" }));+ expect(fireEvent.keyDown(viewport, { key: "Escape" })).toBe(true);+ expect(stage().dataset.marsMode).toBe("player");+ view.unmount();+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/mars/MarsWorldStage.tsx b/jarvis/ui/web/frontend/src/components/society/mars/MarsWorldStage.tsxnew file mode 100644index 0000000000..ff3aba73b8--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/mars/MarsWorldStage.tsx@@ -0,0 +1,175 @@+import { Component, Suspense, useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";+import { useQuery } from "@tanstack/react-query";+import { Canvas } from "@react-three/fiber";+import { useReducedMotion } from "framer-motion";+import { useCanvasAwake } from "@/hooks/useCanvasAwake";+import { useWebglSurface } from "@/hooks/useWebglSurface";+import { useWebglSupported } from "@/lib/graphDimension";+import { useLocaleChunk, useT } from "@/i18n";+import { CAMERA_FOV, fitWorldBounds } from "./camera";+import { MarsScene, type CameraMode } from "./MarsScene";+import { WORLD, WORLD_BOUNDS } from "./world";+import { MarsBackgroundControl } from "./MarsBackgroundControl";+import { readViewPreferences, saveViewPreferences, VIEWPOINTS, type CameraPose, type Viewpoint } from "./viewPreferences";+import { fetchMarsRoster, WORLD_ID } from "./api";+import { agentFollowRecords, pedestrianNavigationRecords } from "./navigationApi";+import { MarsNavigationContext, useMarsNavigation } from "./useMarsNavigation";+import { useEventStore } from "@/store/events";+import { useCompanionPresentation } from "../companion/useCompanionPresentation";+import { readCompanionVisible, writeCompanionVisible } from "../companion/preferences";+import { useCompanionFocusRequests } from "../companion/useCompanionFocusRequests";+import { useAgentFollowTarget } from "./useAgentFollowTarget";+import { bindFollowEscape } from "./followInput";+import { ownsTextOrUi } from "./input";+import "./mars.css";++export interface MarsWorldStageProps {+ topRight?: ReactNode;+ onOpenLedger: () => void;+ onSelectAgent?: (id: string | null) => void;+ stationPanel?: ReactNode;+ onOpenStation?: () => void;+}++class RenderBoundary extends Component<{ children: ReactNode; fallbackText: string }, { failed: boolean }> {+ state = { failed: false };+ static getDerivedStateFromError() { return { failed: true }; }+ componentDidCatch(error: Error) { console.warn("Mars prototype renderer unavailable", error); }+ render() {+ return this.state.failed+ ? <div className="mars-render-fallback" role="status">{this.props.fallbackText}</div>+ : this.props.children;+ }+}++const INITIAL_CAMERA = fitWorldBounds(WORLD_BOUNDS, 1.6).position;++/** New integrated Mars foundation. This stage claims neither final art nor backend job completion. */+export function MarsWorldStage({ topRight, onOpenLedger, onSelectAgent, stationPanel, onOpenStation }: MarsWorldStageProps) {+ const t = useT();+ const ready = useLocaleChunk("society");+ const hostRef = useRef<HTMLDivElement>(null);+ const awake = useCanvasAwake(hostRef);+ const [initial] = useState(readViewPreferences);+ const [mode, setMode] = useState<CameraMode>(initial.mode);+ const [followAgentId, setFollowAgentId] = useState(initial.followAgentId);+ const navigation = useMarsNavigation(awake);+ const roster = useQuery({ queryKey: ["mars", WORLD_ID, "roster"], queryFn: ({ signal }) => fetchMarsRoster(signal), enabled: awake, retry: false, staleTime: 5000,+ refetchOnMount: "always", refetchOnWindowFocus: false, refetchInterval: awake && mode === "follow" ? () => 2500 + Math.random() * 500 : false });+ const navigationRecords = useMemo(() => pedestrianNavigationRecords(navigation.data), [navigation.data]);+ const followRecords = useMemo(() => agentFollowRecords(navigation.data), [navigation.data]);+ const agentNames = useMemo(() => new Map((roster.data ?? []).map((row) => [row.agent_id, row.name])), [roster.data]);+ const { generation } = useWebglSurface(hostRef);+ const webgl = useWebglSupported();+ const reduced = useReducedMotion() ?? false;+ const [neutral, setNeutral] = useState(initial.neutral);+ const [shadows, setShadows] = useState(initial.shadows);+ const [viewpoint, setViewpoint] = useState<Viewpoint>(initial.viewpoint);+ const [pose, setPose] = useState<CameraPose | null>(initial.pose);+ useEffect(() => { saveViewPreferences({ mode, followAgentId, neutral, shadows, viewpoint, pose }); }, [mode, followAgentId, neutral, shadows, viewpoint, pose]);+ const navigationFresh = navigation.isSuccess && navigation.isFetchedAfterMount;+ const rosterFresh = roster.isSuccess && roster.isFetchedAfterMount;+ const followOffline = navigation.isError || roster.isError || navigation.fetchStatus === "paused" || roster.fetchStatus === "paused";+ const followAvailable = navigationFresh && rosterFresh && !followOffline;+ const follow = useAgentFollowTarget(mode === "follow" ? followAgentId : null, {+ records: followRecords, names: agentNames, navigationFresh, rosterFresh,+ offline: followOffline,+ });+ const followCandidates = useMemo(() => followRecords.filter((row) => row.presence === "placed" && agentNames.has(row.agent_id)), [followRecords, agentNames]);+ const [selected, setSelected] = useState<string | null>(null);+ const [reset, setReset] = useState(0);+ const [gigiVisible, setGigiVisible] = useState(() => readCompanionVisible(WORLD.world_id));+ const { pending: gigiFocus, request: requestGigiFocus, acknowledge: acknowledgeGigiFocus, cancel: cancelGigiFocus } = useCompanionFocusRequests();+ const [gigiRecall, setGigiRecall] = useState(0);+ const gigiPresentation = useCompanionPresentation(awake);+ const showGigi = (visible: boolean) => { setGigiVisible(visible); writeCompanionVisible(WORLD.world_id, visible); if (!visible) cancelGigiFocus(); };+ const openAssistant = useCallback(() => useEventStore.getState().setActiveSection("chats"), []);+ const focusGigi = useCallback(() => {+ setGigiVisible(true); writeCompanionVisible(WORLD.world_id, true);+ setFollowAgentId(null); setSelected(null); setMode("orbit"); requestGigiFocus();+ }, [requestGigiFocus]);+ const orbit = useCallback(() => { setFollowAgentId(null); cancelGigiFocus(); setMode("orbit"); }, [cancelGigiFocus]);+ const select = useCallback((id: string) => { setFollowAgentId(null); cancelGigiFocus(); setSelected(id); setMode("orbit"); }, [cancelGigiFocus]);+ const startFollow = useCallback((id: string) => {+ if (!followAvailable || !followCandidates.some((row) => row.agent_id === id)) return;+ cancelGigiFocus(); setSelected(null); setFollowAgentId(id); setMode("follow");+ hostRef.current?.focus({ preventScroll: true });+ }, [cancelGigiFocus, followAvailable, followCandidates]);+ useEffect(() => {+ if (mode !== "follow" || follow.status !== "missing") return;+ setFollowAgentId(null); setMode(pose ? "orbit" : "overview");+ }, [mode, follow.status, pose]);+ useEffect(() => {+ const host = hostRef.current;+ if (!host || mode !== "follow" || !awake || stationPanel) return;+ return bindFollowEscape(host, orbit);+ }, [ready, mode, awake, stationPanel, orbit]);+ const choose = (next: CameraMode) => {+ setFollowAgentId(null); cancelGigiFocus(); setMode(next); setSelected(null);+ if (next === "overview" || next === "outpost") setReset((value) => value + 1);+ if (next === "player") hostRef.current?.focus({ preventScroll: true });+ };+ const selectedBuilding = WORLD.buildings.find((building) => building.id === selected);+ if (!ready) return null;+ return (+ <MarsNavigationContext.Provider value={navigation}>+ <section className="mars-stage" data-mars-world={WORLD.world_id} data-mars-layout={WORLD.layout_version} data-mars-stage="blockout" data-mars-mode={mode} data-mars-follow-agent={followAgentId ?? ""} data-mars-follow-state={follow.status} aria-label={t("society.mars.foundation")}>+ <div className="mars-toolbar" data-mars-ui>+ <div className="mars-title"><strong>{t("society.mars.colony")}</strong><span>{t("society.mars.foundation")}</span></div>+ <div className="mars-actions">+ <button type="button" aria-pressed={mode === "overview"} onClick={() => choose("overview")}>{t("society.mars.overview")}</button>+ <button type="button" aria-pressed={mode === "outpost"} onClick={() => choose("outpost")}>{t("society.mars.outpost")}</button>+ <select aria-label={t("society.mars.viewpoint")} value={viewpoint} onChange={(event) => {+ setViewpoint(event.target.value as Viewpoint); choose("outpost");+ }}>+ {VIEWPOINTS.map((value) => <option key={value} value={value}>{t(`society.mars.view_${value}`)}</option>)}+ </select>+ <button type="button" aria-pressed={mode === "player"} onClick={() => choose("player")}>{t("society.mars.walk")}</button>+ <select aria-label={t("society.mars.follow_agent")} value={mode === "follow" ? followAgentId ?? "" : ""} disabled={!followAvailable}+ onChange={(event) => { if (event.target.value) startFollow(event.target.value); else orbit(); }}>+ <option value="">{t("society.mars.follow_agent")}</option>+ {followCandidates.map((row) => <option key={row.agent_id} value={row.agent_id}>{agentNames.get(row.agent_id)}</option>)}+ </select>+ {mode === "follow" && <button type="button" onClick={orbit}>{t("society.mars.stop_follow")}</button>}+ <button type="button" aria-pressed={neutral} onClick={() => setNeutral((value) => !value)}>{t("society.mars.neutral")}</button>+ <button type="button" aria-pressed={shadows} onClick={() => setShadows((value) => !value)}>{t("society.mars.shadows")}</button>+ {onOpenStation && <button type="button" onClick={onOpenStation}>{t("society.mars.station_title")}</button>}+ <button type="button" onClick={onOpenLedger}>{t("society.mars.ledger")}</button>+ <button type="button" onClick={focusGigi}>{t("society.mars.gigi_focus")}</button>+ <button type="button" onClick={() => { showGigi(true); setGigiRecall((value) => value + 1); }}>{t("society.mars.gigi_recall")}</button>+ <button type="button" aria-pressed={gigiVisible} onClick={() => showGigi(!gigiVisible)}>{t(gigiVisible ? "society.mars.gigi_hide" : "society.mars.gigi_show")}</button>+ {topRight}+ </div>+ </div>+ <div className="mars-scene-container">+ <div ref={hostRef} className="mars-viewport" tabIndex={0} role="application" aria-label={t("society.mars.viewport")} data-mars-player="pending" data-mars-frames="0"+ onPointerDownCapture={(event) => { if (mode === "follow" && !ownsTextOrUi(event.target)) hostRef.current?.focus({ preventScroll: true }); }}>+ {webgl ? (+ <RenderBoundary key={generation} fallbackText={t("society.mars.no_graphics")}>+ <Suspense fallback={<div className="mars-render-fallback" role="status">{t("society.mars.loading")}</div>}>+ <Canvas shadows="percentage" camera={{ position: INITIAL_CAMERA, fov: CAMERA_FOV, near: 0.12, far: 20000 }} dpr={[1, 1.5]} gl={{ antialias: true, alpha: false }} frameloop={!awake ? "never" : reduced ? "demand" : "always"} onPointerMissed={() => { setSelected(null); onSelectAgent?.(null); }}>+ <MarsScene hostRef={hostRef} mode={mode} neutral={neutral} shadows={shadows} viewpoint={viewpoint} initialPose={pose} onSavePose={setPose} awake={awake && !stationPanel} selected={selected} onSelect={select} onOrbit={orbit} onOpenStation={onOpenStation} reset={reset} navigationRecords={navigationRecords} agentNames={agentNames} navigationStale={navigation.isError} onSelectAgent={onSelectAgent}+ vehicles={navigation.data?.vehicles ?? []} rides={navigation.data?.rides ?? []}+ followTarget={follow.target} followAgentId={followAgentId} followAvailable={followAvailable} onFollowAgent={startFollow} onStopFollow={orbit}+ gigiVisible={gigiVisible} gigiFocus={gigiFocus} onGigiFocusApplied={acknowledgeGigiFocus} gigiRecall={gigiRecall} reducedMotion={reduced} gigiPresentation={gigiPresentation} onOpenAssistant={openAssistant} onFocusGigi={focusGigi} />+ </Canvas>+ </Suspense>+ </RenderBoundary>+ ) : <div className="mars-render-fallback" role="status">{t("society.mars.no_graphics")}</div>}+ </div>+ {stationPanel && <div className="mars-station-slot" data-mars-ui>{stationPanel}</div>}+ </div>+ <div className="mars-footer" data-mars-ui>+ {mode === "follow" && <p role="status" aria-live="polite">{t(follow.status === "offline" ? "society.mars.follow_offline" : follow.status === "live" ? "society.mars.following_agent" : "society.mars.follow_waiting").replace("{0}", follow.target?.name ?? agentNames.get(followAgentId ?? "") ?? followAgentId ?? "")}</p>}+ {navigation.isError && <p role="status">{t("society.mars.positions_offline")}</p>}+ <MarsBackgroundControl />+ <p>{t(mode === "player" ? "society.mars.player_help" : "society.mars.orbit_help")}</p>+ <p role="status" aria-live="polite">{selectedBuilding ? `${selectedBuilding.name} — ${t(selectedBuilding.access === "required-interior" ? "society.mars.interior_pending" : "society.mars.access_pending")}` : t("society.mars.placeholder_actor")}</p>+ {selected === "operations" && onOpenStation && <button type="button" className="mars-use-station" onClick={onOpenStation}>{t("society.mars.station_title")}</button>}+ </div>+ </section>+ </MarsNavigationContext.Provider>+ );+}++export default MarsWorldStage;diff --git a/jarvis/ui/web/frontend/src/components/society/mars/OutpostReference.tsx b/jarvis/ui/web/frontend/src/components/society/mars/OutpostReference.tsxnew file mode 100644index 0000000000..49a2c89398--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/mars/OutpostReference.tsx@@ -0,0 +1,68 @@+import { useEffect, useState } from "react";+import { useThree, type ThreeEvent } from "@react-three/fiber";+import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";+import { Material, Mesh, Texture, type Group } from "three";+import outpostUrl from "../../../../../../../../art/studies/mars-outpost-reference/exports/communications-outpost.glb";+import { outpostBuildingAt } from "./buildingSelection";++function dispose(root: Group): void {+ const materials = new Set<Material>(), textures = new Set<Texture>();+ root.traverse((object) => {+ if (!(object instanceof Mesh)) return;+ object.geometry.dispose();+ for (const material of Array.isArray(object.material) ? object.material : [object.material]) {+ materials.add(material);+ for (const value of Object.values(material)) if (value instanceof Texture) textures.add(value);+ }+ });+ for (const texture of textures) texture.dispose();+ for (const material of materials) material.dispose();+}++/** Review asset loaded in the actual renderer, outside the production asset catalog. */+export function OutpostReference({ onSelect, onReady }: {+ onSelect: (id: string) => void; onReady: (ready: boolean) => void;+}) {+ const [scene, setScene] = useState<Group | null>(null);+ const [failed, setFailed] = useState(false);+ const invalidate = useThree((state) => state.invalidate);+ useEffect(() => {+ const controller = new AbortController();+ let owned: Group | null = null;+ let retired = false;+ setFailed(false);+ void fetch(outpostUrl, { signal: controller.signal })+ .then((response) => {+ if (!response.ok) throw new Error("outpost_asset_unavailable");+ return response.arrayBuffer();+ })+ .then((buffer) => new GLTFLoader().parseAsync(buffer, ""))+ .then((asset) => {+ if (retired) { dispose(asset.scene); return; }+ owned = asset.scene;+ owned.traverse((object) => {+ if (object instanceof Mesh) { object.castShadow = true; object.receiveShadow = true; }+ });+ setScene(owned); onReady(true); invalidate();+ })+ .catch((error: unknown) => {+ if (retired) return;+ console.warn("Outpost reference could not load", error instanceof Error ? error.name : "Error");+ setFailed(true); onReady(false); invalidate();+ });+ return () => {+ retired = true; controller.abort();+ if (owned) dispose(owned);+ };+ }, [invalidate, onReady]);+ if (!scene || failed) return null;+ const select = (event: ThreeEvent<MouseEvent>) => {+ if (event.delta > 4) return;+ const point = event.point;+ const building = outpostBuildingAt([point.x, point.y, point.z]);+ if (!building) return;+ event.stopPropagation();+ onSelect(building);+ };+ return <primitive object={scene} position={[320, 58, 50]} onClick={select} dispose={null} />;+}diff --git a/jarvis/ui/web/frontend/src/components/society/mars/agentFollowCamera.test.ts b/jarvis/ui/web/frontend/src/components/society/mars/agentFollowCamera.test.tsnew file mode 100644index 0000000000..68e27a6173--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/mars/agentFollowCamera.test.ts@@ -0,0 +1,37 @@+import { describe, expect, it } from "vitest";+import { createAgentFollowPose } from "./agentFollowCamera";+import { box, type Vec3 } from "./world";++describe("Mars agent follow camera", () => {+ it("keeps the same offset while translating with the rendered agent", () => {+ const start: Vec3 = [10, 3, 20];+ const delta: Vec3 = [25, 4, -30];+ const moved = start.map((value, axis) => value + delta[axis]) as Vec3;+ const first = createAgentFollowPose(start, [], () => 0);+ const next = createAgentFollowPose(moved, [], () => 0);+ expect(first.target).toEqual([10, 4.4, 20]);+ expect(first.position).toEqual([16, 8.4, 28]);+ for (let axis = 0; axis < 3; axis++) {+ expect(next.target[axis] - first.target[axis]).toBeCloseTo(delta[axis]);+ expect(next.position[axis] - first.position[axis]).toBeCloseTo(delta[axis]);+ }+ expect(createAgentFollowPose(moved, [], () => 0)).toEqual(next);+ expect(start).toEqual([10, 3, 20]);+ });++ it("shortens its sightline before a building while keeping the agent targeted", () => {+ const wall = box("wall", 3, 0, 4, 8, 8, 1);+ const pose = createAgentFollowPose([0, 0, 0], [wall], () => 0);+ expect(pose.target).toEqual([0, 1.4, 0]);+ expect(pose.position[2]).toBeGreaterThan(0);+ expect(pose.position[2]).toBeLessThan(3.15);+ expect(pose.position[0]).toBeCloseTo(pose.position[2] * 6 / 8);+ });++ it("keeps the lens in front of terrain that obstructs the follow offset", () => {+ const pose = createAgentFollowPose([0, 0, 0], [], (_x, z) => z > 3 ? 10 : 0);+ expect(pose.target).toEqual([0, 1.4, 0]);+ expect(pose.position[2]).toBeGreaterThan(0);+ expect(pose.position[2]).toBeLessThanOrEqual(3);+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/mars/agentFollowCamera.ts b/jarvis/ui/web/frontend/src/components/society/mars/agentFollowCamera.tsnew file mode 100644index 0000000000..a7e6550447--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/mars/agentFollowCamera.ts@@ -0,0 +1,10 @@+import { avoidCameraCollision } from "./camera";+import type { CameraPose } from "./viewPreferences";+import { BUILDING_COLLIDERS, terrainHeight, type Vec3 } from "./world";++/** Follow the rendered agent with a stable offset and the world's collision rules. */+export function createAgentFollowPose(position: Vec3, colliders = BUILDING_COLLIDERS, ground = terrainHeight): CameraPose {+ const target: Vec3 = [position[0], position[1] + 1.4, position[2]];+ const desired: Vec3 = [target[0] + 6, target[1] + 4, target[2] + 8];+ return { target, position: avoidCameraCollision(target, desired, colliders, ground) };+}diff --git a/jarvis/ui/web/frontend/src/components/society/mars/api.test.ts b/jarvis/ui/web/frontend/src/components/society/mars/api.test.tsnew file mode 100644index 0000000000..bbe9c80b71--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/mars/api.test.ts@@ -0,0 +1,44 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { clearDraftAttempt, MarsApiError, readDraftAttempt, saveDraftAttempt, submitMarsDraft } from "./api";+import { containsCredential } from "./credentialInput";++afterEach(() => { sessionStorage.clear(); vi.unstubAllGlobals(); });+const attempt = { request_id: "52f36e94-8701-4b46-b0c1-628bc775fdf0", agent_id: "comms", draft: "Draft a meeting invitation." };++describe("station command recovery", () => {+ it("preserves a newer attempt when an unmounted request completes late", () => {+ saveDraftAttempt(attempt);+ expect(readDraftAttempt()).toEqual(attempt);+ const next = { ...attempt, request_id: "52f36e94-8701-4b46-b0c1-628bc775fdf1" };+ saveDraftAttempt(next);+ clearDraftAttempt(attempt.request_id);+ expect(readDraftAttempt()).toEqual(next);+ clearDraftAttempt(next.request_id);+ expect(readDraftAttempt()).toBeNull();+ });+ it("does not persist credential-shaped drafts", () => {+ const synthetic = "sk-" + "example".repeat(6);+ expect(containsCredential(synthetic)).toBe(true);+ saveDraftAttempt({ ...attempt, draft: synthetic });+ expect(readDraftAttempt()).toBeNull();+ expect(containsCredential(attempt.draft)).toBe(false);+ expect(containsCredential("commit " + "a".repeat(40))).toBe(false);+ });+ it("retains exact request identity on repeated uncertain submissions", async () => {+ const bodies: string[] = [];+ vi.stubGlobal("fetch", async (_url: string, init: RequestInit) => {+ bodies.push(String(init.body)); throw new Error("offline");+ });+ await expect(submitMarsDraft(attempt)).rejects.toThrow("offline");+ await expect(submitMarsDraft(attempt)).rejects.toThrow("offline");+ expect(bodies[0]).toBe(bodies[1]);+ });+ it("exposes only a safe credential-rejection classification", async () => {+ vi.stubGlobal("fetch", async () => new Response(JSON.stringify({+ detail: { reason: "credential_input_use_api_key_settings" },+ }), { status: 422 }));+ await expect(submitMarsDraft(attempt)).rejects.toMatchObject({+ status: 422, credentialInput: true, message: "mars_request_failed",+ } satisfies Partial<MarsApiError>);+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/mars/api.ts b/jarvis/ui/web/frontend/src/components/society/mars/api.tsnew file mode 100644index 0000000000..0df52d6223--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/mars/api.ts@@ -0,0 +1,93 @@+import { z } from "zod";+import { containsCredential } from "./credentialInput";++export const COMMAND_STATES = ["queued", "active", "completed", "failed", "canceled", "interrupted", "unknown"] as const;+export type CommandState = typeof COMMAND_STATES[number];+export const WORLD_ID = "mars:ordinary" as const;++const commandSchema = z.object({+ command_id: z.string(), agent_id: z.string(), request_id: z.string(), trace_id: z.string(),+ world_id: z.literal(WORLD_ID), state: z.enum(COMMAND_STATES),+ task_ref: z.string().nullable(), result_ref: z.string().nullable(),+ reason: z.string(), cancel_requested: z.boolean(),+});+export type MarsCommand = z.infer<typeof commandSchema>;+const snapshotSchema = z.object({+ world_id: z.literal(WORLD_ID), schema_version: z.literal(1), layout_version: z.literal(1),+ seq: z.number().int().nonnegative(), commands: z.array(commandSchema).max(200),+});+export type MarsSnapshot = z.infer<typeof snapshotSchema>;+const rosterSchema = z.object({+ agents: z.array(z.object({+ agent_id: z.string(), name: z.string(), state: z.string(),+ })).max(2000),+});+export interface DraftAttempt { request_id: string; draft: string; agent_id: string }+const ATTEMPT_KEY = "jarvis.mars:ordinary.pending-draft.v1";+export function readDraftAttempt(): DraftAttempt | null {+ try {+ const raw = sessionStorage.getItem(ATTEMPT_KEY);+ if (!raw) return null;+ const value = z.object({+ request_id: z.string().uuid(), draft: z.string().min(1).max(4000),+ agent_id: z.string().min(1).max(128),+ }).strict().safeParse(JSON.parse(raw));+ return value.success ? value.data : null;+ } catch {+ // Storage denial costs refresh recovery only; in-memory retries retain their ID.+ return null;+ }+}+export function saveDraftAttempt(value: DraftAttempt | null): void {+ if (value && containsCredential(value.draft)) return;+ try {+ if (value) sessionStorage.setItem(ATTEMPT_KEY, JSON.stringify(value));+ else sessionStorage.removeItem(ATTEMPT_KEY);+ } catch {+ // Keep the current in-memory request on private/locked-down browser profiles.+ }+}+export function clearDraftAttempt(requestId: string): void {+ if (readDraftAttempt()?.request_id === requestId) saveDraftAttempt(null);+}+export class MarsApiError extends Error {+ constructor(readonly status: number, readonly credentialInput = false) { super("mars_request_failed"); }+}+async function request(path: string, init?: RequestInit): Promise<unknown> {+ const response = await fetch(`/api/society${path}`, {+ ...init,+ headers: { "Content-Type": "application/json", ...init?.headers },+ });+ if (!response.ok) {+ let credentialInput = false;+ try {+ const error = await response.json();+ credentialInput = error?.detail?.reason === "credential_input_use_api_key_settings";+ } catch {+ // Non-JSON gateway errors are represented only by their status, never their body.+ }+ throw new MarsApiError(response.status, credentialInput);+ }+ return response.json();+}+export async function fetchMarsSnapshot(signal?: AbortSignal): Promise<MarsSnapshot> {+ return snapshotSchema.parse(await request("/mars/snapshot", { signal }));+}+export async function fetchMarsRoster(signal?: AbortSignal) {+ return rosterSchema.parse(await request("/agents", { signal })).agents;+}+export async function submitMarsDraft(attempt: DraftAttempt): Promise<MarsCommand> {+ return commandSchema.parse(await request(`/mars/agents/${encodeURIComponent(attempt.agent_id)}/commands`, {+ method: "POST",+ body: JSON.stringify({+ request_id: attempt.request_id, draft: attempt.draft,+ world_id: WORLD_ID, schema_version: 1, layout_version: 1,+ }),+ }));+}+export async function cancelMarsCommand(command: MarsCommand): Promise<MarsCommand> {+ return commandSchema.parse(await request(+ `/mars/agents/${encodeURIComponent(command.agent_id)}/commands/${encodeURIComponent(command.command_id)}/cancel`,+ { method: "POST" },+ ));+}diff --git a/jarvis/ui/web/frontend/src/components/society/mars/buildingSelection.test.ts b/jarvis/ui/web/frontend/src/components/society/mars/buildingSelection.test.tsnew file mode 100644index 0000000000..b8e62738e0--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/mars/buildingSelection.test.ts@@ -0,0 +1,15 @@+import { expect, it } from "vitest";+import { outpostBuildingAt } from "./buildingSelection";++it("selects the inspected building rather than sending every click to the mast", () => {+ expect(outpostBuildingAt([294, 61, 71])).toBe("operations");+ expect(outpostBuildingAt([351, 63, 69])).toBe("radome-south");+ expect(outpostBuildingAt([278, 65, 46])).toBe("dish-west");+ expect(outpostBuildingAt([320, 80, 46])).toBe("communications-mast");+});++it("does not move the camera when the user clicks a road, open terrace or cliff", () => {+ for (const point of [[294, 58, 75], [285.1, 58, 76.4], [310, 58, 87], [320, 15, 96]] as [number, number, number][]) {+ expect(outpostBuildingAt(point)).toBeNull();+ }+});diff --git a/jarvis/ui/web/frontend/src/components/society/mars/buildingSelection.ts b/jarvis/ui/web/frontend/src/components/society/mars/buildingSelection.tsnew file mode 100644index 0000000000..9abd206493--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/mars/buildingSelection.ts@@ -0,0 +1,14 @@+import { WORLD, type Vec3 } from "./world";++/** Material-batched GLBs must not turn every road or cliff click into mast focus. */+export function outpostBuildingAt(point: Vec3): string | null {+ const candidates = WORLD.buildings.filter((building) => {+ if (building.district_id !== "communications-outpost") return false;+ const [x, y, z] = building.position, [width, height, depth] = building.size;+ return point[1] >= y - 0.05 && point[1] <= y + height + 0.5+ && Math.abs(point[0] - x) <= width / 2 + 0.3 && Math.abs(point[2] - z) <= depth / 2 + 0.3;+ });+ candidates.sort((a, b) => Math.hypot(point[0] - a.position[0], point[2] - a.position[2])+ - Math.hypot(point[0] - b.position[0], point[2] - b.position[2]));+ return candidates[0]?.id ?? null;+}diff --git a/jarvis/ui/web/frontend/src/components/society/mars/camera.test.ts b/jarvis/ui/web/frontend/src/components/society/mars/camera.test.tsnew file mode 100644index 0000000000..261e24c5ef--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/mars/camera.test.ts@@ -0,0 +1,101 @@+import { describe, expect, it } from "vitest";+import { PerspectiveCamera, Vector3 } from "three";+import { avoidCameraCollision, boundsCorners, CAMERA_CLEARANCE, CAMERA_FOV, fitWorldBounds, frameInspectionBounds, MAX_POLAR, MIN_POLAR } from "./camera";+import { box, BUILDING_COLLIDERS, outpostBounds, outpostCloseBounds, terrainHeight, WORLD_BOUNDS } from "./world";+import { parseViewPreferences, VIEW_DIRECTIONS, VIEWPOINTS } from "./viewPreferences";++describe("Mars camera", () => {+ it.each(VIEWPOINTS.filter((view) => view !== "close_reference"))("frames the complete authored Outpost from %s", (view) => {+ const bounds = outpostBounds();+ expect(bounds.min[0]).toBeLessThan(125); // West bridge, not just the plateau.+ expect(bounds.min[1]).toBeLessThan(0); // Complete cliff/support base.+ const frame = frameInspectionBounds(bounds, 16 / 9, 1.15, VIEW_DIRECTIONS[view]);+ const camera = new PerspectiveCamera(CAMERA_FOV, 16 / 9, 0.12, 20000);+ camera.position.fromArray(frame.position); camera.lookAt(...frame.target); camera.updateMatrixWorld();+ for (const point of boundsCorners(bounds)) {+ const projected = new Vector3(...point).project(camera);+ expect(Math.abs(projected.x)).toBeLessThan(1 / 1.15);+ expect(Math.abs(projected.y)).toBeLessThan(1 / 1.15);+ }+ });+ it.each([0.65, 1, 16 / 9, 3.4])("frames the close Outpost completely with a clear lens at aspect %s", (aspect) => {+ const bounds = outpostCloseBounds();+ const frame = frameInspectionBounds(bounds, aspect, 1.15, VIEW_DIRECTIONS.close_reference);+ const camera = new PerspectiveCamera(CAMERA_FOV, aspect, 0.12, 20000);+ camera.position.fromArray(frame.position); camera.lookAt(...frame.target); camera.updateMatrixWorld();+ for (const corner of boundsCorners(bounds)) {+ const projected = new Vector3(...corner).project(camera);+ expect(Math.abs(projected.x)).toBeLessThan(1 / 1.15);+ expect(Math.abs(projected.y)).toBeLessThan(1 / 1.15);+ expect(projected.z).toBeGreaterThan(-1);+ expect(projected.z).toBeLessThan(1);+ }+ for (const collider of BUILDING_COLLIDERS) {+ const inSolid = frame.position.every((value, axis) => value >= collider.min[axis] - CAMERA_CLEARANCE && value <= collider.max[axis] + CAMERA_CLEARANCE);+ expect(inSolid, collider.id).toBe(false);+ }+ expect(frame.position[1]).toBeGreaterThanOrEqual(terrainHeight(frame.position[0], frame.position[2]) + CAMERA_CLEARANCE);+ });+ it("brings the close reference nearer while retaining the reference viewing direction", () => {+ expect(VIEW_DIRECTIONS.close_reference).toEqual(VIEW_DIRECTIONS.reference);+ const full = frameInspectionBounds(outpostBounds(), 16 / 9, 1.15, VIEW_DIRECTIONS.reference);+ const close = frameInspectionBounds(outpostCloseBounds(), 16 / 9, 1.15, VIEW_DIRECTIONS.close_reference);+ expect(close.distance).toBeLessThan(full.distance);+ });+ it("backs a preset lens out of solids without cropping its complete subject", () => {+ const bounds = box("subject", 0, 0, 0, 10, 10, 10);+ const raw = fitWorldBounds(bounds, 1.6);+ const obstacle = box("lens-obstacle", ...raw.position, 10, 10, 10);+ const frame = frameInspectionBounds(bounds, 1.6, 1.15, [0.8, 0.9, 1], [obstacle], () => -10);+ expect(frame.distance).toBeGreaterThan(raw.distance);+ expect(frame.target).toEqual(raw.target);+ const camera = new PerspectiveCamera(CAMERA_FOV, 1.6, 0.12, 20000);+ camera.position.fromArray(frame.position); camera.lookAt(...frame.target); camera.updateMatrixWorld();+ for (const point of boundsCorners(bounds)) {+ const projected = new Vector3(...point).project(camera);+ expect(Math.abs(projected.x)).toBeLessThan(1 / 1.15);+ expect(Math.abs(projected.y)).toBeLessThan(1 / 1.15);+ }+ });+ it("restores only valid client/world view state and recovers from corrupt storage", () => {+ const pose = { position: [320, 100, 150], target: [320, 76, 50] };+ const saved = { world_id: "mars:ordinary", layout_version: 1, mode: "orbit", viewpoint: "rear", neutral: true, pose };+ expect(parseViewPreferences(JSON.stringify(saved))).toEqual({ mode: "orbit", viewpoint: "rear", neutral: true, shadows: true, pose, followAgentId: null });+ expect(parseViewPreferences(JSON.stringify({ ...saved, shadows: false })).shadows).toBe(false);+ for (const change of [{ world_id: "mars:swarm:other" }, { layout_version: 2 }, { mode: "bad" }]) {+ expect(parseViewPreferences(JSON.stringify({ ...saved, ...change })).mode).toBe("overview");+ }+ for (const position of [[0, 0], [null, 0, 0], [1e9, 0, 0], pose.target]) {+ expect(parseViewPreferences(JSON.stringify({ ...saved, pose: { ...pose, position } })).mode).toBe("overview");+ }+ expect(parseViewPreferences("invalid JSON").mode).toBe("overview");+ });+ it.each([0.32, 0.65, 1, 16 / 9, 3.4])("fits the full three-dimensional world at aspect %s", (aspect) => {+ const frame = fitWorldBounds(WORLD_BOUNDS, aspect);+ const camera = new PerspectiveCamera(CAMERA_FOV, aspect, 0.12, 20000);+ camera.position.fromArray(frame.position); camera.lookAt(...frame.target); camera.updateMatrixWorld();+ for (const corner of boundsCorners(WORLD_BOUNDS)) {+ const point = new Vector3(...corner).project(camera);+ expect(Math.abs(point.x)).toBeLessThan(1 / 1.15);+ expect(Math.abs(point.y)).toBeLessThan(1 / 1.15);+ expect(point.z).toBeGreaterThan(-1); expect(point.z).toBeLessThan(1);+ }+ });+ it("shortens a follow camera before its wall, and permits a clear sightline", () => {+ const wall = box("wall", 0, 0, 4, 8, 8, 1);+ const blocked = avoidCameraCollision([0, 2, 0], [0, 3, 10], [wall], () => 0);+ expect(blocked[2]).toBeLessThan(3.5);+ expect(avoidCameraCollision([0, 2, 0], [0, 3, 2], [wall], () => 0)).toEqual([0, 3, 2]);+ });+ it("stops before terrain occlusion and avoids both vertical poles", () => {+ const position = avoidCameraCollision([0, 2, 0], [0, 3, 20], [], (_x, z) => z > 6 ? 10 : 0);+ expect(position[2]).toBeLessThanOrEqual(6);+ expect(MIN_POLAR).toBeGreaterThan(0); expect(MAX_POLAR).toBeLessThan(Math.PI / 2);+ });+ it("keeps the lens outside a landmark even when its orbit pivot is inside", () => {+ const mast = box("mast", 0, 0, 0, 14, 62, 14);+ expect(avoidCameraCollision([0, 30, 0], [0, 31, 20], [mast], () => 0)).toEqual([0, 31, 20]);+ const near = avoidCameraCollision([0, 30, 0], [0, 30, 1], [mast], () => 0);+ expect(near[2]).toBeGreaterThan(7.35);+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/mars/camera.ts b/jarvis/ui/web/frontend/src/components/society/mars/camera.tsnew file mode 100644index 0000000000..c70bc001e8--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/mars/camera.ts@@ -0,0 +1,103 @@+import { Vector3 } from "three";+import { BUILDING_COLLIDERS, terrainHeight, type Bounds, type Collider, type Vec3 } from "./world";++export const CAMERA_FOV = 45;+export const MIN_POLAR = 0.035;+export const MAX_POLAR = Math.PI / 2 - 0.035;+export const CAMERA_CLEARANCE = 0.35;++export function boundsCorners(bounds: Bounds): Vec3[] {+ const corners: Vec3[] = [];+ for (const x of [bounds.min[0], bounds.max[0]]) for (const y of [bounds.min[1], bounds.max[1]]) for (const z of [bounds.min[2], bounds.max[2]]) corners.push([x, y, z]);+ return corners;+}++/** Solve every corner against horizontal AND vertical frusta, including its depth. */+export function fitWorldBounds(bounds: Bounds, aspect: number, padding = 1.15, direction: Vec3 = [0.8, 0.9, 1]) {+ const target = new Vector3().fromArray(bounds.min).add(new Vector3().fromArray(bounds.max)).multiplyScalar(0.5);+ const outward = new Vector3(...direction).normalize();+ const right = new Vector3().crossVectors(new Vector3(0, 1, 0), outward).normalize();+ const up = new Vector3().crossVectors(outward, right).normalize();+ const tanV = Math.tan(CAMERA_FOV * Math.PI / 360);+ const tanH = tanV * Math.max(0.05, aspect);+ let distance = 1;+ for (const corner of boundsCorners(bounds)) {+ const offset = new Vector3(...corner).sub(target);+ distance = Math.max(distance, offset.dot(outward) + Math.max(Math.abs(offset.dot(right)) * padding / tanH, Math.abs(offset.dot(up)) * padding / tanV) + 1);+ }+ return { target: target.toArray() as Vec3, position: target.clone().addScaledVector(outward, distance).toArray() as Vec3, distance };+}++/** A frame may look through parts of its subject; only its lens must be clear.+ * Moving farther along the same direction preserves the complete bounds fit.+ */+export function frameInspectionBounds(bounds: Bounds, aspect: number, padding = 1.15, direction: Vec3 = [0.8, 0.9, 1], colliders = BUILDING_COLLIDERS, ground = terrainHeight) {+ const frame = fitWorldBounds(bounds, aspect, padding, direction);+ const target = new Vector3(...frame.target);+ const outward = new Vector3(...direction).normalize();+ for (let attempt = 0; attempt < 32; attempt++) {+ const position = target.clone().addScaledVector(outward, frame.distance).toArray() as Vec3;+ const inSolid = colliders.some((box) => position.every((n, axis) => n >= box.min[axis] - CAMERA_CLEARANCE && n <= box.max[axis] + CAMERA_CLEARANCE));+ if (!inSolid && position[1] >= ground(position[0], position[2]) + CAMERA_CLEARANCE) return { ...frame, position };+ frame.distance *= 1.2;+ }+ throw new Error("No clear Mars inspection camera position");+}++export function segmentBox(from: Vec3, to: Vec3, bounds: Collider, radius = 0): number | null {+ let enter = 0, leave = 1;+ for (let axis = 0; axis < 3; axis++) {+ const delta = to[axis] - from[axis];+ const min = bounds.min[axis] - radius, max = bounds.max[axis] + radius;+ if (Math.abs(delta) < 1e-10) {+ if (from[axis] < min || from[axis] > max) return null;+ continue;+ }+ let near = (min - from[axis]) / delta, far = (max - from[axis]) / delta;+ if (near > far) [near, far] = [far, near];+ enter = Math.max(enter, near);+ leave = Math.min(leave, far);+ if (enter > leave) return null;+ }+ return enter;+}++/** Shorten the sightline against solid geometry and terrain; never send the camera through a roof. */+export function avoidCameraCollision(target: Vec3, desired: Vec3, colliders = BUILDING_COLLIDERS, ground = terrainHeight): Vec3 {+ const inside = (point: Vec3, c: Collider) => point.every((value, axis) => value >= c.min[axis] - CAMERA_CLEARANCE && value <= c.max[axis] + CAMERA_CLEARANCE);+ let endpoint: Vec3 = [...desired];+ // Inspecting an object may put the pivot inside it. Keep the lens outside+ // that object instead of collapsing the camera onto the occupied pivot.+ for (const collider of colliders) {+ if (!inside(target, collider) || !inside(endpoint, collider)) continue;+ const direction = new Vector3(...endpoint).sub(new Vector3(...target));+ if (direction.lengthSq() < 1e-10) direction.set(0, 0, 1);+ direction.normalize();+ let exitDistance = Infinity;+ for (let axis = 0; axis < 3; axis++) {+ const delta = direction.getComponent(axis);+ if (Math.abs(delta) < 1e-10) continue;+ const boundary = delta > 0 ? collider.max[axis] + CAMERA_CLEARANCE : collider.min[axis] - CAMERA_CLEARANCE;+ exitDistance = Math.min(exitDistance, (boundary - target[axis]) / delta);+ }+ endpoint = target.map((value, axis) => value + direction.getComponent(axis) * (exitDistance + 0.01)) as Vec3;+ }+ let fraction = 1;+ for (const collider of colliders) {+ if (inside(target, collider)) continue;+ const hit = segmentBox(target, endpoint, collider, CAMERA_CLEARANCE);+ if (hit !== null) fraction = Math.min(fraction, Math.max(0, hit - 0.002));+ }+ const length = Math.hypot(...endpoint.map((v, i) => v - target[i]));+ const count = Math.min(1024, Math.max(8, Math.ceil(length / 2)));+ for (let i = 1; i <= count; i++) {+ const t = i / count;+ if (t > fraction) break;+ const x = target[0] + (endpoint[0] - target[0]) * t, y = target[1] + (endpoint[1] - target[1]) * t, z = target[2] + (endpoint[2] - target[2]) * t;+ if (y < ground(x, z) + CAMERA_CLEARANCE) {+ fraction = (i - 1) / count;+ break;+ }+ }+ return target.map((value, axis) => value + (endpoint[axis] - value) * fraction) as Vec3;+}diff --git a/jarvis/ui/web/frontend/src/components/society/mars/controller.test.ts b/jarvis/ui/web/frontend/src/components/society/mars/controller.test.tsnew file mode 100644index 0000000000..d51e99eaea--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/mars/controller.test.ts@@ -0,0 +1,76 @@+import { describe, expect, it } from "vitest";+import { advancePlayer, createPlayer, isPositionClear, RUN_SPEED, sweepSlide, WALK_SPEED, type CollisionWorld, type PlayerInput } from "./controller";+import { box, ROADS, surfaceHeight } from "./world";++const flat: CollisionWorld = { colliders: [], ground: () => 0 };+const walk: PlayerInput = { forward: 1, right: 0, run: false, jump: false };+const still: PlayerInput = { forward: 0, right: 0, run: false, jump: false };++describe("bounded Mars movement", () => {+ it.each([30, 60, 120])("moves consistently at %s render FPS", (fps) => {+ const player = createPlayer([0, 0, 0]);+ for (let i = 0; i < fps; i++) advancePlayer(player, walk, 0, 1 / fps, flat);+ expect(player.position[2]).toBeCloseTo(-WALK_SPEED, 3);+ expect(player.position[1]).toBe(0);+ });+ it("normalizes diagonals and caps a thirty-second frame stall", () => {+ const player = createPlayer([0, 0, 0]);+ expect(advancePlayer(player, { ...walk, right: 1, run: true }, 0, 30, flat)).toBe(12);+ expect(Math.hypot(player.position[0], player.position[2])).toBeCloseTo(RUN_SPEED * 0.1, 3);+ const before = [...player.position];+ advancePlayer(player, walk, 0, -1, flat); advancePlayer(player, walk, 0, NaN, flat);+ expect(player.position).toEqual(before);+ });+ it("sweeps through a thin-wall fixture without tunneling and slides along it", () => {+ const wall: CollisionWorld = { ground: () => 0, colliders: [box("thin-wall", 3, 0, 0, 0.1, 5, 10)] };+ const next = sweepSlide([0, 0, 0], 20, 2, wall);+ expect(next[0]).toBeLessThan(2.56); expect(next[2]).toBeGreaterThan(1.9);+ expect(isPositionClear(next, wall)).toBe(true);+ });+ it("enters through the operations door and stops at the back wall", () => {+ const player = createPlayer([294, surfaceHeight(294, 75), 75]);+ for (let i = 0; i < 240; i++) advancePlayer(player, walk, 0, 1 / 60);+ expect(player.position[2]).toBeLessThan(64);+ expect(player.position[2]).toBeGreaterThan(57);+ expect(isPositionClear(player.position)).toBe(true);+ });+ it("crosses the Outpost bridge without losing deck height at its endpoints", () => {+ const road = ROADS.find((item) => item.id === "route-01")!;+ const player = createPlayer([road.start[0], surfaceHeight(road.start[0], road.start[2]), road.start[2]]);+ const dx = road.end[0] - road.start[0], dz = road.end[2] - road.start[2];+ const yaw = -Math.atan2(dz, dx);+ const frames = Math.ceil(Math.hypot(dx, dz) / WALK_SPEED * 60);+ for (let i = 0; i < frames; i++) advancePlayer(player, { ...still, right: 1 }, yaw, 1 / 60);+ expect(player.position[0]).toBeCloseTo(road.end[0], 0);+ expect(player.position[1]).toBeCloseTo(58, 1);+ });+ it("lands after a single jump and does not auto-jump while Space stays held", () => {+ const player = createPlayer([0, 0, 0]);+ let peak = 0;+ for (let i = 0; i < 180; i++) {+ advancePlayer(player, { ...still, jump: true }, 0, 1 / 60, flat);+ peak = Math.max(peak, player.position[1]);+ }+ expect(peak).toBeGreaterThan(0.7); expect(peak).toBeLessThan(1);+ expect(player.position[1]).toBe(0); expect(player.grounded).toBe(true);+ });+ it("stops upward motion at a low ceiling", () => {+ const world = { ground: () => 0, colliders: [box("ceiling", 0, 2.1, 0, 10, 0.2, 10)] };+ const player = createPlayer([0, 0, 0]);+ for (let i = 0; i < 60; i++) {+ advancePlayer(player, { ...still, jump: i < 2 }, 0, 1 / 60, world);+ expect(player.position[1] + 1.8).toBeLessThanOrEqual(2.1);+ }+ expect(player.grounded).toBe(true);+ });+ it("climbs a small step but refuses an unsupported cliff edge", () => {+ const step = { colliders: [], ground: (_x: number, z: number) => z < -1 ? 0.2 : 0 };+ const player = createPlayer([0, 0, 0]);+ for (let i = 0; i < 60; i++) advancePlayer(player, walk, 0, 1 / 60, step);+ expect(player.position[2]).toBeLessThan(-3); expect(player.position[1]).toBeCloseTo(0.2);+ const cliff = { colliders: [], ground: (_x: number, z: number) => z < -1 ? -20 : 0 };+ const edge = createPlayer([0, 0, 0]);+ for (let i = 0; i < 60; i++) advancePlayer(edge, walk, 0, 1 / 60, cliff);+ expect(edge.position[2]).toBeGreaterThan(-1); expect(edge.position[1]).toBe(0);+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/mars/controller.ts b/jarvis/ui/web/frontend/src/components/society/mars/controller.tsnew file mode 100644index 0000000000..072f552f06--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/mars/controller.ts@@ -0,0 +1,115 @@+import { BUILDING_COLLIDERS, PLAYER_SPAWN, WORLD_BOUNDS, surfaceHeight, type Collider, type Vec3 } from "./world";++export const FIXED_STEP = 1 / 120;+export const MAX_FRAME = 0.1;+export const PLAYER_RADIUS = 0.4;+export const PLAYER_HEIGHT = 1.8;+export const WALK_SPEED = 4.4;+export const RUN_SPEED = 7.5;+export const STEP_HEIGHT = 0.35;+export const MAX_SLOPE = Math.tan(38 * Math.PI / 180);+export interface PlayerInput { forward: number; right: number; run: boolean; jump: boolean }+export interface PlayerState { position: Vec3; yaw: number; velocityY: number; grounded: boolean; accumulator: number; jumpHeld: boolean }+export interface CollisionWorld { colliders: Collider[]; ground: (x: number, z: number) => number }+export const COLLISION_WORLD: CollisionWorld = { colliders: BUILDING_COLLIDERS, ground: surfaceHeight };++export function createPlayer(position: Vec3 = PLAYER_SPAWN): PlayerState {+ return { position: [...position], yaw: 0, velocityY: 0, grounded: true, accumulator: 0, jumpHeld: false };+}++export function isPositionClear(position: Vec3, world = COLLISION_WORLD): boolean {+ return !world.colliders.some((c) => position[1] + PLAYER_HEIGHT > c.min[1] && position[1] < c.max[1]+ && position[0] > c.min[0] - PLAYER_RADIUS && position[0] < c.max[0] + PLAYER_RADIUS+ && position[2] > c.min[2] - PLAYER_RADIUS && position[2] < c.max[2] + PLAYER_RADIUS);+}++/** Swept expanded AABBs prevent high speed tunneling; remaining motion slides along the wall. */+export function sweepSlide(position: Vec3, dx: number, dz: number, world = COLLISION_WORLD): Vec3 {+ const result: Vec3 = [...position];+ for (let iteration = 0; iteration < 3 && Math.abs(dx) + Math.abs(dz) > 1e-8; iteration++) {+ let first = 1, normalX = 0, normalZ = 0;+ for (const c of world.colliders) {+ if (position[1] + PLAYER_HEIGHT <= c.min[1] || position[1] >= c.max[1]) continue;+ let enter = -Infinity, leave = Infinity, nx = 0, nz = 0;+ for (const axis of [0, 2] as const) {+ const delta = axis === 0 ? dx : dz, start = result[axis];+ const min = c.min[axis] - PLAYER_RADIUS, max = c.max[axis] + PLAYER_RADIUS;+ if (Math.abs(delta) < 1e-12) {+ if (start <= min || start >= max) { leave = -Infinity; break; }+ continue;+ }+ let near = (min - start) / delta, far = (max - start) / delta;+ const normal = -Math.sign(delta);+ if (near > far) [near, far] = [far, near];+ if (near > enter) { enter = near; nx = axis === 0 ? normal : 0; nz = axis === 2 ? normal : 0; }+ leave = Math.min(leave, far);+ }+ if (enter >= -1e-7 && enter < first && enter <= leave && leave >= 0) {+ first = Math.max(0, enter); normalX = nx; normalZ = nz;+ }+ }+ const travel = Math.max(0, first - 0.00001);+ result[0] += dx * travel; result[2] += dz * travel;+ if (first === 1) break;+ dx *= 1 - first; dz *= 1 - first;+ const into = dx * normalX + dz * normalZ;+ dx -= normalX * into; dz -= normalZ * into;+ }+ return result;+}++function stepPlayer(state: PlayerState, input: PlayerInput, cameraYaw: number, dt: number, world: CollisionWorld) {+ const magnitude = Math.hypot(input.forward, input.right);+ if (magnitude > 0) {+ const speed = input.run ? RUN_SPEED : WALK_SPEED;+ const forward = input.forward / magnitude, right = input.right / magnitude;+ const dx = (right * Math.cos(cameraYaw) - forward * Math.sin(cameraYaw)) * speed * dt;+ const dz = (-right * Math.sin(cameraYaw) - forward * Math.cos(cameraYaw)) * speed * dt;+ const next = sweepSlide(state.position, dx, dz, world);+ const currentGround = world.ground(state.position[0], state.position[2]);+ const nextGround = world.ground(next[0], next[2]);+ const distance = Math.hypot(next[0] - state.position[0], next[2] - state.position[2]);+ // Preserve an explicit ledge boundary. Jumping does not grant wall/steep-slope traversal.+ const slope = (nextGround - currentGround) / Math.max(distance, 0.00001);+ const probeDistance = 0.5;+ const probe = world.ground(next[0] + dx / Math.max(Math.hypot(dx, dz), 0.00001) * probeDistance, next[2] + dz / Math.max(Math.hypot(dx, dz), 0.00001) * probeDistance);+ const smallStep = nextGround - currentGround <= STEP_HEIGHT && (probe - nextGround) / probeDistance <= MAX_SLOPE;+ const allowedRise = nextGround - state.position[1] <= STEP_HEIGHT;+ const safeEdge = currentGround - nextGround <= STEP_HEIGHT;+ if ((slope <= MAX_SLOPE || smallStep) && allowedRise && safeEdge) {+ state.position[0] = Math.max(WORLD_BOUNDS.min[0] + PLAYER_RADIUS, Math.min(WORLD_BOUNDS.max[0] - PLAYER_RADIUS, next[0]));+ state.position[2] = Math.max(WORLD_BOUNDS.min[2] + PLAYER_RADIUS, Math.min(WORLD_BOUNDS.max[2] - PLAYER_RADIUS, next[2]));+ state.yaw = Math.atan2(dx, dz);+ }+ }+ if (input.jump && !state.jumpHeld && state.grounded) { state.velocityY = 5.2; state.grounded = false; }+ state.jumpHeld = input.jump;+ const ground = world.ground(state.position[0], state.position[2]);+ state.velocityY -= 16 * dt;+ let y = state.position[1] + state.velocityY * dt;+ for (const c of world.colliders) {+ if (state.position[0] < c.min[0] - PLAYER_RADIUS || state.position[0] > c.max[0] + PLAYER_RADIUS+ || state.position[2] < c.min[2] - PLAYER_RADIUS || state.position[2] > c.max[2] + PLAYER_RADIUS) continue;+ if (state.velocityY > 0 && state.position[1] + PLAYER_HEIGHT <= c.min[1] && y + PLAYER_HEIGHT >= c.min[1]) {+ y = c.min[1] - PLAYER_HEIGHT - 0.001; state.velocityY = 0;+ }+ if (state.velocityY < 0 && state.position[1] >= c.max[1] && y <= c.max[1]) {+ y = c.max[1]; state.velocityY = 0; state.grounded = true;+ }+ }+ if (y <= ground + 0.001) { y = ground; state.velocityY = 0; state.grounded = true; }+ else if (state.velocityY !== 0) state.grounded = false;+ state.position[1] = y;+}++/** Drop excess suspended time instead of replaying seconds of movement after a hidden tab. */+export function advancePlayer(state: PlayerState, input: PlayerInput, cameraYaw: number, elapsed: number, world = COLLISION_WORLD): number {+ state.accumulator += Math.max(0, Math.min(MAX_FRAME, Number.isFinite(elapsed) ? elapsed : 0));+ let steps = 0;+ while (state.accumulator + 1e-10 >= FIXED_STEP && steps < 12) {+ stepPlayer(state, input, cameraYaw, FIXED_STEP, world);+ state.accumulator = Math.max(0, state.accumulator - FIXED_STEP);+ steps++;+ }+ return steps;+}diff --git a/jarvis/ui/web/frontend/src/components/society/mars/credentialInput.ts b/jarvis/ui/web/frontend/src/components/society/mars/credentialInput.tsnew file mode 100644index 0000000000..7d1a337788--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/mars/credentialInput.ts@@ -0,0 +1,16 @@+/** Client preflight before draft recovery storage. Server guard remains authoritative. */+const PATTERNS = [+ /\bsk-(?:proj-|ant-|or-|live-)?[A-Za-z0-9_-]{20,}\b/,+ /\b(?:AIza[0-9A-Za-z_-]{30,}|xai-[A-Za-z0-9]{20,}|gsk_[A-Za-z0-9]{20,}|gh[pousr]_[A-Za-z0-9]{30,})\b/,+ /\b[Bb]earer\s+[A-Za-z0-9._\-]{16,}\b/,+ /^\s*authorization\s*[:=]\s*\S{12,}\s*$/im,+ /\b(?:api[_-]?key|secret(?:[_-]?key)?|password|passwd|pwd|access[_-]?token|auth[_-]?token|client[_-]?secret)\b\s*[:=]\s*['"]?[^\s'"]{8,}/i,+ /\beyJ[A-Za-z0-9_-]{6,}\.eyJ[A-Za-z0-9_-]{3,}\.[A-Za-z0-9_-]{3,}\b/,+ /\b[0-9a-fA-F]{64,}\b/,+ /\b[A-Za-z0-9+/]{64,}={0,2}\b/,+ /-----BEGIN (?:RSA |EC |OPENSSH |DSA |PGP )?PRIVATE KEY-----/,+];+export function containsCredential(value: string): boolean {+ return PATTERNS.some((pattern) => pattern.test(value));+}+diff --git a/jarvis/ui/web/frontend/src/components/society/mars/followInput.test.ts b/jarvis/ui/web/frontend/src/components/society/mars/followInput.test.tsnew file mode 100644index 0000000000..46144e2568--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/mars/followInput.test.ts@@ -0,0 +1,60 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { bindFollowEscape } from "./followInput";++const disposers: (() => void)[] = [];+function fixture() {+ const host = document.createElement("div"); host.tabIndex = 0; document.body.append(host); host.focus();+ const stop = vi.fn(); disposers.push(bindFollowEscape(host, stop));+ return { host, stop };+}+function escape(target: Element, prevented = false) {+ const event = new KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true });+ if (prevented) event.preventDefault();+ target.dispatchEvent(event); return event;+}+afterEach(() => { disposers.splice(0).forEach((dispose) => dispose()); document.body.replaceChildren(); });++describe("follow Escape ownership", () => {+ it("consumes focused viewport Escape before the Society document handler and disposes", () => {+ const { host, stop } = fixture();+ let seen = false;+ document.addEventListener("keydown", (event) => { seen = event.defaultPrevented; }, { once: true });+ expect(escape(host).defaultPrevented).toBe(true);+ expect(seen).toBe(true); expect(stop).toHaveBeenCalledTimes(1);+ disposers.splice(0).forEach((dispose) => dispose());+ expect(escape(host).defaultPrevented).toBe(false); expect(stop).toHaveBeenCalledTimes(1);+ });+ it.each(["input", "textarea", "select", "button", "[contenteditable]", ".xterm", "[role=dialog]", "[role=menu]", "[data-mars-ui]"])("protects %s descendants and active fields", (selector) => {+ const { host, stop } = fixture();+ const field = document.createElement(selector.startsWith("[") || selector.startsWith(".") ? "div" : selector);+ if (selector === "[contenteditable]") field.setAttribute("contenteditable", "true");+ if (selector === ".xterm") field.className = "xterm";+ if (selector.startsWith("[role=")) field.setAttribute("role", selector.slice(6, -1));+ if (selector === "[data-mars-ui]") field.dataset.marsUi = "";+ field.tabIndex = 0; host.append(field); field.focus();+ expect(escape(field).defaultPrevented).toBe(false);+ expect(escape(host).defaultPrevented).toBe(false);+ expect(stop).not.toHaveBeenCalled();+ });+ it("ignores unfocused worlds and already handled Escape", () => {+ const { host, stop } = fixture();+ escape(host, true); expect(stop).not.toHaveBeenCalled();+ host.blur(); escape(host); expect(stop).not.toHaveBeenCalled();+ });+ it("stops focused follow on browser fullscreen exit without a keydown and releases its listener", () => {+ const { stop } = fixture();+ document.dispatchEvent(new Event("fullscreenchange"));+ expect(stop).toHaveBeenCalledTimes(1);+ disposers.splice(0).forEach((dispose) => dispose());+ document.dispatchEvent(new Event("fullscreenchange"));+ expect(stop).toHaveBeenCalledTimes(1);+ });+ it("ignores fullscreen exit while a form or another view owns focus", () => {+ const { host, stop } = fixture();+ const field = document.createElement("input"); host.append(field); field.focus();+ document.dispatchEvent(new Event("fullscreenchange"));+ field.blur();+ document.dispatchEvent(new Event("fullscreenchange"));+ expect(stop).not.toHaveBeenCalled();+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/mars/followInput.ts b/jarvis/ui/web/frontend/src/components/society/mars/followInput.tsnew file mode 100644index 0000000000..01ac67fda1--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/mars/followInput.ts@@ -0,0 +1,24 @@+import { ownsTextOrUi } from "./input";++/** Escape belongs to follow only while its own viewport has keyboard focus. */+export function bindFollowEscape(host: HTMLElement, stop: () => void): () => void {+ const ownsFocus = () => host.contains(document.activeElement) && !ownsTextOrUi(document.activeElement);+ const escape = (event: KeyboardEvent) => {+ if ((event.key !== "Escape" && event.code !== "Escape") || event.defaultPrevented+ || event.altKey || event.ctrlKey || event.metaKey || !ownsFocus()+ || ownsTextOrUi(event.target)) return;+ event.preventDefault();+ stop();+ };+ // Browser Escape may leave fullscreen without dispatching a page keydown.+ // The parent preserves this map while follow relinquishes its own camera.+ const fullscreen = () => {+ if (!document.fullscreenElement && ownsFocus()) stop();+ };+ host.addEventListener("keydown", escape);+ document.addEventListener("fullscreenchange", fullscreen);+ return () => {+ host.removeEventListener("keydown", escape);+ document.removeEventListener("fullscreenchange", fullscreen);+ };+}diff --git a/jarvis/ui/web/frontend/src/components/society/mars/input.test.ts b/jarvis/ui/web/frontend/src/components/society/mars/input.test.tsnew file mode 100644index 0000000000..f7cb26d8a2--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/mars/input.test.ts@@ -0,0 +1,60 @@+// @vitest-environment jsdom+import { afterEach, describe, expect, it, vi } from "vitest";+import { bindPlayerInput, NO_INPUT, ownsTextOrUi } from "./input";++const disposers: (() => void)[] = [];+function fixture() {+ const host = document.createElement("div"); host.tabIndex = 0; document.body.append(host); host.focus();+ const invalidate = vi.fn();+ const input = bindPlayerInput(host, invalidate);+ disposers.push(() => input.dispose());+ return { host, input, invalidate };+}+function key(target: Element | Window, type: string, code: string) { target.dispatchEvent(new KeyboardEvent(type, { code, bubbles: true, cancelable: true })); }+afterEach(() => { disposers.splice(0).forEach((dispose) => dispose()); document.body.replaceChildren(); });++describe("Mars input ownership", () => {+ it("retains short taps until physics consumes them and then releases movement", () => {+ const { host, input } = fixture();+ key(host, "keydown", "KeyW"); key(host, "keyup", "KeyW");+ expect(input.read().forward).toBe(1);+ expect(input.read().forward).toBe(1);+ input.consume();+ expect(input.read()).toEqual(NO_INPUT);+ key(host, "keydown", "Space"); key(host, "keyup", "Space");+ window.dispatchEvent(new Event("blur"));+ expect(input.read()).toEqual(NO_INPUT);+ });+ it("keeps held movement when a mouse-look drag ends normally", () => {+ const { host, input } = fixture();+ key(host, "keydown", "KeyW"); input.consume();+ host.dispatchEvent(new Event("lostpointercapture"));+ expect(input.read().forward).toBe(1);+ key(host, "keyup", "KeyW");+ expect(input.read()).toEqual(NO_INPUT);+ });+ it("moves only the focused world and clears keys on blur", () => {+ const { host, input } = fixture();+ key(host, "keydown", "KeyW"); expect(input.read().forward).toBe(1);+ window.dispatchEvent(new Event("blur")); expect(input.read()).toEqual(NO_INPUT);+ key(host, "keyup", "KeyW"); expect(input.read()).toEqual(NO_INPUT);+ });+ it.each(["input", "textarea", "button", "select"])("typing or focusing %s releases held movement", (tag) => {+ const { host, input } = fixture(); key(host, "keydown", "KeyW");+ const field = document.createElement(tag); host.append(field); field.focus();+ key(field, "keydown", "KeyW"); key(field, "keydown", "Space");+ expect(input.read()).toEqual(NO_INPUT);+ host.focus(); expect(input.read()).toEqual(NO_INPUT);+ });+ it("protects terminal, contenteditable and modal descendants", () => {+ for (const markup of ['<div class="xterm"><span></span></div>', '<div contenteditable="true"><span></span></div>', '<div role="dialog"><span></span></div>']) {+ const root = document.createElement("div"); root.innerHTML = markup; document.body.append(root);+ expect(ownsTextOrUi(root.querySelector("span"))).toBe(true);+ }+ });+ it("releases movement on Escape and ignores all input after disposal", () => {+ const { host, input } = fixture();+ key(host, "keydown", "KeyW"); key(host, "keydown", "Escape"); expect(input.read()).toEqual(NO_INPUT);+ input.dispose(); key(host, "keydown", "KeyW"); expect(input.read()).toEqual(NO_INPUT);+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/mars/input.ts b/jarvis/ui/web/frontend/src/components/society/mars/input.tsnew file mode 100644index 0000000000..26792644b4--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/mars/input.ts@@ -0,0 +1,75 @@+import type { PlayerInput } from "./controller";++const MOVEMENT_KEYS = new Set(["KeyW", "KeyA", "KeyS", "KeyD", "ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", "Space", "ShiftLeft", "ShiftRight"]);+export const NO_INPUT: PlayerInput = { forward: 0, right: 0, run: false, jump: false };+export function ownsTextOrUi(target: EventTarget | null): boolean {+ return target instanceof Element && Boolean(target.closest("input, textarea, select, button, a, [contenteditable]:not([contenteditable='false']), [role='textbox'], [role='dialog'], [role='menu'], [data-mars-ui], .xterm"));+}++/** All listeners belong to one mounted world. Call dispose on world or input-mode changes. */+export function bindPlayerInput(host: HTMLElement, invalidate: () => void, escape: () => void = () => undefined, look: (dx: number, dy: number) => void = () => undefined, interact: () => void = () => undefined) {+ const keys = new Set<string>();+ const pending = new Set<string>();+ let disposed = false;+ let pointerId: number | null = null, pointerX = 0, pointerY = 0;+ const release = () => {+ const captured = pointerId;+ pointerId = null;+ if (captured !== null && host.hasPointerCapture?.(captured)) host.releasePointerCapture(captured);+ };+ const clear = () => { keys.clear(); pending.clear(); release(); invalidate(); };+ const canOwn = (target: EventTarget | null) => !ownsTextOrUi(target) && host.contains(document.activeElement) && !ownsTextOrUi(document.activeElement);+ const down = (event: KeyboardEvent) => {+ if (event.code === "Escape") { clear(); escape(); return; }+ if (!canOwn(event.target) || event.altKey || event.ctrlKey || event.metaKey) { clear(); return; }+ if (event.code === "KeyE" && !event.repeat) { event.preventDefault(); interact(); return; }+ if (!MOVEMENT_KEYS.has(event.code)) return;+ event.preventDefault(); keys.add(event.code); pending.add(event.code); invalidate();+ };+ const up = (event: KeyboardEvent) => { keys.delete(event.code); invalidate(); };+ const focus = (event: FocusEvent) => { if (!canOwn(event.target)) clear(); };+ const pointer = (event: PointerEvent) => {+ if (ownsTextOrUi(event.target)) return;+ host.focus({ preventScroll: true });+ if (event.button !== 0) return;+ pointerId = event.pointerId; pointerX = event.clientX; pointerY = event.clientY;+ host.setPointerCapture?.(event.pointerId);+ };+ const move = (event: PointerEvent) => {+ if (event.pointerId !== pointerId) return;+ look(event.clientX - pointerX, event.clientY - pointerY);+ pointerX = event.clientX; pointerY = event.clientY; invalidate();+ };+ const lostCapture = () => { release(); invalidate(); };+ window.addEventListener("keydown", down);+ window.addEventListener("keyup", up);+ window.addEventListener("blur", clear);+ document.addEventListener("focusin", focus);+ host.addEventListener("pointerdown", pointer);+ host.addEventListener("pointermove", move);+ host.addEventListener("pointerup", release);+ host.addEventListener("pointercancel", clear);+ host.addEventListener("lostpointercapture", lostCapture);+ return {+ clear,+ consume() { pending.clear(); },+ read(): PlayerInput {+ if (disposed || !canOwn(document.activeElement)) { keys.clear(); pending.clear(); return NO_INPUT; }+ // A press/release between render frames still reaches one physics step.+ const held = (...codes: string[]) => codes.some((code) => keys.has(code) || pending.has(code));+ return {+ forward: Number(held("KeyW", "ArrowUp")) - Number(held("KeyS", "ArrowDown")),+ right: Number(held("KeyD", "ArrowRight")) - Number(held("KeyA", "ArrowLeft")),+ run: held("ShiftLeft", "ShiftRight"), jump: held("Space"),+ };+ },+ dispose() {+ disposed = true; clear();+ window.removeEventListener("keydown", down); window.removeEventListener("keyup", up);+ window.removeEventListener("blur", clear); document.removeEventListener("focusin", focus);+ host.removeEventListener("pointerdown", pointer);+ host.removeEventListener("pointermove", move); host.removeEventListener("pointerup", release);+ host.removeEventListener("pointercancel", clear); host.removeEventListener("lostpointercapture", lostCapture);+ },+ };+}diff --git a/jarvis/ui/web/frontend/src/components/society/mars/mars.css b/jarvis/ui/web/frontend/src/components/society/mars/mars.cssnew file mode 100644index 0000000000..f7e771eb5d--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/mars/mars.css@@ -0,0 +1,21 @@+.mars-stage { display:flex; flex-direction:column; height:100%; min-height:0; background:hsl(var(--background)); color:hsl(var(--foreground)); }+.mars-toolbar { display:flex; align-items:center; justify-content:space-between; flex-wrap:wrap; gap:10px; padding:10px 14px; border-bottom:1px solid hsl(var(--border)); }+.mars-title { display:flex; flex-direction:column; gap:3px; font-size:13px; }+.mars-title span { font-size:11px; color:hsl(var(--muted-foreground)); }+.mars-actions { display:flex; align-items:center; flex-wrap:wrap; gap:5px; }+.mars-actions button, .mars-actions select { border:1px solid hsl(var(--border)); border-radius:5px; padding:6px 9px; background:hsl(var(--background)); color:hsl(var(--foreground)); font-size:11px; cursor:pointer; }+.mars-actions button:hover, .mars-actions button[aria-pressed="true"] { background:hsl(var(--secondary)); }+.mars-actions button:focus-visible, .mars-actions select:focus-visible, .mars-viewport:focus-visible { outline:2px solid hsl(var(--ring)); outline-offset:-2px; }+.mars-scene-container { position:relative; flex:1; min-height:180px; display:flex; }+.mars-viewport { position:relative; flex:1; min-width:0; overflow:hidden; touch-action:none; }+.mars-station-slot { position:absolute; z-index:25; right:10px; top:10px; width:min(400px, calc(100% - 20px)); max-height:calc(100% - 20px); overflow:auto; }+.mars-use-station { border:1px solid hsl(var(--border)); background:hsl(var(--secondary)); color:hsl(var(--foreground)); border-radius:4px; font-size:11px; padding:4px 8px; }+.mars-render-fallback { display:flex; align-items:center; justify-content:center; height:100%; min-height:180px; padding:24px; font-size:13px; color:hsl(var(--muted-foreground)); }+.mars-footer { display:flex; flex-wrap:wrap; gap:4px 20px; padding:8px 14px; border-top:1px solid hsl(var(--border)); background:hsl(var(--background)); }+.mars-footer p { margin:0; font-size:11px; color:hsl(var(--muted-foreground)); }+.mars-district-label { display:flex; flex-direction:column; align-items:center; gap:2px; padding:4px 7px; border:1px solid hsl(var(--border)); border-radius:4px; background:hsl(var(--popover) / .9); color:hsl(var(--popover-foreground)); white-space:nowrap; font-size:10px; }+.mars-district-label span { font-size:9px; color:hsl(var(--muted-foreground)); }+.mars-door-label { padding:4px 6px; border-radius:3px; background:hsl(var(--popover) / .9); color:hsl(var(--popover-foreground)); white-space:nowrap; font-size:10px; }+.gigi-focus-marker { border:1px solid hsl(var(--border)); border-radius:8px; padding:4px 8px; background:hsl(var(--popover) / .92); color:hsl(var(--popover-foreground)); font-size:11px; white-space:nowrap; cursor:pointer; }+.gigi-focus-marker:focus-visible { outline:2px solid hsl(var(--ring)); outline-offset:2px; }+@media (max-width:600px) { .mars-toolbar { padding:7px; } .mars-actions { gap:3px; } .mars-actions button { padding:6px; } .mars-footer { padding:6px 8px; } .mars-district-label { font-size:8px; padding:2px 4px; } }diff --git a/jarvis/ui/web/frontend/src/components/society/mars/navigationApi.test.ts b/jarvis/ui/web/frontend/src/components/society/mars/navigationApi.test.tsnew file mode 100644index 0000000000..d64abaa6f6--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/mars/navigationApi.test.ts@@ -0,0 +1,33 @@+import { describe, expect, it } from "vitest";+import { latestNavigationRecords, navigationSnapshotSchema } from "./navigationApi";++const row = (command: string, state = "moving", presence = "placed") => ({+ command_id: command, request_id: command, agent_id: "one", trace_id: command,+ world_id: "mars:ordinary", station_id: "communications-console", mode: "pedestrian",+ graph_version: 1, graph_signature: "a".repeat(64), state, presence,+ position: [268, 58, 68], current_node: "outpost-arrival", edge_id: "route-03", next_node: "console-approach", edge_progress: 0.3, reason: "",+});+const snapshot = (commands: unknown[]) => ({ world_id: "mars:ordinary", schema_version: 1,+ graph_version: 1, graph_signature: "a".repeat(64), seq: 5, commands, occupancies: [] });++describe("navigation client contract", () => {+ it("uses durable receipt order for the latest actor location, including stopped bodies", () => {+ const data = navigationSnapshotSchema.parse(snapshot([row("older"), row("newer", "canceled")]));+ expect(latestNavigationRecords(data)).toHaveLength(1);+ expect(latestNavigationRecords(data)[0].command_id).toBe("newer");+ expect(latestNavigationRecords(data)[0].presence).toBe("placed");+ });+ it("retains explicit nonphysical spawn queues without inventing placed actors", () => {+ const data = navigationSnapshotSchema.parse(snapshot([row("queued", "queueing", "spawn_queue")]));+ expect(latestNavigationRecords(data).filter((record) => record.presence === "placed")).toEqual([]);+ });+ it("rejects wrong worlds/graphs, oversized snapshots and nonfinite locations", () => {+ for (const body of [+ { ...snapshot([]), world_id: "mars:swarm:other" },+ { ...snapshot([]), graph_version: 2 },+ snapshot(Array.from({ length: 321 }, () => row("too-many"))),+ snapshot([{ ...row("invalid"), position: [Infinity, 0, 0] }]),+ snapshot([{ ...row("invalid"), state: "completed" }]),+ ]) expect(navigationSnapshotSchema.safeParse(body).success).toBe(false);+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/mars/navigationApi.ts b/jarvis/ui/web/frontend/src/components/society/mars/navigationApi.tsnew file mode 100644index 0000000000..346b593035--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/mars/navigationApi.ts@@ -0,0 +1,112 @@+import { z } from "zod";+import { MarsApiError, WORLD_ID } from "./api";+import { WORLD } from "./world";++export const NAVIGATION_STATES = ["queueing", "moving", "temporarily_blocked", "rerouting", "arrived", "unreachable", "canceled"] as const;+const identity = z.string().min(1).max(128);+const position = z.tuple([z.number().finite(), z.number().finite(), z.number().finite()]);+const travelRecordSchema = z.object({+ command_id: identity, request_id: identity, trace_id: identity,+ world_id: z.literal(WORLD_ID), station_id: identity, mode: z.enum(["pedestrian", "rover"]),+ graph_version: z.literal(WORLD.navigation.version), graph_signature: z.string().regex(/^[0-9a-f]{64}$/),+ state: z.enum(NAVIGATION_STATES), presence: z.enum(["spawn_queue", "placed"]),+ position, current_node: identity, edge_id: identity.nullable(), next_node: identity.nullable(),+ edge_progress: z.number().min(0).max(1), reason: z.string().max(200),+});+export const navigationRecordSchema = travelRecordSchema.extend({ agent_id: identity });+export type NavigationRecord = z.infer<typeof navigationRecordSchema>;+export const vehicleRecordSchema = travelRecordSchema.extend({ vehicle_id: identity, ride_id: identity.nullable() });+export type VehicleRecord = z.infer<typeof vehicleRecordSchema>;+export const RIDE_STATES = ["approaching", "ready_to_board", "boarded", "traveling", "arrived", "stopped", "exit_blocked", "completed", "canceled"] as const;+export const roverRideSchema = z.object({+ ride_id: identity, request_id: identity, agent_id: identity, vehicle_id: identity, trace_id: identity,+ origin_dock_id: identity, destination_dock_id: identity.nullable(), approach_command_id: identity,+ state: z.enum(RIDE_STATES), attached: z.boolean(),+ created_ms: z.number().int().nonnegative(), updated_ms: z.number().int().nonnegative(), deadline_ms: z.number().int().nonnegative(),+ reason: z.string().max(200),+});+export type RoverRideRecord = z.infer<typeof roverRideSchema>;+export const navigationSnapshotSchema = z.object({+ world_id: z.literal(WORLD_ID), schema_version: z.literal(1),+ graph_version: z.literal(WORLD.navigation.version), graph_signature: z.string().regex(/^[0-9a-f]{64}$/),+ seq: z.number().int().nonnegative(), commands: z.array(navigationRecordSchema).max(320),+ occupancies: z.array(z.object({ resource_id: identity, command_id: identity, agent_id: identity.nullable(),+ actor: z.object({ kind: z.enum(["agent", "vehicle"]), id: identity }).nullable().optional(),+ position, graph_signature: z.string().length(64) })).max(1024),+ vehicles: z.array(vehicleRecordSchema).max(64).default([]),+ rides: z.array(roverRideSchema).max(320).default([]),+});+export type NavigationSnapshot = z.infer<typeof navigationSnapshotSchema>;+const attemptSchema = z.object({ request_id: z.string().uuid(), agent_id: identity, station_id: identity });+export type MoveAttempt = z.infer<typeof attemptSchema>;+const ATTEMPT_KEY = `jarvis.${WORLD_ID}.pending-move.v1`;++export function readMoveAttempt(): MoveAttempt | null {+ try {+ const parsed = attemptSchema.safeParse(JSON.parse(sessionStorage.getItem(ATTEMPT_KEY) ?? "null"));+ return parsed.success ? parsed.data : null;+ } catch { return null; } // Storage denial/corruption only loses refresh retry recovery.+}+export function saveMoveAttempt(attempt: MoveAttempt): void {+ try { sessionStorage.setItem(ATTEMPT_KEY, JSON.stringify(attempt)); }+ catch { /* In-memory retries retain the same request identity. */ }+}+export function clearMoveAttempt(requestId: string): void {+ try {+ if (readMoveAttempt()?.request_id === requestId) sessionStorage.removeItem(ATTEMPT_KEY);+ } catch { /* A later retry is idempotent even if storage remains unavailable. */ }+}++async function request(path: string, init?: RequestInit): Promise<unknown> {+ const response = await fetch(`/api/society/mars${path}`, {+ ...init, headers: { "Content-Type": "application/json", ...init?.headers },+ });+ if (!response.ok) throw new MarsApiError(response.status);+ return response.json();+}+export async function fetchNavigationSnapshot(signal?: AbortSignal): Promise<NavigationSnapshot> {+ return navigationSnapshotSchema.parse(await request("/navigation/snapshot", { signal }));+}+export async function submitMove(attempt: MoveAttempt): Promise<NavigationRecord> {+ return navigationRecordSchema.parse(await request(`/agents/${encodeURIComponent(attempt.agent_id)}/moves`, {+ method: "POST", body: JSON.stringify({ request_id: attempt.request_id, station_id: attempt.station_id,+ world_id: WORLD_ID, schema_version: 1, layout_version: WORLD.layout_version,+ graph_version: WORLD.navigation.version, mode: "pedestrian" }),+ }));+}+export async function cancelMove(record: NavigationRecord): Promise<NavigationRecord> {+ return navigationRecordSchema.parse(await request(`/agents/${encodeURIComponent(record.agent_id)}/moves/${encodeURIComponent(record.command_id)}/cancel`, { method: "POST" }));+}++/** The API orders receipts by durable ordinal, including each actor's latest receipt. */+export function latestNavigationRecords(snapshot?: NavigationSnapshot): NavigationRecord[] {+ const latest = new Map<string, NavigationRecord>();+ for (const record of snapshot?.commands ?? []) latest.set(record.agent_id, record);+ return [...latest.values()];+}++export function currentRoverRide(snapshot: NavigationSnapshot | undefined, agentId: string): RoverRideRecord | undefined {+ return snapshot?.rides.find((ride) => ride.agent_id === agentId && !["completed", "canceled"].includes(ride.state));+}++/** Attached riders have no separate pedestrian body, even if the vehicle is unavailable. */+export function pedestrianNavigationRecords(snapshot?: NavigationSnapshot): NavigationRecord[] {+ const attached = new Set(snapshot?.rides.filter((ride) => ride.attached).map((ride) => ride.agent_id));+ return latestNavigationRecords(snapshot).filter((record) => !attached.has(record.agent_id));+}++/** A display-only attachment projection from one atomic server snapshot. */+export function agentFollowRecords(snapshot?: NavigationSnapshot): NavigationRecord[] {+ const records = latestNavigationRecords(snapshot);+ const rides = new Map(snapshot?.rides.filter((ride) => ride.attached).map((ride) => [ride.agent_id, ride]));+ const vehicles = new Map(snapshot?.vehicles.map((vehicle) => [vehicle.vehicle_id, vehicle]));+ return records.flatMap((record) => {+ const ride = rides.get(record.agent_id);+ if (!ride) return [record];+ const vehicle = vehicles.get(ride.vehicle_id);+ if (!vehicle || vehicle.ride_id !== ride.ride_id || vehicle.presence !== "placed") return [];+ return [{ ...record, position: vehicle.position, presence: vehicle.presence, state: vehicle.state,+ mode: vehicle.mode, current_node: vehicle.current_node, edge_id: vehicle.edge_id,+ next_node: vehicle.next_node, edge_progress: vehicle.edge_progress }];+ });+}diff --git a/jarvis/ui/web/frontend/src/components/society/mars/orbitCamera.test.ts b/jarvis/ui/web/frontend/src/components/society/mars/orbitCamera.test.tsnew file mode 100644index 0000000000..42165120aa--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/mars/orbitCamera.test.ts@@ -0,0 +1,48 @@+import { describe, expect, it } from "vitest";+import { constrainOrbitPose, orbitLensIsClear } from "./orbitCamera";+import { frameInspectionBounds } from "./camera";+import { box, outpostCloseBounds, type Vec3 } from "./world";++describe("orbit lens motion", () => {+ it("keeps the first real Outpost wheel gesture near the previous camera instead of collapsing onto its buried pivot", () => {+ const before = frameInspectionBounds(outpostCloseBounds(), 1745 / 786);+ const requested = { target: before.target, position: before.position.map((n, i) => before.target[i] + (n - before.target[i]) * 0.94) as Vec3 };+ const result = constrainOrbitPose(before, requested);+ expect(Math.hypot(...result.position.map((n, i) => n - before.target[i]))).toBeGreaterThan(200);+ expect(result.position).toEqual(requested.position);+ expect(result.target).toEqual(before.target);+ });++ it("does not treat a subject between the pivot and a clear lens as a collision", () => {+ const subject = box("subject", 0, 0, 0, 10, 30, 10);+ const before = { position: [0, 10, 25] as Vec3, target: [0, 10, 0] as Vec3 };+ const wanted = { position: [0, 10, 20] as Vec3, target: before.target };+ expect(constrainOrbitPose(before, wanted, [subject], () => -10)).toEqual(wanted);+ });++ it("stops a large dolly before a wall and allows an immediate reverse gesture", () => {+ const wall = box("wall", 0, 0, 0, 10, 20, 1);+ const before = { position: [0, 5, 5] as Vec3, target: [0, 5, -5] as Vec3 };+ const blocked = constrainOrbitPose(before, { ...before, position: [0, 5, -4] }, [wall], () => -10);+ expect(blocked.position[2]).toBeGreaterThan(0.85);+ expect(blocked.position[2]).toBeLessThan(0.86);+ expect(constrainOrbitPose(blocked, before, [wall], () => -10)).toEqual(before);+ });++ it("moves lens and pivot together when a pan meets an obstacle", () => {+ const wall = box("wall", 5, 0, 0, 1, 20, 20);+ const before = { position: [0, 5, 5] as Vec3, target: [0, 5, 0] as Vec3 };+ const result = constrainOrbitPose(before, { position: [10, 5, 5], target: [10, 5, 0] }, [wall], () => -10);+ expect(result.position[0]).toBeLessThan(4.15);+ expect(result.position[0]).toBe(result.target[0]);+ expect(result.position[2] - result.target[2]).toBe(5);+ });++ it("stops above ground without moving the pivot into the floor", () => {+ const before = { position: [0, 10, 10] as Vec3, target: [0, 0, 0] as Vec3 };+ const result = constrainOrbitPose(before, { ...before, position: [0, -10, 10] }, [], () => 0);+ expect(result.position[1]).toBeGreaterThanOrEqual(0.35);+ expect(result.position[1]).toBeLessThan(0.351);+ expect(orbitLensIsClear([0, -1, 10], [], () => 0)).toBe(false);+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/mars/orbitCamera.ts b/jarvis/ui/web/frontend/src/components/society/mars/orbitCamera.tsnew file mode 100644index 0000000000..e6aa0fe44b--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/mars/orbitCamera.ts@@ -0,0 +1,53 @@+import { CAMERA_CLEARANCE, segmentBox } from "./camera";+import { BUILDING_COLLIDERS, cameraGroundHeight, WORLD_BOUNDS, type Collider, type Vec3 } from "./world";+import type { CameraPose } from "./viewPreferences";++type Ground = (x: number, z: number) => number;+const interpolate = (a: Vec3, b: Vec3, t: number): Vec3 => a.map((n, i) => n + (b[i] - n) * t) as Vec3;++export function orbitLensIsClear(position: Vec3, colliders: Collider[] = BUILDING_COLLIDERS, ground: Ground = cameraGroundHeight): boolean {+ return position.every(Number.isFinite)+ && position[1] >= ground(position[0], position[2]) + CAMERA_CLEARANCE+ && !colliders.some(box => position.every((n, i) => n >= box.min[i] - CAMERA_CLEARANCE && n <= box.max[i] + CAMERA_CLEARANCE));+}++/** Sweep the lens from its previous pose, never from the inspection pivot.+ * A subject's centre is often inside a building or below its floor. Treating+ * that sightline as a follow-camera tether collapses the first wheel gesture.+ */+export function constrainOrbitPose(previous: CameraPose, requested: CameraPose, colliders: Collider[] = BUILDING_COLLIDERS, ground: Ground = cameraGroundHeight): CameraPose {+ const target = requested.target.map((n, i) => Math.max(WORLD_BOUNDS.min[i], Math.min(WORLD_BOUNDS.max[i], n))) as Vec3;+ const position = requested.position.map((n, i) => n + (target[i] - requested.target[i])) as Vec3;+ const distance = Math.hypot(...position.map((n, i) => n - previous.position[i]));+ if (distance < 1e-8) return { position, target };+ let fraction = 1;+ for (const box of colliders) {+ const hit = segmentBox(previous.position, position, box, CAMERA_CLEARANCE);+ if (hit !== null) fraction = Math.min(fraction, Math.max(0, hit - 0.001 / distance));+ }+ // Terrain is a continuous height field plus the authored cliff footprint.+ // Refine the first crossing so large wheel deltas stop at the same surface.+ const samples = Math.min(1024, Math.max(8, Math.ceil(distance / 0.25)));+ let safe = 0;+ for (let i = 1; i <= samples; i++) {+ const t = Math.min(fraction, i / samples);+ const p = interpolate(previous.position, position, t);+ if (p[1] < ground(p[0], p[2]) + CAMERA_CLEARANCE) {+ let blocked = t;+ for (let step = 0; step < 16; step++) {+ const mid = (safe + blocked) / 2, q = interpolate(previous.position, position, mid);+ if (q[1] < ground(q[0], q[2]) + CAMERA_CLEARANCE) blocked = mid;+ else safe = mid;+ }+ fraction = safe;+ break;+ }+ safe = t;+ if (t >= fraction) break;+ }+ if (fraction === 1) return { position, target };+ return {+ position: interpolate(previous.position, position, fraction),+ target: interpolate(previous.target, target, fraction),+ };+}diff --git a/jarvis/ui/web/frontend/src/components/society/mars/roadGeometry.test.ts b/jarvis/ui/web/frontend/src/components/society/mars/roadGeometry.test.tsnew file mode 100644index 0000000000..faa13bc99e--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/mars/roadGeometry.test.ts@@ -0,0 +1,30 @@+import { describe, expect, it } from "vitest";+import { Vector3 } from "three";+import { roadOrientation } from "./roadGeometry";+import { ROADS } from "./world";+import { BUILDING_COLLIDERS } from "./world";+import { segmentBox } from "./camera";++describe("graded road rendering", () => {+ it("keeps the advertised pedestrian routes clear of building walls", () => {+ for (const road of ROADS) {+ const start: [number, number, number] = [road.start[0], road.start[1] + 1, road.start[2]];+ const end: [number, number, number] = [road.end[0], road.end[1] + 1, road.end[2]];+ for (const collider of BUILDING_COLLIDERS) {+ expect(segmentBox(start, end, collider, 0.4), `${road.id} intersects ${collider.id}`).toBeNull();+ }+ }+ });+ it("keeps every route horizontal across its width and every railing upright", () => {+ for (const road of ROADS) {+ const orientation = roadOrientation(road.start, road.end);+ const width = new Vector3(road.width / 2, 0, 0).applyQuaternion(orientation);+ const up = new Vector3(0, 1, 0).applyQuaternion(orientation);+ expect(width.y, road.id).toBeCloseTo(0, 8);+ expect(up.y, road.id).toBeGreaterThan(0.9);+ const forward = new Vector3(0, 0, 1).applyQuaternion(orientation);+ const delta = new Vector3(...road.end).sub(new Vector3(...road.start)).normalize();+ expect(forward.distanceTo(delta), road.id).toBeLessThan(1e-8);+ }+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/mars/roadGeometry.ts b/jarvis/ui/web/frontend/src/components/society/mars/roadGeometry.tsnew file mode 100644index 0000000000..349f923fc9--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/mars/roadGeometry.ts@@ -0,0 +1,10 @@+import { Matrix4, Quaternion, Vector3 } from "three";+import type { Vec3 } from "./world";++/** Grade along the road; the width stays horizontal and the railings stay above it. */+export function roadOrientation(start: Vec3, end: Vec3): Quaternion {+ const forward = new Vector3(...end).sub(new Vector3(...start)).normalize();+ const right = new Vector3(forward.z, 0, -forward.x).normalize();+ const up = new Vector3().crossVectors(forward, right).normalize();+ return new Quaternion().setFromRotationMatrix(new Matrix4().makeBasis(right, up, forward));+}diff --git a/jarvis/ui/web/frontend/src/components/society/mars/roverApi.test.ts b/jarvis/ui/web/frontend/src/components/society/mars/roverApi.test.tsnew file mode 100644index 0000000000..d92c18fc2b--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/mars/roverApi.test.ts@@ -0,0 +1,48 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { agentFollowRecords, navigationSnapshotSchema, pedestrianNavigationRecords } from "./navigationApi";+import { clearRoverAttempt, readRoverAttempt, saveRoverAttempt, submitRoverAction, type RoverAttempt } from "./roverApi";+import { roverRide, roverSnapshot, roverVehicle } from "./roverFixtures.test-support";++afterEach(() => { vi.unstubAllGlobals(); sessionStorage.clear(); });++describe("rover atomic snapshot and retry contract", () => {+ it("suppresses the separate body and follows only the matching confirmed vehicle", () => {+ const ride = { ...roverRide, state: "traveling" as const, attached: true };+ const vehicle = { ...roverVehicle, ride_id: ride.ride_id, position: [300, 58.006, 84] as [number, number, number], state: "moving" as const };+ const snapshot = roverSnapshot([ride], [vehicle]);+ expect(pedestrianNavigationRecords(snapshot)).toEqual([]);+ expect(agentFollowRecords(snapshot)[0].position).toEqual(vehicle.position);+ expect(snapshot.commands[0].position).not.toEqual(vehicle.position);+ for (const vehicles of [[], [{ ...vehicle, ride_id: "other-ride" }], [{ ...vehicle, presence: "spawn_queue" as const }]]) {+ expect(agentFollowRecords(roverSnapshot([ride], vehicles))).toEqual([]);+ expect(pedestrianNavigationRecords(roverSnapshot([ride], vehicles))).toEqual([]);+ }+ expect(pedestrianNavigationRecords(roverSnapshot([{ ...ride, state: "completed", attached: false }], [vehicle]))).toHaveLength(1);+ });++ it("accepts typed vehicle occupancy without inventing an ordinary agent", () => {+ const snapshot = roverSnapshot();+ const data = navigationSnapshotSchema.parse({ ...snapshot, occupancies: [{ resource_id: "node:rover-a-dock",+ command_id: roverVehicle.command_id, agent_id: null, actor: { kind: "vehicle", id: "outpost-rover" },+ position: roverVehicle.position, graph_signature: "a".repeat(64) }] });+ expect(data.occupancies[0].agent_id).toBeNull();+ expect(data.occupancies[0].actor?.kind).toBe("vehicle");+ expect(navigationSnapshotSchema.safeParse({ ...snapshot, rides: [{ ...roverRide, state: "boarding_complete_by_animation" }] }).success).toBe(false);+ expect(navigationSnapshotSchema.safeParse({ ...snapshot, vehicles: [{ ...roverVehicle, position: [NaN, 58, 70] }] }).success).toBe(false);+ });++ it("saves the exact action payload through refresh and clears only its own attempt", async () => {+ const attempt: RoverAttempt = { request_id: crypto.randomUUID(), agent_id: "agent/one", ride_id: "ride/one", action: "travel", destination_dock_id: "outpost-b" };+ saveRoverAttempt(attempt);+ expect(readRoverAttempt()).toEqual(attempt);+ clearRoverAttempt("different"); expect(readRoverAttempt()).toEqual(attempt);+ const fetcher = vi.fn(async () => new Response(JSON.stringify(roverRide), { status: 200 }));+ vi.stubGlobal("fetch", fetcher);+ await submitRoverAction(readRoverAttempt()!); await submitRoverAction(readRoverAttempt()!);+ expect(fetcher.mock.calls[0]).toEqual(fetcher.mock.calls[1]);+ const [path, init] = fetcher.mock.calls[0] as unknown as [string, RequestInit];+ expect(path).toBe("/api/society/mars/agents/agent%2Fone/rides/ride%2Fone/travel");+ expect(JSON.parse(init.body as string)).toEqual({ request_id: attempt.request_id, destination_dock_id: "outpost-b" });+ clearRoverAttempt(attempt.request_id); expect(readRoverAttempt()).toBeNull();+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/mars/roverApi.ts b/jarvis/ui/web/frontend/src/components/society/mars/roverApi.tsnew file mode 100644index 0000000000..a56932e1c2--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/mars/roverApi.ts@@ -0,0 +1,47 @@+import { z } from "zod";+import { MarsApiError, WORLD_ID } from "./api";+import { roverRideSchema, type RoverRideRecord } from "./navigationApi";+import { WORLD } from "./world";++const identity = z.string().min(1).max(128);+const base = { request_id: z.string().uuid(), agent_id: identity };+const ride = { ...base, ride_id: identity };+export const roverAttemptSchema = z.discriminatedUnion("action", [+ z.object({ ...base, action: z.literal("reserve"), vehicle_id: identity }),+ z.object({ ...ride, action: z.literal("board") }),+ z.object({ ...ride, action: z.literal("travel"), destination_dock_id: identity }),+ z.object({ ...ride, action: z.literal("cancel") }),+ z.object({ ...ride, action: z.literal("exit") }),+]);+export type RoverAttempt = z.infer<typeof roverAttemptSchema>;+const ATTEMPT_KEY = `jarvis.${WORLD_ID}.pending-rover.v1`;++export function readRoverAttempt(): RoverAttempt | null {+ try {+ const result = roverAttemptSchema.safeParse(JSON.parse(sessionStorage.getItem(ATTEMPT_KEY) ?? "null"));+ return result.success ? result.data : null;+ } catch { return null; } // Storage corruption or denial only loses refresh recovery.+}+export function saveRoverAttempt(attempt: RoverAttempt): void {+ try { sessionStorage.setItem(ATTEMPT_KEY, JSON.stringify(attempt)); }+ catch { /* The mounted panel retains the original request for safe retries. */ }+}+export function clearRoverAttempt(requestId: string): void {+ try {+ if (readRoverAttempt()?.request_id === requestId) sessionStorage.removeItem(ATTEMPT_KEY);+ } catch { /* Replaying the retained request remains idempotent. */ }+}++export async function submitRoverAction(attempt: RoverAttempt): Promise<RoverRideRecord> {+ const action = roverAttemptSchema.parse(attempt);+ const basePath = `/api/society/mars/agents/${encodeURIComponent(action.agent_id)}/rides`;+ const path = action.action === "reserve" ? basePath : `${basePath}/${encodeURIComponent(action.ride_id)}/${action.action}`;+ const body = action.action === "reserve"+ ? { request_id: action.request_id, vehicle_id: action.vehicle_id, world_id: WORLD_ID,+ schema_version: 1, layout_version: WORLD.layout_version, graph_version: WORLD.navigation.version }+ : action.action === "travel" ? { request_id: action.request_id, destination_dock_id: action.destination_dock_id }+ : { request_id: action.request_id };+ const response = await fetch(path, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });+ if (!response.ok) throw new MarsApiError(response.status);+ return roverRideSchema.parse(await response.json());+}diff --git a/jarvis/ui/web/frontend/src/components/society/mars/roverFixtures.test-support.ts b/jarvis/ui/web/frontend/src/components/society/mars/roverFixtures.test-support.tsnew file mode 100644index 0000000000..c9f00341be--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/mars/roverFixtures.test-support.ts@@ -0,0 +1,20 @@+import { navigationSnapshotSchema, roverRideSchema, vehicleRecordSchema } from "./navigationApi";+import { WORLD } from "./world";++export const roverAgent = {+ command_id: "approach-one", request_id: "approach-one", agent_id: "agent-one", trace_id: "trace",+ world_id: WORLD.world_id, station_id: "rover-a-board", mode: "pedestrian", graph_version: WORLD.navigation.version,+ graph_signature: "a".repeat(64), state: "arrived", presence: "placed", position: [282, 58.006, 75],+ current_node: "rover-a-board", edge_id: null, next_node: null, edge_progress: 0, reason: "",+};+export const roverVehicle = vehicleRecordSchema.parse({ ...roverAgent, vehicle_id: "outpost-rover", command_id: "vehicle-one",+ ride_id: null, mode: "rover", position: [282, 58.006, 74.8], current_node: "rover-a-dock" });+export const roverRide = roverRideSchema.parse({+ ride_id: "ride-one", request_id: "reservation-one", agent_id: "agent-one", vehicle_id: "outpost-rover", trace_id: "trace",+ origin_dock_id: "outpost-a", destination_dock_id: null, approach_command_id: "approach-one", state: "ready_to_board",+ attached: false, created_ms: 1, updated_ms: 2, deadline_ms: 10000, reason: "",+});+export function roverSnapshot(rides = [roverRide], vehicles = [{ ...roverVehicle, ride_id: "ride-one" }]) {+ return navigationSnapshotSchema.parse({ world_id: WORLD.world_id, schema_version: 1, graph_version: WORLD.navigation.version,+ graph_signature: "a".repeat(64), seq: 1, commands: [roverAgent], occupancies: [], vehicles, rides });+}diff --git a/jarvis/ui/web/frontend/src/components/society/mars/shadows.test.ts b/jarvis/ui/web/frontend/src/components/society/mars/shadows.test.tsnew file mode 100644index 0000000000..913514be4d--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/mars/shadows.test.ts@@ -0,0 +1,27 @@+import { expect, it } from "vitest";+import { OrthographicCamera, Vector3 } from "three";+import { boundsCorners } from "./camera";+import { outpostBounds } from "./world";+import { fitOutpostShadow, OUTPOST_SHADOW, SUN_POSITION, SUN_TARGET } from "./shadows";++it("keeps every authored bridge, cliff and tower corner inside the shadow camera", () => {+ const { left, right, top, bottom, near, far } = OUTPOST_SHADOW;+ const camera = new OrthographicCamera(left, right, top, bottom, near, far);+ camera.position.fromArray(SUN_POSITION); camera.lookAt(...SUN_TARGET); camera.updateMatrixWorld();+ for (const point of boundsCorners(outpostBounds())) {+ const projected = new Vector3(...point).project(camera);+ for (const coordinate of projected.toArray()) expect(Math.abs(coordinate)).toBeLessThan(1);+ }+});++it("retains a small physical depth offset when the reference bounds change", () => {+ const bounds = outpostBounds();+ const wider = fitOutpostShadow({ min: [bounds.min[0] - 20, bounds.min[1], bounds.min[2]], max: bounds.max });+ expect(wider.far - wider.near).not.toBe(OUTPOST_SHADOW.far - OUTPOST_SHADOW.near);+ for (const shadow of [OUTPOST_SHADOW, wider]) {+ const physicalOffset = -shadow.bias * (shadow.far - shadow.near);+ expect(physicalOffset).toBeGreaterThan(0);+ expect(physicalOffset).toBeLessThan(0.2);+ expect(physicalOffset).toBeCloseTo(0.18);+ }+});diff --git a/jarvis/ui/web/frontend/src/components/society/mars/shadows.ts b/jarvis/ui/web/frontend/src/components/society/mars/shadows.tsnew file mode 100644index 0000000000..af02331d98--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/mars/shadows.ts@@ -0,0 +1,29 @@+import { OrthographicCamera, Vector3 } from "three";+import { boundsCorners } from "./camera";+import { outpostBounds, OUTPOST, type Bounds, type Vec3 } from "./world";++export const SUN_POSITION: Vec3 = [OUTPOST.center[0] - 140, 230, 180];+export const SUN_TARGET: Vec3 = [320, 58, 50];+export const SHADOW_MAP_SIZE = 2048;++/** Fit the complete authored reference in light space, including its bridge.+ * Depth bias is expressed in metres before conversion to normalized depth;+ * changing the shadow frustum must not change its physical separation.+ */+export function fitOutpostShadow(bounds: Bounds) {+ const camera = new OrthographicCamera();+ camera.position.fromArray(SUN_POSITION);+ camera.lookAt(...SUN_TARGET);+ camera.updateMatrixWorld();+ const points = boundsCorners(bounds).map((point) => new Vector3(...point).applyMatrix4(camera.matrixWorldInverse));+ const padding = 8;+ const left = Math.min(...points.map((p) => p.x)) - padding;+ const right = Math.max(...points.map((p) => p.x)) + padding;+ const bottom = Math.min(...points.map((p) => p.y)) - padding;+ const top = Math.max(...points.map((p) => p.y)) + padding;+ const near = Math.max(0.5, -Math.max(...points.map((p) => p.z)) - padding);+ const far = -Math.min(...points.map((p) => p.z)) + padding;+ return { left, right, bottom, top, near, far, bias: -0.18 / (far - near), normalBias: 0.06 };+}++export const OUTPOST_SHADOW = fitOutpostShadow(outpostBounds());diff --git a/jarvis/ui/web/frontend/src/components/society/mars/useAgentFollowTarget.test.tsx b/jarvis/ui/web/frontend/src/components/society/mars/useAgentFollowTarget.test.tsxnew file mode 100644index 0000000000..a244fbb81c--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/mars/useAgentFollowTarget.test.tsx@@ -0,0 +1,75 @@+import { renderHook } from "@testing-library/react";+import { describe, expect, it } from "vitest";+import { navigationRecordSchema, type NavigationRecord } from "./navigationApi";+import { useAgentFollowTarget, type AgentFollowSnapshot } from "./useAgentFollowTarget";++const record = navigationRecordSchema.parse({+ command_id: "first", request_id: "request", agent_id: "one", trace_id: "trace",+ world_id: "mars:ordinary", station_id: "communications-console", mode: "pedestrian",+ graph_version: 1, graph_signature: "a".repeat(64), state: "moving", presence: "placed",+ position: [268, 58, 68], current_node: "outpost-arrival", edge_id: "route-03",+ next_node: "console-approach", edge_progress: 0.3, reason: "",+});+function snapshot(changes: Partial<AgentFollowSnapshot> = {}): AgentFollowSnapshot {+ return { records: [record], names: new Map([["one", "Worker"]]), navigationFresh: true, rosterFresh: true, offline: false, ...changes };+}++describe("confirmed agent-follow targets", () => {+ it("waits for both fresh queries before restoring a stored identity", () => {+ const hook = renderHook(({ data }) => useAgentFollowTarget("one", data), {+ initialProps: { data: snapshot({ navigationFresh: false, rosterFresh: false }) },+ });+ expect(hook.result.current).toEqual({ target: null, status: "waiting" });+ hook.rerender({ data: snapshot({ rosterFresh: false }) });+ expect(hook.result.current).toEqual({ target: null, status: "waiting" });+ hook.rerender({ data: snapshot() });+ expect(hook.result.current.target?.position).toEqual(record.position);+ expect(hook.result.current.status).toBe("live");+ hook.unmount();+ });++ it("follows the physical agent across replacement commands and preserves placed terminal states", () => {+ const hook = renderHook(({ data }) => useAgentFollowTarget("one", data), { initialProps: { data: snapshot() } });+ const replacement: NavigationRecord = { ...record, command_id: "replacement", position: [270, 58, 70] };+ hook.rerender({ data: snapshot({ records: [replacement] }) });+ expect(hook.result.current.target).toEqual({ agentId: "one", name: "Worker", position: replacement.position });+ for (const state of ["arrived", "canceled", "unreachable"] as const) {+ hook.rerender({ data: snapshot({ records: [{ ...replacement, state }] }) });+ expect(hook.result.current.status).toBe("live");+ expect(hook.result.current.target?.agentId).toBe("one");+ }+ hook.unmount();+ });++ it("holds the last confirmed target while offline and resumes only with fresh placement", () => {+ const hook = renderHook(({ data }) => useAgentFollowTarget("one", data), { initialProps: { data: snapshot() } });+ const confirmed = hook.result.current.target;+ hook.rerender({ data: snapshot({ records: [], navigationFresh: false, rosterFresh: false, offline: true }) });+ expect(hook.result.current).toEqual({ target: confirmed, status: "offline" });+ const position: NavigationRecord["position"] = [272, 58, 74];+ hook.rerender({ data: snapshot({ records: [{ ...record, position }] }) });+ expect(hook.result.current.target?.position).toEqual(position);+ expect(hook.result.current.status).toBe("live");+ hook.unmount();+ });++ it.each(["navigation", "roster", "spawn_queue"])("clears a target missing from successful %s evidence", (kind) => {+ const hook = renderHook(({ data }) => useAgentFollowTarget("one", data), { initialProps: { data: snapshot() } });+ hook.rerender({ data: snapshot(kind === "navigation" ? { records: [], rosterFresh: false, offline: true }+ : kind === "roster" ? { names: new Map(), navigationFresh: false, offline: true }+ : { records: [{ ...record, presence: "spawn_queue" }] }) });+ expect(hook.result.current).toEqual({ target: null, status: "missing" });+ hook.unmount();+ });++ it("never borrows the old target when changing identity or stopping", () => {+ const hook = renderHook(({ id, data }) => useAgentFollowTarget(id, data), {+ initialProps: { id: "one" as string | null, data: snapshot() },+ });+ hook.rerender({ id: "two", data: snapshot({ navigationFresh: false, rosterFresh: false, offline: true }) });+ expect(hook.result.current).toEqual({ target: null, status: "offline" });+ hook.rerender({ id: null, data: snapshot() });+ expect(hook.result.current).toEqual({ target: null, status: "idle" });+ hook.unmount();+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/mars/useAgentFollowTarget.ts b/jarvis/ui/web/frontend/src/components/society/mars/useAgentFollowTarget.tsnew file mode 100644index 0000000000..a634482580--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/mars/useAgentFollowTarget.ts@@ -0,0 +1,41 @@+import { useEffect, useMemo, useRef } from "react";+import type { NavigationRecord } from "./navigationApi";+import type { Vec3 } from "./world";++export interface AgentFollowTarget {+ agentId: string;+ name: string;+ position: Vec3;+}++export interface AgentFollowSnapshot {+ records: NavigationRecord[];+ names: ReadonlyMap<string, string>;+ navigationFresh: boolean;+ rosterFresh: boolean;+ offline: boolean;+}++/** A failed request is not evidence of deletion; cached data cannot restore follow. */+export function useAgentFollowTarget(agentId: string | null, snapshot: AgentFollowSnapshot) {+ const confirmed = useRef<AgentFollowTarget | null>(null);+ const { records, names, navigationFresh, rosterFresh, offline } = snapshot;+ const record = records.find((item) => item.agent_id === agentId);+ const name = agentId ? names.get(agentId) : undefined;+ const missing = Boolean(agentId && ((navigationFresh && record?.presence !== "placed")+ || (rosterFresh && name === undefined)));+ const live = Boolean(agentId && !missing && navigationFresh && rosterFresh && !offline);+ const target = useMemo<AgentFollowTarget | null>(() => {+ if (live && agentId && record && name !== undefined) return { agentId, name, position: record.position };+ if (agentId && !missing && confirmed.current?.agentId === agentId) return confirmed.current;+ return null;+ }, [agentId, live, missing, name, record]);++ useEffect(() => {+ if (!agentId || missing) confirmed.current = null;+ else if (live) confirmed.current = target;+ }, [agentId, missing, live, target]);++ const status = !agentId ? "idle" : missing ? "missing" : offline ? "offline" : live ? "live" : "waiting";+ return { target, status };+}diff --git a/jarvis/ui/web/frontend/src/components/society/mars/useMarsNavigation.ts b/jarvis/ui/web/frontend/src/components/society/mars/useMarsNavigation.tsnew file mode 100644index 0000000000..6266920e30--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/mars/useMarsNavigation.ts@@ -0,0 +1,18 @@+import { createContext, useContext } from "react";+import { useQuery, type UseQueryResult } from "@tanstack/react-query";+import { WORLD_ID } from "./api";+import { fetchNavigationSnapshot, type NavigationSnapshot } from "./navigationApi";++export const NAVIGATION_KEY = ["mars", WORLD_ID, "navigation"] as const;+export const MarsNavigationContext = createContext<UseQueryResult<NavigationSnapshot, Error> | null>(null);++/** World and its operator panel share one polling owner; Ledger can own its own. */+export function useMarsNavigation(enabled = true) {+ const shared = useContext(MarsNavigationContext);+ const local = useQuery<NavigationSnapshot, Error>({+ queryKey: NAVIGATION_KEY, queryFn: ({ signal }) => fetchNavigationSnapshot(signal),+ enabled: enabled && !shared, retry: false, refetchOnWindowFocus: false,+ refetchInterval: enabled && !shared ? () => 1000 + Math.random() * 250 : false,+ });+ return shared ?? local;+}diff --git a/jarvis/ui/web/frontend/src/components/society/mars/viewPreferences.test.ts b/jarvis/ui/web/frontend/src/components/society/mars/viewPreferences.test.tsnew file mode 100644index 0000000000..b8276dc541--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/mars/viewPreferences.test.ts@@ -0,0 +1,87 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { parseViewPreferences, readViewPreferences, saveViewPreferences, VIEW_KEY, type CameraPose, type ViewPreferences } from "./viewPreferences";+import { WORLD } from "./world";++const pose: CameraPose = { position: [320, 100, 150], target: [320, 76, 50] };+const preferences: ViewPreferences = { mode: "follow", followAgentId: "comms", viewpoint: "rear", neutral: true, shadows: false, pose };+const saved = { ...preferences, world_id: WORLD.world_id, layout_version: WORLD.layout_version };+const parse = (change: Record<string, unknown>) => parseViewPreferences(JSON.stringify({ ...saved, ...change }));++afterEach(() => { vi.unstubAllGlobals(); localStorage.clear(); });++describe("Mars view preferences", () => {+ it("restores and persists the close reference preset within its world and layout", () => {+ const close: ViewPreferences = { ...preferences, mode: "outpost", followAgentId: null, viewpoint: "close_reference" };+ expect(parse({ ...close })).toEqual(close);+ saveViewPreferences(close);+ expect(readViewPreferences()).toEqual(close);+ expect(JSON.parse(localStorage.getItem(VIEW_KEY)!)).toEqual({ ...saved, ...close });+ for (const change of [{ world_id: "mars:swarm:other" }, { layout_version: WORLD.layout_version + 1 }]) {+ expect(parse({ ...close, ...change })).toMatchObject({ mode: "overview", viewpoint: "reference", followAgentId: null });+ }+ });++ it("rejects an unknown camera preset instead of restoring unrecognized view state", () => {+ expect(parse({ viewpoint: "unknown_reference" })).toMatchObject({ mode: "overview", viewpoint: "reference", followAgentId: null, pose: null });+ });++ it("restores a selected agent and trims surrounding spaces without needing a stale pose", () => {+ expect(parse({})).toEqual(preferences);+ expect(parse({ followAgentId: " comms ", pose: null })).toEqual({ ...preferences, pose: null });+ expect(parse({ followAgentId: "a".repeat(128) }).followAgentId).toHaveLength(128);+ });++ it.each([undefined, null, 7, {}, "", " ", "a".repeat(129), "comms\n", "com\u0000ms", "com\u007fms", "com\u0085ms"])(+ "exits follow for invalid agent identity %j, keeping only a usable camera pose", (followAgentId) => {+ expect(parse({ followAgentId })).toEqual({ ...preferences, mode: "orbit", followAgentId: null });+ expect(parse({ followAgentId, pose: null })).toEqual({ ...preferences, mode: "overview", followAgentId: null, pose: null });+ },+ );++ it.each(["overview", "outpost", "orbit", "player"] as const)("clears follow identity when restoring %s mode", (mode) => {+ expect(parse({ mode })).toEqual({ ...preferences, mode, followAgentId: null });+ });++ it("still reads older camera preferences that have no follow field", () => {+ const { followAgentId: _identity, ...legacy } = saved;+ expect(parseViewPreferences(JSON.stringify({ ...legacy, mode: "orbit" }))).toEqual({ ...preferences, mode: "orbit", followAgentId: null });+ });++ it("does not restore follow selection from another world or layout", () => {+ for (const change of [{ world_id: "mars:swarm:other" }, { layout_version: WORLD.layout_version + 1 }]) {+ expect(parse(change)).toMatchObject({ mode: "overview", followAgentId: null, pose: null });+ }+ expect(parseViewPreferences("broken JSON")).toMatchObject({ mode: "overview", followAgentId: null, pose: null });+ });++ it("stores only view fields and leaves other world and authoritative state untouched", () => {+ const otherKey = "jarvis.mars:swarm:other.view.v1";+ const authorityKey = "jarvis.mars:ordinary.journeys";+ const journey = JSON.stringify({ agent_id: "comms", position: [1, 2, 3], status: "moving" });+ localStorage.setItem(otherKey, "other view");+ localStorage.setItem(authorityKey, journey);+ saveViewPreferences({ ...preferences, followAgentId: " comms ",+ pose: { ...pose, agentPosition: [1, 2, 3] }, agentPosition: [1, 2, 3], journey,+ } as ViewPreferences);+ expect(JSON.parse(localStorage.getItem(VIEW_KEY)!)).toEqual(saved);+ expect(readViewPreferences()).toEqual(preferences);+ expect(localStorage.getItem(otherKey)).toBe("other view");+ expect(localStorage.getItem(authorityKey)).toBe(journey);+ });++ it("also validates follow identity before saving", () => {+ saveViewPreferences({ ...preferences, followAgentId: "" });+ expect(readViewPreferences()).toEqual({ ...preferences, mode: "orbit", followAgentId: null });+ saveViewPreferences({ ...preferences, mode: "player" });+ expect(readViewPreferences()).toEqual({ ...preferences, mode: "player", followAgentId: null });+ });++ it("keeps controls usable when local storage is denied", () => {+ vi.stubGlobal("localStorage", {+ getItem() { throw new Error("storage denied"); },+ setItem() { throw new Error("storage denied"); },+ });+ expect(readViewPreferences()).toMatchObject({ mode: "overview", followAgentId: null, pose: null });+ expect(() => saveViewPreferences(preferences)).not.toThrow();+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/mars/viewPreferences.ts b/jarvis/ui/web/frontend/src/components/society/mars/viewPreferences.tsnew file mode 100644index 0000000000..21d31b8701--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/mars/viewPreferences.ts@@ -0,0 +1,64 @@+import { WORLD, WORLD_BOUNDS, type Vec3 } from "./world";++export const VIEWPOINTS = ["reference", "close_reference", "front", "rear", "left", "right", "top"] as const;+export type Viewpoint = typeof VIEWPOINTS[number];+export type CameraMode = "overview" | "outpost" | "orbit" | "player" | "follow";+export interface CameraPose { position: Vec3; target: Vec3 }+export interface ViewPreferences {+ mode: CameraMode;+ viewpoint: Viewpoint;+ neutral: boolean;+ shadows: boolean;+ pose: CameraPose | null;+ followAgentId: string | null;+}+const DEFAULTS: ViewPreferences = { mode: "overview", viewpoint: "reference", neutral: false, shadows: true, pose: null, followAgentId: null };+export const VIEW_KEY = `jarvis.${WORLD.world_id}.view.v${WORLD.layout_version}`;+export const VIEW_DIRECTIONS: Record<Viewpoint, Vec3> = {+ reference: [0.8, 0.9, 1], close_reference: [0.8, 0.9, 1], front: [0, 0.28, 1], rear: [0, 0.28, -1],+ left: [-1, 0.28, 0], right: [1, 0.28, 0], top: [0, 1, 0.04],+};++/** Client-owned view state never enters the authoritative task or journey records. */+export function parseViewPreferences(raw: string | null): ViewPreferences {+ try {+ const value = JSON.parse(raw ?? "null");+ if (!value || value.world_id !== WORLD.world_id || value.layout_version !== WORLD.layout_version+ || !["overview", "outpost", "orbit", "player", "follow"].includes(value.mode)+ || !VIEWPOINTS.includes(value.viewpoint) || typeof value.neutral !== "boolean") return { ...DEFAULTS };+ const vector = (v: unknown): v is Vec3 => Array.isArray(v) && v.length === 3+ && v.every((n) => typeof n === "number" && Number.isFinite(n) && Math.abs(n) <= 20000);+ const pose = value.pose;+ const validPose = pose && vector(pose.position) && vector(pose.target)+ && pose.target.every((n: number, axis: number) => n >= WORLD_BOUNDS.min[axis] && n <= WORLD_BOUNDS.max[axis])+ && Math.hypot(...pose.position.map((n: number, axis: number) => n - pose.target[axis])) >= 0.5;+ const identity = typeof value.followAgentId === "string" ? value.followAgentId.trim() : "";+ const followAgentId = value.mode === "follow" && identity.length > 0 && identity.length <= 128+ && !/[\u0000-\u001f\u007f-\u009f]/.test(value.followAgentId) ? identity : null;+ const mode: CameraMode = value.mode === "follow" && !followAgentId ? (validPose ? "orbit" : "overview")+ : value.mode === "orbit" && !validPose ? "overview" : value.mode;+ return { mode, viewpoint: value.viewpoint, neutral: value.neutral,+ shadows: typeof value.shadows === "boolean" ? value.shadows : true,+ pose: validPose ? { position: pose.position, target: pose.target } : null, followAgentId };+ } catch {+ // Corrupt or older client preferences must never prevent opening the world.+ return { ...DEFAULTS };+ }+}++export function readViewPreferences(): ViewPreferences {+ try { return parseViewPreferences(localStorage.getItem(VIEW_KEY)); }+ catch { return { ...DEFAULTS }; } // Storage denial only disables view restoration.+}++export function saveViewPreferences(value: ViewPreferences): void {+ try {+ const identity = { world_id: WORLD.world_id, layout_version: WORLD.layout_version };+ const preferences = parseViewPreferences(JSON.stringify({+ mode: value.mode, viewpoint: value.viewpoint, neutral: value.neutral, shadows: value.shadows,+ pose: value.pose, followAgentId: value.followAgentId, ...identity,+ }));+ localStorage.setItem(VIEW_KEY, JSON.stringify({ ...preferences, ...identity }));+ }+ catch { /* In-memory controls remain usable when client storage is unavailable. */ }+}diff --git a/jarvis/ui/web/frontend/src/components/society/mars/world.test.ts b/jarvis/ui/web/frontend/src/components/society/mars/world.test.tsnew file mode 100644index 0000000000..feedbdfc61--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/mars/world.test.ts@@ -0,0 +1,124 @@+import { describe, expect, it } from "vitest";+import { BUILDING_COLLIDERS, createTerrainGeometry, outpostBounds, outpostCloseBounds, PLAYER_SPAWN, projectRoad, ROADS, surfaceHeight, terrainHeight, WORLD } from "./world";+import { isPositionClear } from "./controller";+import outpostContract from "../../../../../../../../art/studies/mars-outpost-reference/source/geometry-contract.json";++describe("canonical Mars foundation", () => {+ it("crops only the distant bridge extension from close inspection, retaining the authored subject", () => {+ const complete = outpostBounds(), close = outpostCloseBounds();+ expect(close.min[0]).toBeGreaterThan(complete.min[0]);+ expect(close.min.slice(1)).toEqual(complete.min.slice(1));+ expect(close.max).toEqual(complete.max);+ const origin = outpostContract.world_translation;+ const plateau = outpostContract.colliders.find((collider) => collider.shape === "plateau")!;+ for (const [x, z] of [...plateau.footprint!, ...outpostContract.walk_surfaces.terrace.footprint]) {+ expect(x + origin[0]).toBeGreaterThanOrEqual(close.min[0]);+ expect(x + origin[0]).toBeLessThanOrEqual(close.max[0]);+ expect(z + origin[2]).toBeGreaterThanOrEqual(close.min[2]);+ expect(z + origin[2]).toBeLessThanOrEqual(close.max[2]);+ }+ for (const collider of BUILDING_COLLIDERS.filter((item) => item.id.startsWith("outpost:"))) {+ for (let axis = 0; axis < 3; axis++) {+ expect(collider.min[axis]).toBeGreaterThanOrEqual(close.min[axis]);+ expect(collider.max[axis]).toBeLessThanOrEqual(close.max[axis]);+ }+ }+ const landing = outpostContract.anchors.find((anchor) => anchor.id === "bridge-outpost-end")!;+ const remote = outpostContract.anchors.find((anchor) => anchor.id === "bridge-colony-end")!;+ expect(landing.position[0] + origin[0]).toBeGreaterThanOrEqual(close.min[0]);+ expect(remote.position[0] + origin[0]).toBeLessThan(close.min[0]);+ expect(outpostBounds()).toEqual(complete);+ });+ it("connects every declared navigation node to the Outpost without changed endpoint heights", () => {+ const visited = new Set(["outpost-arrival"]);+ for (let pass = 0; pass < WORLD.navigation.nodes.length; pass++) {+ for (const edge of WORLD.navigation.edges) {+ if (visited.has(edge.from)) visited.add(edge.to);+ if (visited.has(edge.to)) visited.add(edge.from);+ }+ }+ expect([...visited].sort()).toEqual(WORLD.navigation.nodes.map((node) => node.id).sort());+ for (const road of ROADS) {+ expect(projectRoad(road.start[0], road.start[2], road).height).toBe(road.start[1]);+ expect(projectRoad(road.end[0], road.end[2], road).height).toBe(road.end[1]);+ }+ });++ it("keeps server solid collision identical to the complete authored runtime collision", () => {+ const canonical = WORLD.navigation.collision.solid_boxes;+ const expected = BUILDING_COLLIDERS.filter((collider) => collider.id.startsWith("outpost:"));+ expect(canonical.map((box) => box.id).sort()).toEqual(expected.map((box) => box.id).sort());+ for (const collider of expected) {+ const projected = canonical.find((box) => box.id === collider.id)!;+ for (let axis = 0; axis < 3; axis++) {+ expect(projected.min[axis], `${collider.id}/min/${axis}`).toBeCloseTo(collider.min[axis], 10);+ expect(projected.max[axis], `${collider.id}/max/${axis}`).toBeCloseTo(collider.max[axis], 10);+ }+ }+ });++ it("keeps docks, boarding and both exits on the actual authored deck without creating new roads", () => {+ expect(ROADS.map((road) => road.id)).toEqual(WORLD.navigation.surface_edges.map((edge) => edge.id));+ expect(ROADS.some((road) => road.from.startsWith("rover-") || road.to.startsWith("rover-"))).toBe(false);+ const support = WORLD.navigation.collision.support_surfaces.find((row) => row.id === "outpost:route-05")!;+ const inside = (x: number, z: number) => support.polygon.every(([ax, az], i, polygon) => {+ const [bx, bz] = polygon[(i + 1) % polygon.length];+ return (bx - ax) * (z - az) - (bz - az) * (x - ax) >= -1e-7;+ });+ for (const dock of WORLD.navigation.rover_docks) {+ const ids = [dock.node_id, ...[dock.boarding_station_id, ...dock.exit_station_ids].map((id) => WORLD.navigation.destinations.find((row) => row.id === id)!.anchor)];+ for (const id of ids) {+ const [x, y, z] = WORLD.navigation.nodes.find((node) => node.id === id)!.position;+ expect(inside(x, z), id).toBe(true);+ const projectedHeight = support.plane[0] * x + support.plane[1] * z + support.plane[2];+ expect(projectedHeight, id).toBeCloseTo(58.006, 8);+ expect(surfaceHeight(x, z), id).toBeCloseTo(projectedHeight, 8);+ expect(Math.abs(y - projectedHeight), id).toBeLessThan(0.081);+ expect(isPositionClear([x, projectedHeight, z]), id).toBe(true);+ }+ }+ });++ it("keeps shared nodes within the authored/proxy deck seam tolerance", () => {+ for (const node of WORLD.navigation.nodes) {+ expect(Math.abs(surfaceHeight(node.position[0], node.position[2]) - node.position[1]), node.id).toBeLessThanOrEqual(0.081);+ }+ expect(surfaceHeight(294, 64)).toBe(58); // Finished operations floor.+ expect(surfaceHeight(365, 60)).toBeCloseTo(57.97, 5); // Authored terrace.+ });++ it("keeps rendered terrain below every road centre and avoids a raised endpoint cap", () => {+ for (const road of ROADS) {+ for (let step = 0; step <= 20; step++) {+ const t = step / 20;+ const x = road.start[0] + (road.end[0] - road.start[0]) * t;+ const z = road.start[2] + (road.end[2] - road.start[2]) * t;+ const y = road.start[1] + (road.end[1] - road.start[1]) * t;+ expect(terrainHeight(x, z), `${road.id}/${t}`).toBeLessThanOrEqual(y + 0.08);+ }+ }+ const bridge = ROADS.find((road) => road.id === "route-01")!;+ const t = 126 / 131;+ expect(surfaceHeight(251, 40 + 10 * t)).toBeCloseTo(48 + 10 * t, 5);+ expect(projectRoad(251, 40 + 10 * t, bridge).distance).toBeCloseTo(0);+ });++ it("provides a clear initial spawn and a genuine open doorway", () => {+ expect(isPositionClear(PLAYER_SPAWN)).toBe(true);+ expect(isPositionClear([294, 58.08, 71])).toBe(true);+ expect(isPositionClear([294, 58.08, 64])).toBe(true);+ expect(isPositionClear([290, 58.08, 71])).toBe(false);+ expect(BUILDING_COLLIDERS.some((collider) => collider.id === "outpost:operations-roof")).toBe(true);+ });++ it("rebuilds identical terrain including the entire original bounds", () => {+ const a = createTerrainGeometry(), b = createTerrainGeometry();+ expect(a.getAttribute("position").array).toEqual(b.getAttribute("position").array);+ expect(a.getIndex()!.count).toBeGreaterThan(170000);+ a.computeBoundingBox();+ expect(a.boundingBox!.min.y).toBe(-12);+ expect(a.boundingBox!.min.x).toBe(WORLD.bounds.min[0]);+ expect(a.boundingBox!.max.z).toBe(WORLD.bounds.max[2]);+ a.dispose(); b.dispose();+ });+});diff --git a/jarvis/ui/web/frontend/src/components/society/mars/world.ts b/jarvis/ui/web/frontend/src/components/society/mars/world.tsnew file mode 100644index 0000000000..f1360aefbe--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/mars/world.ts@@ -0,0 +1,253 @@+/** New Mars geometry and collision projection; no legacy island state is consumed. */+import { BufferGeometry, Float32BufferAttribute, Color } from "three";+import definition from "./worldDefinition.json";+import outpostContract from "../../../../../../../../art/studies/mars-outpost-reference/source/geometry-contract.json";+import outpostExport from "../../../../../../../../art/studies/mars-outpost-reference/source/export-report.json";++export type Vec3 = [number, number, number];+export interface Bounds { min: Vec3; max: Vec3 }+export interface Collider extends Bounds { id: string }+export const WORLD = definition;+export const WORLD_BOUNDS: Bounds = {+ min: [...WORLD.bounds.min] as Vec3,+ max: [...WORLD.bounds.max] as Vec3,+};+export const OUTPOST = WORLD.districts.find((d) => d.id === "communications-outpost")!;+const OUTPOST_ORIGIN = outpostContract.world_translation;+const WALK_SURFACES = outpostContract.walk_surfaces;+const nodes = new Map(WORLD.navigation.nodes.map((node) => [node.id, node]));+// Logical docking/shoulder segments do not redraw or regrade authored roads.+export const ROADS = WORLD.navigation.surface_edges.map((edge) => ({+ ...edge,+ start: [...nodes.get(edge.from)!.position] as Vec3,+ end: [...nodes.get(edge.to)!.position] as Vec3,+}));+export type Road = (typeof ROADS)[number];++const smooth = (value: number) => {+ const t = Math.max(0, Math.min(1, value));+ return t * t * (3 - 2 * t);+};++export function projectRoad(x: number, z: number, road: Road) {+ const dx = road.end[0] - road.start[0];+ const dz = road.end[2] - road.start[2];+ const along = ((x - road.start[0]) * dx + (z - road.start[2]) * dz) / (dx * dx + dz * dz);+ const t = Math.max(0, Math.min(1, along));+ return {+ t, along,+ distance: Math.hypot(x - road.start[0] - dx * t, z - road.start[2] - dz * t),+ height: road.start[1] + (road.end[1] - road.start[1]) * t,+ };+}++/** Authored plateaus over a continuous deterministic height field. */+function designHeight(x: number, z: number): number {+ let height = -3 + 3.5 * Math.sin(x * 0.016) * Math.cos(z * 0.012)+ + 1.2 * Math.sin(x * 0.051 + z * 0.029);+ for (const district of WORLD.districts) {+ // The finished reference owns its own cliff shell. A coarse terrain mound+ // here would bury the modeled rear/side faces inside the blockout.+ if (district.id === "communications-outpost") continue;+ const dx = Math.abs(x - district.center[0]);+ const dz = Math.abs(z - district.center[2]);+ // A level central pad with irregular, fully modeled surrounding escarpments.+ const outside = Math.max(dx - district.size[0] / 2, dz - district.size[1] / 2);+ const skirt = 30 + 6 * Math.sin(x * 0.04 + z * 0.03);+ const weight = 1 - smooth(outside / skirt);+ height = Math.max(height, -6 + (district.center[1] + 6) * weight);+ }+ let nearest = Infinity;+ let roadHeight = height;+ let weight = 0;+ for (const road of ROADS) {+ if (road.kind === "bridge" || road.kind === "interior"+ || road.from.startsWith("outpost-") || road.to.startsWith("outpost-")) continue;+ const projection = projectRoad(x, z, road);+ const distance = Math.max(0, projection.distance - road.width / 2);+ if (distance < nearest && distance < 9) {+ nearest = distance;+ roadHeight = projection.height;+ weight = 1 - smooth(distance / 9);+ }+ }+ height += (roadHeight - height) * weight;+ // A coarse triangle adjacent to a graded corridor must not poke through its+ // deck. Cut only excess terrain, including bridge abutments; never raise the+ // ravine under a bridge. The margin covers this field's 5 m cells.+ for (const road of ROADS) {+ if (road.kind === "interior") continue;+ const projection = projectRoad(x, z, road);+ if (projection.distance <= road.width / 2 + 7.5) height = Math.min(height, projection.height - 0.2);+ }+ return height;+}++// This grid is both the rendered terrain and the exact triangle collision field.+const CELLS_X = 174;+const CELLS_Z = 164;+const DX = (WORLD_BOUNDS.max[0] - WORLD_BOUNDS.min[0]) / CELLS_X;+const DZ = (WORLD_BOUNDS.max[2] - WORLD_BOUNDS.min[2]) / CELLS_Z;+const heights = new Float32Array((CELLS_X + 1) * (CELLS_Z + 1));+for (let iz = 0; iz <= CELLS_Z; iz++) {+ for (let ix = 0; ix <= CELLS_X; ix++) {+ heights[iz * (CELLS_X + 1) + ix] = designHeight(WORLD_BOUNDS.min[0] + ix * DX, WORLD_BOUNDS.min[2] + iz * DZ);+ }+}++export function terrainHeight(x: number, z: number): number {+ const gx = Math.max(0, Math.min(CELLS_X - 0.000001, (x - WORLD_BOUNDS.min[0]) / DX));+ const gz = Math.max(0, Math.min(CELLS_Z - 0.000001, (z - WORLD_BOUNDS.min[2]) / DZ));+ const ix = Math.floor(gx), iz = Math.floor(gz), u = gx - ix, v = gz - iz;+ const index = iz * (CELLS_X + 1) + ix;+ const a = heights[index], b = heights[index + 1];+ const c = heights[index + CELLS_X + 1], d = heights[index + CELLS_X + 2];+ return u + v <= 1 ? a + (b - a) * u + (c - a) * v : d + (c - d) * (1 - u) + (b - d) * (1 - v);+}++/** Solid terrain and the cliff do not fill the empty space below bridge decks. */+export function cameraGroundHeight(x: number, z: number): number {+ const plateau = outpostContract.colliders.find((collider) => collider.shape === "plateau");+ const polygon = plateau?.footprint;+ let inside = false;+ const localX = x - OUTPOST_ORIGIN[0], localZ = z - OUTPOST_ORIGIN[2];+ if (polygon) for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {+ const [xi, zi] = polygon[i], [xj, zj] = polygon[j];+ if ((zi > localZ) !== (zj > localZ) && localX < (xj - xi) * (localZ - zi) / (zj - zi) + xi) inside = !inside;+ }+ return Math.max(terrainHeight(x, z), inside ? OUTPOST_ORIGIN[1] + (plateau?.top_y ?? 0) : -Infinity);+}++/** Walkable decks also support the player, but do not fill the space under a bridge. */+export function surfaceHeight(x: number, z: number): number {+ let height = terrainHeight(x, z), nearest = Infinity;+ const localX = x - OUTPOST_ORIGIN[0], localZ = z - OUTPOST_ORIGIN[2];+ const insideFootprint = (footprint: number[][]) => {+ let inside = false;+ for (let i = 0, j = footprint.length - 1; i < footprint.length; j = i++) {+ const [xi, zi] = footprint[i], [xj, zj] = footprint[j];+ if ((zi > localZ) !== (zj > localZ)+ && localX < (xj - xi) * (localZ - zi) / (zj - zi) + xi) inside = !inside;+ }+ return inside;+ };+ const plateau = outpostContract.colliders.find((collider) => collider.shape === "plateau");+ const footprint = plateau?.footprint;+ if (footprint && insideFootprint(footprint)) height = OUTPOST_ORIGIN[1] + (plateau.top_y ?? 0);+ if (insideFootprint(WALK_SURFACES.terrace.footprint)) height = OUTPOST_ORIGIN[1] + WALK_SURFACES.terrace.top_y;+ const operations = WORLD.buildings.find((building) => building.id === "operations")!;+ const [ox, , oz] = operations.position, [ow, , od] = operations.size;+ if (Math.abs(x - ox) <= ow / 2 && Math.abs(z - oz) <= od / 2) {+ const [min, max] = WALK_SURFACES.operations.finished_floor_xz_bounds;+ const finished = localX >= min[0] && localX <= max[0] && localZ >= min[1] && localZ <= max[1];+ height = OUTPOST_ORIGIN[1] + (finished ? WALK_SURFACES.operations.finished_floor_top_y : WALK_SURFACES.operations.structural_slab_top_y);+ }+ for (const road of ROADS) {+ // The entry is terrace followed by the authored interior floor, not a+ // separate raised deck. Preserve its graph edge without inventing a surface.+ if (road.id === "route-04") continue;+ const projection = projectRoad(x, z, road);+ // Collision uses the same rectangular deck as RoadMesh, not a rounded+ // endpoint capsule that creates a step before two sloped routes meet.+ if (projection.along >= -1e-7 && projection.along <= 1 + 1e-7+ && projection.distance <= road.width / 2 && projection.distance < nearest) {+ nearest = projection.distance;+ const authored = WALK_SURFACES[road.id as keyof typeof WALK_SURFACES];+ const offset = typeof authored === "object" && "node_height_offset" in authored ? authored.node_height_offset : 0.08;+ height = projection.height + offset;+ }+ }+ return height;+}++export function createTerrainGeometry(): BufferGeometry {+ const positions: number[] = [], colors: number[] = [], indices: number[] = [];+ const dark = new Color("#694336"), light = new Color("#ad7954");+ const color = new Color();+ for (let iz = 0; iz <= CELLS_Z; iz++) {+ for (let ix = 0; ix <= CELLS_X; ix++) {+ const x = WORLD_BOUNDS.min[0] + ix * DX, z = WORLD_BOUNDS.min[2] + iz * DZ;+ const height = heights[iz * (CELLS_X + 1) + ix];+ positions.push(x, height, z);+ color.copy(dark).lerp(light, Math.max(0, Math.min(1, 0.4 + height / 160 + 0.12 * Math.sin(x * 0.08 + z * 0.09))));+ colors.push(color.r, color.g, color.b);+ if (ix < CELLS_X && iz < CELLS_Z) {+ const a = iz * (CELLS_X + 1) + ix, b = a + 1, c = a + CELLS_X + 1, d = c + 1;+ indices.push(a, c, b, b, c, d);+ }+ }+ }+ // Close the four sides down to the base: rear and side inspection never reveals a sheet.+ const perimeter: number[] = [];+ for (let ix = 0; ix <= CELLS_X; ix++) perimeter.push(ix);+ for (let iz = 1; iz <= CELLS_Z; iz++) perimeter.push(iz * (CELLS_X + 1) + CELLS_X);+ for (let ix = CELLS_X - 1; ix >= 0; ix--) perimeter.push(CELLS_Z * (CELLS_X + 1) + ix);+ for (let iz = CELLS_Z - 1; iz > 0; iz--) perimeter.push(iz * (CELLS_X + 1));+ for (let i = 0; i < perimeter.length; i++) {+ const a = perimeter[i], b = perimeter[(i + 1) % perimeter.length], bottom = positions.length / 3;+ positions.push(positions[a * 3], -12, positions[a * 3 + 2], positions[b * 3], -12, positions[b * 3 + 2]);+ colors.push(dark.r, dark.g, dark.b, dark.r, dark.g, dark.b);+ indices.push(a, b, bottom, b, bottom + 1, bottom);+ }+ const geometry = new BufferGeometry();+ geometry.setAttribute("position", new Float32BufferAttribute(positions, 3));+ geometry.setAttribute("color", new Float32BufferAttribute(colors, 3));+ geometry.setIndex(indices);+ geometry.computeVertexNormals();+ geometry.computeBoundingSphere();+ return geometry;+}++export function box(id: string, x: number, y: number, z: number, width: number, height: number, depth: number): Collider {+ return { id, min: [x - width / 2, y, z - depth / 2], max: [x + width / 2, y + height, z + depth / 2] };+}++/** A real simple entrance is reserved in the operations blockout; final art is pending. */+export const BUILDING_COLLIDERS: Collider[] = WORLD.buildings.flatMap((building) => {+ if (building.district_id === "communications-outpost") return [];+ const [x, y, z] = building.position, [w, h, d] = building.size;+ if (building.id !== "operations") return [box(building.id, x, y, z, w, h, d)];+ const door = 3.6, wall = 0.45, side = (w - door) / 2;+ return [+ box("operations-west", x - w / 2, y, z, wall, h, d),+ box("operations-east", x + w / 2, y, z, wall, h, d),+ box("operations-north", x, y, z - d / 2, w, h, wall),+ box("operations-front-left", x - door / 2 - side / 2, y, z + d / 2, side, h, wall),+ box("operations-front-right", x + door / 2 + side / 2, y, z + d / 2, side, h, wall),+ box("operations-lintel", x, y + 3.4, z + d / 2, door, h - 3.4, wall),+ box("operations-roof", x, y + h, z, w, wall, d),+ ];+}).concat(outpostContract.colliders.flatMap((collider) => {+ if (collider.shape !== "box" || !collider.center || !collider.size) return [];+ const [x, y, z] = collider.center, [w, h, d] = collider.size;+ return [box("outpost:" + collider.id, x + OUTPOST_ORIGIN[0], y + OUTPOST_ORIGIN[1] - h / 2, z + OUTPOST_ORIGIN[2], w, h, d)];+}));++export const PLAYER_SPAWN: Vec3 = [WORLD.spawn.position[0], surfaceHeight(WORLD.spawn.position[0], WORLD.spawn.position[2]), WORLD.spawn.position[2]];++export function outpostBounds(): Bounds {+ // Include the authored bridge/supports and complete cliff, not just the+ // proposed plateau envelope. Independent review presets must fit every side.+ const translation = outpostExport.world_translation;+ return {+ min: outpostExport.local_runtime_bounds.min.map((n, i) => n + translation[i]) as Vec3,+ max: outpostExport.local_runtime_bounds.max.map((n, i) => n + translation[i]) as Vec3,+ };+}++/** Close inspection excludes the western bridge extension, not the cliff or mast. */+export function outpostCloseBounds(): Bounds {+ const bounds = outpostBounds();+ const plateau = outpostContract.colliders.find((collider) => collider.shape === "plateau");+ const landing = outpostContract.anchors.find((anchor) => anchor.id === "bridge-outpost-end");+ if (!plateau?.footprint || !landing) return bounds;+ // Keep the bridge landing, every platform edge and every Outpost solid.+ // The export's other five planes retain complete cliff and landmark coverage.+ bounds.min[0] = Math.min(+ ...plateau.footprint.map(([x]) => x + OUTPOST_ORIGIN[0]),+ ...WALK_SURFACES.terrace.footprint.map(([x]) => x + OUTPOST_ORIGIN[0]),+ ...BUILDING_COLLIDERS.filter((collider) => collider.id.startsWith("outpost:")).map((collider) => collider.min[0]),+ landing.position[0] + OUTPOST_ORIGIN[0],+ );+ return bounds;+}diff --git a/jarvis/ui/web/frontend/src/components/society/mars/worldDefinition.json b/jarvis/ui/web/frontend/src/components/society/mars/worldDefinition.jsonnew file mode 100644index 0000000000..ea5b6d6a9e--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/mars/worldDefinition.json@@ -0,0 +1,3370 @@+{+ "schema_version": 1,+ "world_id": "mars:ordinary",+ "layout_version": 1,+ "seed": 6901,+ "units": "metres",+ "axes": {+ "up": "+Y",+ "east": "+X",+ "north": "-Z"+ },+ "reference_id": "ref-layout",+ "status": "blockout",+ "bounds": {+ "min": [+ -430,+ -12,+ -400+ ],+ "max": [+ 435,+ 180,+ 410+ ]+ },+ "districts": [+ {+ "id": "central",+ "name": "Central district",+ "center": [+ 0,+ 48,+ 0+ ],+ "size": [+ 250,+ 210+ ],+ "landmark_height": 35,+ "stage": "blockout",+ "terrain": "plateau",+ "access": "exterior",+ "asset": null+ },+ {+ "id": "foundry",+ "name": "Agent Foundry",+ "center": [+ -30,+ 92,+ -290+ ],+ "size": [+ 145,+ 135+ ],+ "landmark_height": 82,+ "stage": "blockout",+ "terrain": "plateau",+ "access": "exterior",+ "asset": null+ },+ {+ "id": "mine",+ "name": "The Mine",+ "center": [+ 150,+ 80,+ -260+ ],+ "size": [+ 155,+ 155+ ],+ "landmark_height": 20,+ "stage": "blockout",+ "terrain": "plateau",+ "access": "exterior",+ "asset": null+ },+ {+ "id": "workshop",+ "name": "Workshop",+ "center": [+ -230,+ 66,+ -170+ ],+ "size": [+ 130,+ 115+ ],+ "landmark_height": 24,+ "stage": "blockout",+ "terrain": "plateau",+ "access": "exterior",+ "asset": null+ },+ {+ "id": "water-extraction",+ "name": "Water Extraction",+ "center": [+ -320,+ 42,+ -10+ ],+ "size": [+ 130,+ 150+ ],+ "landmark_height": 22,+ "stage": "blockout",+ "terrain": "plateau",+ "access": "exterior",+ "asset": null+ },+ {+ "id": "memory-house",+ "name": "Memory House",+ "center": [+ 240,+ 70,+ -160+ ],+ "size": [+ 105,+ 100+ ],+ "landmark_height": 23,+ "stage": "blockout",+ "terrain": "plateau",+ "access": "exterior",+ "asset": null+ },+ {+ "id": "harbor-gate",+ "name": "Harbor Gate",+ "center": [+ -230,+ 25,+ 240+ ],+ "size": [+ 180,+ 145+ ],+ "landmark_height": 65,+ "stage": "blockout",+ "terrain": "plateau",+ "access": "exterior",+ "asset": null+ },+ {+ "id": "gardens",+ "name": "Gardens",+ "center": [+ 80,+ 36,+ 300+ ],+ "size": [+ 210,+ 125+ ],+ "landmark_height": 20,+ "stage": "blockout",+ "terrain": "plateau",+ "access": "exterior",+ "asset": null+ },+ {+ "id": "solar-field",+ "name": "Solar Field",+ "center": [+ -25,+ 58,+ -175+ ],+ "size": [+ 170,+ 85+ ],+ "landmark_height": 5,+ "stage": "blockout",+ "terrain": "plateau",+ "access": "exterior",+ "asset": null+ },+ {+ "id": "communications-outpost",+ "name": "Communications Outpost",+ "center": [+ 320,+ 58,+ 50+ ],+ "size": [+ 120,+ 95+ ],+ "landmark_height": 62,+ "stage": "blockout",+ "terrain": "plateau",+ "access": "exterior",+ "asset": null+ }+ ],+ "buildings": [+ {+ "id": "jarvis-hub",+ "name": "Jarvis Hub",+ "district_id": "central",+ "position": [+ 0,+ 48,+ 0+ ],+ "size": [+ 36,+ 30,+ 36+ ],+ "checkpoint": "meeting",+ "stage": "blockout",+ "access": "planned-exterior",+ "asset": null+ },+ {+ "id": "terminal",+ "name": "Terminal",+ "district_id": "central",+ "position": [+ -64,+ 48,+ -34+ ],+ "size": [+ 36,+ 12,+ 18+ ],+ "checkpoint": "hub:cli",+ "stage": "blockout",+ "access": "planned-exterior",+ "asset": null+ },+ {+ "id": "plugin-docks",+ "name": "Plugin Docks",+ "district_id": "central",+ "position": [+ 64,+ 48,+ -34+ ],+ "size": [+ 36,+ 12,+ 18+ ],+ "checkpoint": "hub:plugins",+ "stage": "blockout",+ "access": "planned-exterior",+ "asset": null+ },+ {+ "id": "control-room",+ "name": "Control Room",+ "district_id": "central",+ "position": [+ -72,+ 48,+ 10+ ],+ "size": [+ 24,+ 10,+ 18+ ],+ "checkpoint": "hub:desktop",+ "stage": "blockout",+ "access": "planned-exterior",+ "asset": null+ },+ {+ "id": "skill-forge",+ "name": "Skill Forge",+ "district_id": "central",+ "position": [+ 72,+ 48,+ 10+ ],+ "size": [+ 24,+ 10,+ 18+ ],+ "checkpoint": "hub:skills",+ "stage": "blockout",+ "access": "planned-exterior",+ "asset": null+ },+ {+ "id": "signal-office",+ "name": "Signal Office",+ "district_id": "central",+ "position": [+ -45,+ 48,+ 61+ ],+ "size": [+ 24,+ 10,+ 18+ ],+ "checkpoint": "hub:comms",+ "stage": "blockout",+ "access": "planned-exterior",+ "asset": null+ },+ {+ "id": "gallery",+ "name": "Gallery",+ "district_id": "central",+ "position": [+ 45,+ 48,+ 61+ ],+ "size": [+ 24,+ 10,+ 18+ ],+ "checkpoint": "gallery",+ "stage": "blockout",+ "access": "planned-exterior",+ "asset": null+ },+ {+ "id": "boiler-house",+ "name": "Boiler House",+ "district_id": "central",+ "position": [+ 0,+ 48,+ -76+ ],+ "size": [+ 36,+ 18,+ 24+ ],+ "checkpoint": "hub:models",+ "stage": "blockout",+ "access": "planned-exterior",+ "asset": null+ },+ {+ "id": "lookout",+ "name": "The Lookout",+ "district_id": "central",+ "position": [+ 0,+ 48,+ 85+ ],+ "size": [+ 24,+ 14,+ 24+ ],+ "checkpoint": "idle",+ "stage": "blockout",+ "access": "planned-exterior",+ "asset": null+ },+ {+ "id": "communications-mast",+ "name": "Communications mast",+ "district_id": "communications-outpost",+ "position": [+ 320,+ 58,+ 46+ ],+ "size": [+ 14,+ 62,+ 14+ ],+ "checkpoint": null,+ "stage": "blockout",+ "access": "exterior-only",+ "asset": null+ },+ {+ "id": "operations",+ "name": "Outpost operations",+ "district_id": "communications-outpost",+ "position": [+ 294,+ 58,+ 64+ ],+ "size": [+ 20,+ 8,+ 14+ ],+ "checkpoint": "hub:comms",+ "stage": "blockout",+ "access": "required-interior",+ "asset": null+ },+ {+ "id": "radome-north",+ "name": "North radome",+ "district_id": "communications-outpost",+ "position": [+ 298,+ 58,+ 21+ ],+ "size": [+ 18,+ 17,+ 18+ ],+ "checkpoint": null,+ "stage": "blockout",+ "access": "exterior-only",+ "asset": null+ },+ {+ "id": "radome-south",+ "name": "South radome",+ "district_id": "communications-outpost",+ "position": [+ 351,+ 58,+ 69+ ],+ "size": [+ 22,+ 18,+ 22+ ],+ "checkpoint": null,+ "stage": "blockout",+ "access": "exterior-only",+ "asset": null+ },+ {+ "id": "dish-west",+ "name": "Western dish",+ "district_id": "communications-outpost",+ "position": [+ 278,+ 58,+ 46+ ],+ "size": [+ 21,+ 24,+ 21+ ],+ "checkpoint": null,+ "stage": "blockout",+ "access": "exterior-only",+ "asset": null+ },+ {+ "id": "dish-east",+ "name": "Eastern dish",+ "district_id": "communications-outpost",+ "position": [+ 351,+ 58,+ 21+ ],+ "size": [+ 25,+ 29,+ 25+ ],+ "checkpoint": null,+ "stage": "blockout",+ "access": "exterior-only",+ "asset": null+ },+ {+ "id": "service-east",+ "name": "Outpost service building",+ "district_id": "communications-outpost",+ "position": [+ 363,+ 58,+ 45+ ],+ "size": [+ 12,+ 12,+ 12+ ],+ "checkpoint": null,+ "stage": "blockout",+ "access": "planned-exterior",+ "asset": null+ }+ ],+ "navigation": {+ "version": 1,+ "nodes": [+ {+ "id": "hub-east",+ "position": [+ 125,+ 48,+ 40+ ]+ },+ {+ "id": "outpost-west",+ "position": [+ 256,+ 58,+ 50+ ]+ },+ {+ "id": "outpost-arrival",+ "position": [+ 268,+ 58,+ 68+ ],+ "resource_ids": [+ "corridor:route05-lead"+ ]+ },+ {+ "id": "console-approach",+ "position": [+ 294,+ 58,+ 75+ ]+ },+ {+ "id": "console",+ "position": [+ 294,+ 58,+ 64+ ]+ },+ {+ "id": "outpost-south",+ "position": [+ 325,+ 58,+ 96+ ],+ "resource_ids": [+ "corridor:route05-tail"+ ]+ },+ {+ "id": "gardens-east",+ "position": [+ 185,+ 36,+ 300+ ]+ },+ {+ "id": "hub-south",+ "position": [+ 0,+ 48,+ 109+ ]+ },+ {+ "id": "gardens-north",+ "position": [+ 80,+ 36,+ 234+ ]+ },+ {+ "id": "harbor-east",+ "position": [+ -137,+ 25,+ 240+ ]+ },+ {+ "id": "hub-west",+ "position": [+ -128,+ 48,+ 20+ ]+ },+ {+ "id": "water-east",+ "position": [+ -251,+ 42,+ -10+ ]+ },+ {+ "id": "workshop-south",+ "position": [+ -230,+ 66,+ -111+ ]+ },+ {+ "id": "hub-north",+ "position": [+ 0,+ 48,+ -110+ ]+ },+ {+ "id": "solar-south",+ "position": [+ -25,+ 58,+ -129+ ]+ },+ {+ "id": "foundry-south",+ "position": [+ -30,+ 92,+ -220+ ]+ },+ {+ "id": "mine-south",+ "position": [+ 150,+ 80,+ -180+ ]+ },+ {+ "id": "memory-west",+ "position": [+ 185,+ 70,+ -160+ ]+ },+ {+ "id": "central-northwest",+ "position": [+ -128,+ 48,+ -110+ ]+ },+ {+ "id": "central-northeast",+ "position": [+ 125,+ 48,+ -110+ ]+ },+ {+ "id": "central-southeast",+ "position": [+ 125,+ 48,+ 109+ ]+ },+ {+ "id": "central-southwest",+ "position": [+ -128,+ 48,+ 109+ ]+ },+ {+ "id": "rover-a-dock",+ "position": [+ 285.1,+ 58,+ 76.4+ ],+ "resource_ids": [+ "clearance:rover-a"+ ]+ },+ {+ "id": "rover-a-board",+ "position": [+ 283.05767024317663,+ 58,+ 78.51633862233665+ ]+ },+ {+ "id": "rover-a-exit",+ "position": [+ 284.673268030764,+ 58,+ 79.30996560571289+ ]+ },+ {+ "id": "rover-a-alternate",+ "position": [+ 286.3345308630297,+ 58,+ 73.88684788597524+ ],+ "resource_ids": [+ "corridor:route05-lead"+ ]+ },+ {+ "id": "rover-a-shoulder",+ "position": [+ 279.37769750478327,+ 58,+ 76.70863271575743+ ]+ },+ {+ "id": "rover-a-alternate-shoulder",+ "position": [+ 281.8467592308427,+ 58,+ 71.6823284877079+ ],+ "resource_ids": [+ "corridor:route05-lead"+ ]+ },+ {+ "id": "rover-b-dock",+ "position": [+ 313.6,+ 58,+ 90.4+ ],+ "resource_ids": [+ "clearance:rover-b"+ ]+ },+ {+ "id": "rover-b-board",+ "position": [+ 311.55767024317663,+ 58,+ 92.51633862233665+ ]+ },+ {+ "id": "rover-b-exit",+ "position": [+ 313.173268030764,+ 58,+ 93.30996560571289+ ]+ },+ {+ "id": "rover-b-alternate",+ "position": [+ 314.8345308630297,+ 58,+ 87.88684788597524+ ]+ },+ {+ "id": "rover-b-shoulder",+ "position": [+ 316.85324076915737,+ 58,+ 95.1176715122921+ ]+ },+ {+ "id": "rover-b-alternate-shoulder",+ "position": [+ 319.3223024952168,+ 58,+ 90.09136728424258+ ]+ }+ ],+ "edges": [+ {+ "id": "route-01",+ "from": "hub-east",+ "to": "outpost-west",+ "width": 10,+ "kind": "bridge",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-02",+ "from": "outpost-west",+ "to": "outpost-arrival",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-03",+ "from": "outpost-arrival",+ "to": "console-approach",+ "width": 4,+ "kind": "footpath",+ "modes": [+ "pedestrian"+ ],+ "stage": "blockout",+ "resource_ids": [+ "corridor:route05-lead"+ ]+ },+ {+ "id": "route-04",+ "from": "console-approach",+ "to": "console",+ "width": 2.4,+ "kind": "interior",+ "modes": [+ "pedestrian"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-06",+ "from": "outpost-south",+ "to": "gardens-east",+ "width": 10,+ "kind": "bridge",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-07",+ "from": "hub-south",+ "to": "gardens-north",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-08",+ "from": "gardens-north",+ "to": "gardens-east",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-09",+ "from": "harbor-east",+ "to": "gardens-north",+ "width": 10,+ "kind": "bridge",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-10",+ "from": "hub-west",+ "to": "water-east",+ "width": 10,+ "kind": "bridge",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-11",+ "from": "hub-west",+ "to": "workshop-south",+ "width": 10,+ "kind": "bridge",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-12",+ "from": "hub-north",+ "to": "solar-south",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-13",+ "from": "solar-south",+ "to": "foundry-south",+ "width": 10,+ "kind": "bridge",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-14",+ "from": "foundry-south",+ "to": "mine-south",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-15",+ "from": "hub-east",+ "to": "memory-west",+ "width": 10,+ "kind": "bridge",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-16",+ "from": "memory-west",+ "to": "mine-south",+ "width": 10,+ "kind": "bridge",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-17",+ "from": "hub-west",+ "to": "harbor-east",+ "width": 10,+ "kind": "bridge",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-18",+ "from": "hub-west",+ "to": "central-northwest",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-19",+ "from": "hub-north",+ "to": "central-northeast",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-20",+ "from": "hub-east",+ "to": "central-southeast",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-21",+ "from": "hub-south",+ "to": "central-southwest",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-22",+ "from": "central-northwest",+ "to": "hub-north",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-23",+ "from": "central-northeast",+ "to": "hub-east",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-24",+ "from": "central-southeast",+ "to": "hub-south",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-25",+ "from": "central-southwest",+ "to": "hub-west",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "rover-a-access-1",+ "from": "outpost-arrival",+ "to": "rover-a-shoulder",+ "width": 1.2,+ "kind": "footpath",+ "modes": [+ "pedestrian"+ ],+ "stage": "blockout",+ "surface_id": "route-05",+ "render": false,+ "resource_ids": [+ "corridor:route05-lead"+ ]+ },+ {+ "id": "rover-a-access-2",+ "from": "rover-a-shoulder",+ "to": "rover-a-board",+ "width": 1.2,+ "kind": "footpath",+ "modes": [+ "pedestrian"+ ],+ "stage": "blockout",+ "surface_id": "route-05",+ "render": false+ },+ {+ "id": "rover-a-access-3",+ "from": "rover-a-board",+ "to": "rover-a-exit",+ "width": 1.2,+ "kind": "footpath",+ "modes": [+ "pedestrian"+ ],+ "stage": "blockout",+ "surface_id": "route-05",+ "render": false+ },+ {+ "id": "rover-a-access-4",+ "from": "outpost-arrival",+ "to": "rover-a-alternate-shoulder",+ "width": 1.2,+ "kind": "footpath",+ "modes": [+ "pedestrian"+ ],+ "stage": "blockout",+ "surface_id": "route-05",+ "render": false,+ "resource_ids": [+ "corridor:route05-lead"+ ]+ },+ {+ "id": "rover-a-access-5",+ "from": "rover-a-alternate-shoulder",+ "to": "rover-a-alternate",+ "width": 1.2,+ "kind": "footpath",+ "modes": [+ "pedestrian"+ ],+ "stage": "blockout",+ "surface_id": "route-05",+ "render": false,+ "resource_ids": [+ "corridor:route05-lead"+ ]+ },+ {+ "id": "rover-b-access-1",+ "from": "outpost-south",+ "to": "rover-b-shoulder",+ "width": 1.2,+ "kind": "footpath",+ "modes": [+ "pedestrian"+ ],+ "stage": "blockout",+ "surface_id": "route-05",+ "render": false,+ "resource_ids": [+ "corridor:route05-tail"+ ]+ },+ {+ "id": "rover-b-access-2",+ "from": "rover-b-shoulder",+ "to": "rover-b-exit",+ "width": 1.2,+ "kind": "footpath",+ "modes": [+ "pedestrian"+ ],+ "stage": "blockout",+ "surface_id": "route-05",+ "render": false+ },+ {+ "id": "rover-b-access-3",+ "from": "rover-b-board",+ "to": "rover-b-exit",+ "width": 1.2,+ "kind": "footpath",+ "modes": [+ "pedestrian"+ ],+ "stage": "blockout",+ "surface_id": "route-05",+ "render": false+ },+ {+ "id": "rover-b-access-4",+ "from": "outpost-south",+ "to": "rover-b-alternate-shoulder",+ "width": 1.2,+ "kind": "footpath",+ "modes": [+ "pedestrian"+ ],+ "stage": "blockout",+ "surface_id": "route-05",+ "render": false,+ "resource_ids": [+ "corridor:route05-tail"+ ]+ },+ {+ "id": "rover-b-access-5",+ "from": "rover-b-alternate-shoulder",+ "to": "rover-b-alternate",+ "width": 1.2,+ "kind": "footpath",+ "modes": [+ "pedestrian"+ ],+ "stage": "blockout",+ "surface_id": "route-05",+ "render": false+ },+ {+ "id": "route-05-lead",+ "from": "outpost-arrival",+ "to": "rover-a-dock",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout",+ "surface_id": "route-05",+ "resource_ids": [+ "corridor:route05-lead",+ "clearance:rover-a"+ ]+ },+ {+ "id": "route-05-ride",+ "from": "rover-a-dock",+ "to": "rover-b-dock",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout",+ "surface_id": "route-05",+ "resource_ids": [+ "clearance:rover-a",+ "clearance:rover-b"+ ]+ },+ {+ "id": "route-05-tail",+ "from": "rover-b-dock",+ "to": "outpost-south",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout",+ "surface_id": "route-05",+ "resource_ids": [+ "corridor:route05-tail",+ "clearance:rover-b"+ ]+ }+ ],+ "destinations": [+ {+ "id": "outpost-approach",+ "name": "Outpost approach",+ "anchor": "console-approach",+ "capacity": 1+ },+ {+ "id": "outpost-bridge-staging",+ "name": "Outpost bridge staging",+ "anchor": "outpost-west",+ "capacity": 1+ },+ {+ "id": "rover-a-board",+ "name": "Rover A board",+ "anchor": "rover-a-board",+ "capacity": 1+ },+ {+ "id": "rover-a-exit",+ "name": "Rover A exit",+ "anchor": "rover-a-exit",+ "capacity": 1+ },+ {+ "id": "rover-a-alternate",+ "name": "Rover A alternate",+ "anchor": "rover-a-alternate",+ "capacity": 1+ },+ {+ "id": "rover-b-board",+ "name": "Rover B board",+ "anchor": "rover-b-board",+ "capacity": 1+ },+ {+ "id": "rover-b-exit",+ "name": "Rover B exit",+ "anchor": "rover-b-exit",+ "capacity": 1+ },+ {+ "id": "rover-b-alternate",+ "name": "Rover B alternate",+ "anchor": "rover-b-alternate",+ "capacity": 1+ }+ ],+ "surface_edges": [+ {+ "id": "route-01",+ "from": "hub-east",+ "to": "outpost-west",+ "width": 10,+ "kind": "bridge",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-02",+ "from": "outpost-west",+ "to": "outpost-arrival",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-03",+ "from": "outpost-arrival",+ "to": "console-approach",+ "width": 4,+ "kind": "footpath",+ "modes": [+ "pedestrian"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-04",+ "from": "console-approach",+ "to": "console",+ "width": 2.4,+ "kind": "interior",+ "modes": [+ "pedestrian"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-05",+ "from": "outpost-arrival",+ "to": "outpost-south",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-06",+ "from": "outpost-south",+ "to": "gardens-east",+ "width": 10,+ "kind": "bridge",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-07",+ "from": "hub-south",+ "to": "gardens-north",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-08",+ "from": "gardens-north",+ "to": "gardens-east",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-09",+ "from": "harbor-east",+ "to": "gardens-north",+ "width": 10,+ "kind": "bridge",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-10",+ "from": "hub-west",+ "to": "water-east",+ "width": 10,+ "kind": "bridge",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-11",+ "from": "hub-west",+ "to": "workshop-south",+ "width": 10,+ "kind": "bridge",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-12",+ "from": "hub-north",+ "to": "solar-south",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-13",+ "from": "solar-south",+ "to": "foundry-south",+ "width": 10,+ "kind": "bridge",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-14",+ "from": "foundry-south",+ "to": "mine-south",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-15",+ "from": "hub-east",+ "to": "memory-west",+ "width": 10,+ "kind": "bridge",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-16",+ "from": "memory-west",+ "to": "mine-south",+ "width": 10,+ "kind": "bridge",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-17",+ "from": "hub-west",+ "to": "harbor-east",+ "width": 10,+ "kind": "bridge",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-18",+ "from": "hub-west",+ "to": "central-northwest",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-19",+ "from": "hub-north",+ "to": "central-northeast",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-20",+ "from": "hub-east",+ "to": "central-southeast",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-21",+ "from": "hub-south",+ "to": "central-southwest",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-22",+ "from": "central-northwest",+ "to": "hub-north",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-23",+ "from": "central-northeast",+ "to": "hub-east",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-24",+ "from": "central-southeast",+ "to": "hub-south",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-25",+ "from": "central-southwest",+ "to": "hub-west",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ }+ ],+ "graph_migrations": [+ {+ "source_signature": "9cfc77d4978d54f23b6d97d815fe5e1afcb309f328b78016f919a9ef66d186a5",+ "source_descriptor": {+ "navigation": {+ "version": 1,+ "nodes": [+ {+ "id": "hub-east",+ "position": [+ 125,+ 48,+ 40+ ]+ },+ {+ "id": "outpost-west",+ "position": [+ 256,+ 58,+ 50+ ]+ },+ {+ "id": "outpost-arrival",+ "position": [+ 268,+ 58,+ 68+ ]+ },+ {+ "id": "console-approach",+ "position": [+ 294,+ 58,+ 75+ ]+ },+ {+ "id": "console",+ "position": [+ 294,+ 58,+ 64+ ]+ },+ {+ "id": "outpost-south",+ "position": [+ 325,+ 58,+ 96+ ]+ },+ {+ "id": "gardens-east",+ "position": [+ 185,+ 36,+ 300+ ]+ },+ {+ "id": "hub-south",+ "position": [+ 0,+ 48,+ 109+ ]+ },+ {+ "id": "gardens-north",+ "position": [+ 80,+ 36,+ 234+ ]+ },+ {+ "id": "harbor-east",+ "position": [+ -137,+ 25,+ 240+ ]+ },+ {+ "id": "hub-west",+ "position": [+ -128,+ 48,+ 20+ ]+ },+ {+ "id": "water-east",+ "position": [+ -251,+ 42,+ -10+ ]+ },+ {+ "id": "workshop-south",+ "position": [+ -230,+ 66,+ -111+ ]+ },+ {+ "id": "hub-north",+ "position": [+ 0,+ 48,+ -110+ ]+ },+ {+ "id": "solar-south",+ "position": [+ -25,+ 58,+ -129+ ]+ },+ {+ "id": "foundry-south",+ "position": [+ -30,+ 92,+ -220+ ]+ },+ {+ "id": "mine-south",+ "position": [+ 150,+ 80,+ -180+ ]+ },+ {+ "id": "memory-west",+ "position": [+ 185,+ 70,+ -160+ ]+ },+ {+ "id": "central-northwest",+ "position": [+ -128,+ 48,+ -110+ ]+ },+ {+ "id": "central-northeast",+ "position": [+ 125,+ 48,+ -110+ ]+ },+ {+ "id": "central-southeast",+ "position": [+ 125,+ 48,+ 109+ ]+ },+ {+ "id": "central-southwest",+ "position": [+ -128,+ 48,+ 109+ ]+ }+ ],+ "edges": [+ {+ "id": "route-01",+ "from": "hub-east",+ "to": "outpost-west",+ "width": 10,+ "kind": "bridge",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-02",+ "from": "outpost-west",+ "to": "outpost-arrival",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-03",+ "from": "outpost-arrival",+ "to": "console-approach",+ "width": 4,+ "kind": "footpath",+ "modes": [+ "pedestrian"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-04",+ "from": "console-approach",+ "to": "console",+ "width": 2.4,+ "kind": "interior",+ "modes": [+ "pedestrian"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-05",+ "from": "outpost-arrival",+ "to": "outpost-south",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-06",+ "from": "outpost-south",+ "to": "gardens-east",+ "width": 10,+ "kind": "bridge",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-07",+ "from": "hub-south",+ "to": "gardens-north",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-08",+ "from": "gardens-north",+ "to": "gardens-east",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-09",+ "from": "harbor-east",+ "to": "gardens-north",+ "width": 10,+ "kind": "bridge",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-10",+ "from": "hub-west",+ "to": "water-east",+ "width": 10,+ "kind": "bridge",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-11",+ "from": "hub-west",+ "to": "workshop-south",+ "width": 10,+ "kind": "bridge",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-12",+ "from": "hub-north",+ "to": "solar-south",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-13",+ "from": "solar-south",+ "to": "foundry-south",+ "width": 10,+ "kind": "bridge",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-14",+ "from": "foundry-south",+ "to": "mine-south",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-15",+ "from": "hub-east",+ "to": "memory-west",+ "width": 10,+ "kind": "bridge",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-16",+ "from": "memory-west",+ "to": "mine-south",+ "width": 10,+ "kind": "bridge",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-17",+ "from": "hub-west",+ "to": "harbor-east",+ "width": 10,+ "kind": "bridge",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-18",+ "from": "hub-west",+ "to": "central-northwest",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-19",+ "from": "hub-north",+ "to": "central-northeast",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-20",+ "from": "hub-east",+ "to": "central-southeast",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-21",+ "from": "hub-south",+ "to": "central-southwest",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-22",+ "from": "central-northwest",+ "to": "hub-north",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-23",+ "from": "central-northeast",+ "to": "hub-east",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-24",+ "from": "central-southeast",+ "to": "hub-south",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ },+ {+ "id": "route-25",+ "from": "central-southwest",+ "to": "hub-west",+ "width": 10,+ "kind": "road",+ "modes": [+ "pedestrian",+ "rover"+ ],+ "stage": "blockout"+ }+ ],+ "destinations": [+ {+ "id": "outpost-approach",+ "name": "Outpost approach",+ "anchor": "console-approach",+ "capacity": 1+ },+ {+ "id": "outpost-bridge-staging",+ "name": "Outpost bridge staging",+ "anchor": "outpost-west",+ "capacity": 1+ }+ ]+ },+ "stations": [+ {+ "id": "communications-console",+ "district_id": "communications-outpost",+ "building_id": "operations",+ "checkpoint": "hub:comms",+ "capability": "communication-draft",+ "capacity": 1,+ "anchor": "console"+ }+ ],+ "spawn": {+ "position": [+ 268,+ 58,+ 68+ ],+ "yaw": 1.5707963267948966+ }+ },+ "edge_splits": {+ "route-05": [+ "route-05-lead",+ "route-05-ride",+ "route-05-tail"+ ]+ }+ }+ ],+ "rover_docks": [+ {+ "id": "outpost-a",+ "name": "Operations approach",+ "node_id": "rover-a-dock",+ "boarding_station_id": "rover-a-board",+ "exit_station_ids": [+ "rover-a-exit",+ "rover-a-alternate"+ ],+ "yaw": 1.1141908549024027+ },+ {+ "id": "outpost-b",+ "name": "South overlook",+ "node_id": "rover-b-dock",+ "boarding_station_id": "rover-b-board",+ "exit_station_ids": [+ "rover-b-exit",+ "rover-b-alternate"+ ],+ "yaw": 1.1141908549024027+ }+ ],+ "rovers": [+ {+ "id": "outpost-rover",+ "home_dock_id": "outpost-a",+ "seat_capacity": 1,+ "width_m": 3.4,+ "length_m": 4.8,+ "height_m": 2.6,+ "speed_m_s": 4+ }+ ],+ "collision": {+ "version": 1,+ "source_sha256": "ce64fbcbf1815245e9352f35b0cd6c2b3148acc747bca2e9d53808130e2a0ace",+ "solid_boxes": [+ {+ "id": "outpost:communications-mast",+ "min": [+ 313.0,+ 58.0,+ 39.0+ ],+ "max": [+ 327.0,+ 120.0,+ 53.0+ ]+ },+ {+ "id": "outpost:dish-west base",+ "min": [+ 271.435,+ 58.0,+ 39.435+ ],+ "max": [+ 284.565,+ 67.0,+ 52.565+ ]+ },+ {+ "id": "outpost:dish-east base",+ "min": [+ 343.2,+ 58.0,+ 13.2+ ],+ "max": [+ 358.8,+ 67.0,+ 28.8+ ]+ },+ {+ "id": "outpost:radome-north",+ "min": [+ 289.5,+ 58.0,+ 12.5+ ],+ "max": [+ 306.5,+ 75.0,+ 29.5+ ]+ },+ {+ "id": "outpost:radome-south",+ "min": [+ 340.8,+ 58.0,+ 58.8+ ],+ "max": [+ 361.2,+ 76.0,+ 79.2+ ]+ },+ {+ "id": "outpost:operations-west",+ "min": [+ 284.0,+ 58.0,+ 57.0+ ],+ "max": [+ 284.38,+ 66.0,+ 71.0+ ]+ },+ {+ "id": "outpost:operations-east",+ "min": [+ 303.62,+ 58.0,+ 57.0+ ],+ "max": [+ 304.0,+ 66.0,+ 71.0+ ]+ },+ {+ "id": "outpost:operations-north",+ "min": [+ 284.0,+ 58.0,+ 57.0+ ],+ "max": [+ 304.0,+ 66.0,+ 57.379999999999995+ ]+ },+ {+ "id": "outpost:operations-south-west",+ "min": [+ 284.0,+ 58.0,+ 70.62+ ],+ "max": [+ 292.5,+ 66.0,+ 71.0+ ]+ },+ {+ "id": "outpost:operations-south-east",+ "min": [+ 295.5,+ 58.0,+ 70.62+ ],+ "max": [+ 304.0,+ 66.0,+ 71.0+ ]+ },+ {+ "id": "outpost:operations-lintel",+ "min": [+ 292.5,+ 61.0,+ 70.62+ ],+ "max": [+ 295.5,+ 66.0,+ 71.0+ ]+ },+ {+ "id": "outpost:operations-jamb-west",+ "min": [+ 292.5,+ 58.0,+ 70.7+ ],+ "max": [+ 292.79999999999995,+ 61.0,+ 71.3+ ]+ },+ {+ "id": "outpost:operations-jamb-east",+ "min": [+ 295.20000000000005,+ 58.0,+ 70.7+ ],+ "max": [+ 295.5,+ 61.0,+ 71.3+ ]+ },+ {+ "id": "outpost:operations-roof",+ "min": [+ 284.0,+ 65.6,+ 57.0+ ],+ "max": [+ 304.0,+ 66.0,+ 71.0+ ]+ },+ {+ "id": "outpost:console-desk",+ "min": [+ 291.3,+ 58.0,+ 60.35+ ],+ "max": [+ 296.7,+ 59.7,+ 61.85+ ]+ },+ {+ "id": "outpost:equipment-rack--7.3",+ "min": [+ 285.8,+ 58.0,+ 58.550000000000004+ ],+ "max": [+ 287.59999999999997,+ 60.7,+ 59.85+ ]+ },+ {+ "id": "outpost:equipment-rack-7.3",+ "min": [+ 300.40000000000003,+ 58.0,+ 58.550000000000004+ ],+ "max": [+ 302.2,+ 60.7,+ 59.85+ ]+ },+ {+ "id": "outpost:service-east",+ "min": [+ 357.0,+ 58.0,+ 39.0+ ],+ "max": [+ 369.0,+ 70.0,+ 51.0+ ]+ },+ {+ "id": "outpost:service-module-0",+ "min": [+ 319.0,+ 58.0,+ 22.5+ ],+ "max": [+ 327.0,+ 63.0,+ 29.5+ ]+ },+ {+ "id": "outpost:service-module-1",+ "min": [+ 330.0,+ 58.0,+ 22.5+ ],+ "max": [+ 338.0,+ 63.0,+ 29.5+ ]+ },+ {+ "id": "outpost:service-module-2",+ "min": [+ 329.0,+ 58.0,+ 66.5+ ],+ "max": [+ 337.0,+ 63.0,+ 73.5+ ]+ },+ {+ "id": "outpost:district-sign",+ "min": [+ 334.5,+ 58.25,+ 84.75+ ],+ "max": [+ 359.5,+ 61.75,+ 85.25+ ]+ }+ ],+ "support_surfaces": [+ {+ "id": "outpost:plateau",+ "polygon": [+ [+ 379.19163409438966,+ 50.0+ ],+ [+ 381.7492419347785,+ 58.514104199157146+ ],+ [+ 381.03500148354226,+ 62.59773149092457+ ],+ [+ 379.67266156242977,+ 65.61855150291954+ ],+ [+ 379.7138129811923,+ 68.5285314444432+ ],+ [+ 379.30010118534335,+ 71.03260979086602+ ],+ [+ 378.1277633525924,+ 73.03831634746953+ ],+ [+ 378.03849366748466,+ 75.3147658224957+ ],+ [+ 375.7582675104747,+ 76.47535138798723+ ],+ [+ 376.5920862573003,+ 79.02009076235758+ ],+ [+ 376.0353986202004,+ 80.84748377192284+ ],+ [+ 375.3453245155374,+ 82.56036857604752+ ],+ [+ 372.84886548328643,+ 83.11431138481073+ ],+ [+ 374.619411079832,+ 86.35841802338464+ ],+ [+ 371.8664668879266,+ 86.61419465719865+ ],+ [+ 371.8477631042101,+ 88.77066420610154+ ],+ [+ 369.0427710204593,+ 88.82552705786364+ ],+ [+ 368.5391304378219,+ 90.68211219407127+ ],+ [+ 366.4757798300741,+ 91.26183928516427+ ],+ [+ 364.305907776994,+ 91.71462965746207+ ],+ [+ 362.1056707359226,+ 92.1158188329598+ ],+ [+ 359.15382820533574,+ 91.71099744219333+ ],+ [+ 357.44787241673714,+ 92.63385347604682+ ],+ [+ 357.24984033273296,+ 95.52668955958615+ ],+ [+ 355.0163627172807,+ 96.21929204878478+ ],+ [+ 351.8229780248019,+ 95.72647836343249+ ],+ [+ 350.03576699714756,+ 97.49592171667565+ ],+ [+ 347.24440458962243,+ 98.14202004449209+ ],+ [+ 344.0354146019505,+ 98.54786562306265+ ],+ [+ 340.18614863807016,+ 98.33623732169764+ ],+ [+ 335.6906457592861,+ 97.64443136971514+ ],+ [+ 330.14088995768566,+ 96.09496164452219+ ],+ [+ 320.0000000235387,+ 97.19276845121112+ ],+ [+ 309.92320260553623,+ 95.8036317656123+ ],+ [+ 304.3860817789598,+ 97.41144924863454+ ],+ [+ 300.6171020382319,+ 96.4128335058094+ ],+ [+ 296.8428624194162,+ 96.7738802136463+ ],+ [+ 293.5014243136735,+ 96.82410869524162+ ],+ [+ 290.7775180055971,+ 96.20986430294711+ ],+ [+ 287.26739559252616,+ 97.03352169148432+ ],+ [+ 284.624027589598,+ 96.69395315405563+ ],+ [+ 283.84745624424954,+ 94.1855756066445+ ],+ [+ 282.342651256897,+ 92.87233920109944+ ],+ [+ 280.41092477246457,+ 92.1746708111034+ ],+ [+ 278.78852878478403,+ 91.22140379678106+ ],+ [+ 275.63221416488017,+ 91.77288871157364+ ],+ [+ 274.9874496692863,+ 89.96276392460727+ ],+ [+ 272.81910058089176,+ 89.54373772814304+ ],+ [+ 271.2700169517463,+ 88.57790324653419+ ],+ [+ 268.8458597107479,+ 88.25198768788074+ ],+ [+ 268.25172461805664,+ 86.53075950021659+ ],+ [+ 266.2331971354765,+ 85.79086364501453+ ],+ [+ 267.0127497612887,+ 83.20102120989677+ ],+ [+ 266.65856938990567,+ 81.38145193368136+ ],+ [+ 265.43898673473666,+ 80.03583471739847+ ],+ [+ 265.4497731571428,+ 77.97303719974983+ ],+ [+ 262.8192600737334,+ 77.15077511848128+ ],+ [+ 262.0322551730263,+ 75.28390715927802+ ],+ [+ 262.9883953175588,+ 72.59593881470717+ ],+ [+ 259.223786114948,+ 71.55615868538268+ ],+ [+ 260.0695071914646,+ 68.59576478282621+ ],+ [+ 258.60779132628915,+ 66.06862083812328+ ],+ [+ 258.00916191438665,+ 62.79501784415481+ ],+ [+ 259.32424234087335,+ 58.36609012331292+ ],+ [+ 259.3495762567311,+ 50.000000028341475+ ],+ [+ 260.5964479323404,+ 41.809324029624264+ ],+ [+ 260.1438254971525,+ 37.64558046805121+ ],+ [+ 262.5032946937482,+ 34.95097705446951+ ],+ [+ 261.7596479107917,+ 31.928667068032997+ ],+ [+ 261.5948166400917,+ 29.284800416553985+ ],+ [+ 262.4710933812729,+ 27.199034104119573+ ],+ [+ 260.6006289453545,+ 24.091657566669426+ ],+ [+ 262.9462386735701,+ 22.909517340368904+ ],+ [+ 262.5646990164183,+ 20.547513658910997+ ],+ [+ 264.03700001067955,+ 19.19237167028285+ ],+ [+ 263.85775316965555,+ 16.97079174284609+ ],+ [+ 265.78417245795464,+ 16.029170564120022+ ],+ [+ 267.93078701319394,+ 15.33916835617471+ ],+ [+ 270.02807886435204,+ 14.723225667011768+ ],+ [+ 271.195626916927,+ 13.505118691620538+ ],+ [+ 270.8154598788249,+ 11.062239070736403+ ],+ [+ 271.77760065367204,+ 9.583349706116927+ ],+ [+ 273.49216678942435,+ 8.709703280885485+ ],+ [+ 274.5029255957228,+ 7.1638703618232+ ],+ [+ 276.18553705139044,+ 6.174977109846587+ ],+ [+ 279.0339182950227,+ 6.358389267792468+ ],+ [+ 280.4545394761706,+ 4.978073230611699+ ],+ [+ 284.11531714728227,+ 6.141803519509949+ ],+ [+ 286.6072020861511,+ 5.923706537784902+ ],+ [+ 288.9206790224664,+ 5.342083411497079+ ],+ [+ 290.8615363029251,+ 3.9229948470469864+ ],+ [+ 294.2540217761467,+ 4.505762985551868+ ],+ [+ 296.998541863548,+ 3.5405684804641524+ ],+ [+ 299.9962777661018,+ 2.1005872615302934+ ],+ [+ 304.3640355418862,+ 2.521607653845521+ ],+ [+ 309.4140918179079,+ 1.8822279245663438+ ],+ [+ 319.99999995347287,+ 0.674740860932836+ ],+ [+ 330.42279299555577,+ 2.623660707922049+ ],+ [+ 336.1069664978563,+ 1.091416398381888+ ],+ [+ 339.3572787372233,+ 3.648512367531737+ ],+ [+ 342.7642959204728,+ 4.019599925642176+ ],+ [+ 345.5890146967183,+ 4.7831242046135+ ],+ [+ 348.82367794470844,+ 4.4207693654516405+ ],+ [+ 351.64372982649695,+ 4.531083605000639+ ],+ [+ 354.31818703595144,+ 4.70225385754631+ ],+ [+ 357.4039036178342,+ 4.285014563419921+ ],+ [+ 359.3380272047489,+ 5.214233021835845+ ],+ [+ 361.55706533165505,+ 5.728808006633024+ ],+ [+ 363.0557045872154,+ 6.933918343365669+ ],+ [+ 364.25556995259376,+ 8.332764105762173+ ],+ [+ 365.4836023944597,+ 9.619029546738517+ ],+ [+ 367.05382794706486,+ 10.562764712994756+ ],+ [+ 368.37220519760007,+ 11.705337551899916+ ],+ [+ 369.3847115416682,+ 13.071153826851791+ ],+ [+ 371.1026615972322,+ 13.924999879689885+ ],+ [+ 371.7240152171838,+ 15.568955616061515+ ],+ [+ 372.9811525519948,+ 16.80279950971211+ ],+ [+ 374.4680274538123,+ 17.955756605808368+ ],+ [+ 375.31635820191013,+ 19.548347937688114+ ],+ [+ 377.47521835954484,+ 20.52704426203846+ ],+ [+ 379.62332048963174,+ 21.68942954360917+ ],+ [+ 378.8969662617972,+ 24.310792469651567+ ],+ [+ 379.63839298941355,+ 26.362961777652128+ ],+ [+ 379.1311621599627,+ 29.027309644822214+ ],+ [+ 379.07198808562094,+ 31.67061967597117+ ],+ [+ 377.65811895381694,+ 34.90872910873081+ ],+ [+ 380.19804747358233,+ 37.57501728652195+ ],+ [+ 380.37226430933055,+ 41.67575612326357+ ]+ ],+ "plane": [+ 0,+ 0,+ 57.88+ ]+ },+ {+ "id": "outpost:terrace",+ "polygon": [+ [+ 375.0,+ 78.0+ ],+ [+ 374.88022805923333,+ 79.82736669108073+ ],+ [+ 374.522961568047,+ 81.62346663143529+ ],+ [+ 373.934313455158,+ 83.35756805311127+ ],+ [+ 373.12435565298216,+ 85.0+ ],+ [+ 372.1069467640773,+ 86.5226600061221+ ],+ [+ 370.8994949366117,+ 87.89949493661166+ ],+ [+ 369.52266000612207,+ 89.10694676407729+ ],+ [+ 368.0,+ 90.12435565298213+ ],+ [+ 366.35756805311127,+ 90.93431345515802+ ],+ [+ 364.6234666314353,+ 91.52296156804695+ ],+ [+ 362.8273666910807,+ 91.88022805923335+ ],+ [+ 361.0,+ 92.0+ ],+ [+ 279.0,+ 92.0+ ],+ [+ 277.1726333089193,+ 91.88022805923335+ ],+ [+ 275.3765333685647,+ 91.52296156804695+ ],+ [+ 273.64243194688873,+ 90.93431345515802+ ],+ [+ 272.0,+ 90.12435565298215+ ],+ [+ 270.47733999387793,+ 89.10694676407729+ ],+ [+ 269.10050506338837,+ 87.89949493661166+ ],+ [+ 267.8930532359227,+ 86.5226600061221+ ],+ [+ 266.87564434701784,+ 85.0+ ],+ [+ 266.065686544842,+ 83.35756805311127+ ],+ [+ 265.477038431953,+ 81.62346663143529+ ],+ [+ 265.11977194076667,+ 79.82736669108073+ ],+ [+ 265.0,+ 78.0+ ],+ [+ 265.0,+ 22.0+ ],+ [+ 265.11977194076667,+ 20.17263330891928+ ],+ [+ 265.477038431953,+ 18.376533368564708+ ],+ [+ 266.065686544842,+ 16.642431946888742+ ],+ [+ 266.87564434701784,+ 15.0+ ],+ [+ 267.8930532359227,+ 13.477339993877912+ ],+ [+ 269.1005050633883,+ 12.10050506338834+ ],+ [+ 270.4773399938779,+ 10.893053235922707+ ],+ [+ 272.0,+ 9.875644347017861+ ],+ [+ 273.64243194688873,+ 9.06568654484198+ ],+ [+ 275.3765333685647,+ 8.477038431953048+ ],+ [+ 277.1726333089193,+ 8.119771940766654+ ],+ [+ 279.0,+ 8.0+ ],+ [+ 361.0,+ 8.0+ ],+ [+ 362.8273666910807,+ 8.119771940766654+ ],+ [+ 364.6234666314353,+ 8.47703843195304+ ],+ [+ 366.35756805311127,+ 9.065686544841988+ ],+ [+ 368.0,+ 9.875644347017861+ ],+ [+ 369.52266000612207,+ 10.893053235922707+ ],+ [+ 370.89949493661163,+ 12.100505063388333+ ],+ [+ 372.1069467640773,+ 13.477339993877905+ ],+ [+ 373.12435565298216,+ 14.999999999999993+ ],+ [+ 373.934313455158,+ 16.64243194688875+ ],+ [+ 374.522961568047,+ 18.37653336856471+ ],+ [+ 374.88022805923333,+ 20.172633308919277+ ],+ [+ 375.0,+ 21.999999999999996+ ]+ ],+ "plane": [+ 0,+ 0,+ 57.97+ ]+ },+ {+ "id": "outpost:route-01",+ "polygon": [+ [+ 124.6194278287001,+ 44.985495444028814+ ],+ [+ 125.3805721712999,+ 35.014504555971186+ ],+ [+ 256.3805721712999,+ 45.014504555971186+ ],+ [+ 255.61942782870008,+ 54.985495444028814+ ]+ ],+ "plane": [+ 0.07589363304559411,+ 0.005793407102717108,+ 38.28155958519205+ ]+ },+ {+ "id": "outpost:route-02",+ "polygon": [+ [+ 251.8397485283108,+ 52.77350098112615+ ],+ [+ 260.1602514716892,+ 47.22649901887385+ ],+ [+ 272.1602514716892,+ 65.22649901887385+ ],+ [+ 263.8397485283108,+ 70.77350098112615+ ]+ ],+ "plane": [+ 0.0,+ 0.0,+ 58.006+ ]+ },+ {+ "id": "outpost:route-03",+ "polygon": [+ [+ 267.48005305310426,+ 69.93123151704134+ ],+ [+ 268.51994694689574,+ 66.06876848295866+ ],+ [+ 294.51994694689574,+ 73.06876848295866+ ],+ [+ 293.48005305310426,+ 76.93123151704134+ ]+ ],+ "plane": [+ 0.0,+ 0.0,+ 58.006+ ]+ },+ {+ "id": "outpost:route-05",+ "polygon": [+ [+ 265.79548060173266,+ 72.48777163218708+ ],+ [+ 270.20451939826734,+ 63.512228367812924+ ],+ [+ 327.20451939826734,+ 91.51222836781292+ ],+ [+ 322.79548060173266,+ 100.48777163218708+ ]+ ],+ "plane": [+ 0.0,+ 0.0,+ 58.006+ ]+ }+ ]+ }+ },+ "stations": [+ {+ "id": "communications-console",+ "district_id": "communications-outpost",+ "building_id": "operations",+ "checkpoint": "hub:comms",+ "capability": "communication-draft",+ "capacity": 1,+ "anchor": "console"+ }+ ],+ "spawn": {+ "position": [+ 268,+ 58,+ 68+ ],+ "yaw": 1.5707963267948966+ },+ "view": {+ "near_inspection_m": 0.75,+ "overview_padding": 1.15+ }+}diff --git a/jarvis/ui/web/frontend/src/components/society/roster/RosterRail.tsx b/jarvis/ui/web/frontend/src/components/society/roster/RosterRail.tsxindex cbb436b9b4..be11bbc26e 100644--- a/jarvis/ui/web/frontend/src/components/society/roster/RosterRail.tsx+++ b/jarvis/ui/web/frontend/src/components/society/roster/RosterRail.tsx@@ -14,7 +14,7 @@* fixed width; inside the agent card it is the LEFT eighth and takes its width* from the grid cell — same rows, same sizes, only the divider swaps sides.*/-import { lazy, Suspense, useCallback, useMemo, useState, type MouseEvent } from "react";+import { lazy, Suspense, useCallback, useMemo, useState, type MouseEvent, type ReactNode } from "react";import { Eye, Loader2, Plus, Search } from "lucide-react";import { Badge } from "@/components/ui/badge";@@ -60,6 +60,8 @@ export interface RosterRailProps {side?: "left" | "right";/** Replaces the fixed width when the rail is a grid cell rather than a flex sibling. */className?: string;+ /** Sits above the title — the way back to the rest of the app. */+ header?: ReactNode;}export function RosterRail({@@ -71,6 +73,7 @@ export function RosterRail({onCreate,side = "right",className,+ header,}: RosterRailProps) {const t = useT();const [query, setQuery] = useState("");@@ -121,10 +124,11 @@ export function RosterRail({data-testid="society-roster-rail"className={cn("flex h-full min-h-0 flex-col border-border bg-sidebar",- side === "left" ? "border-r" : "border-l",+ side === "left" ? "border-r border-border" : "border-l border-border",className ?? "w-[300px] shrink-0",)}>+ {header}<div className="flex items-center justify-between gap-2 px-3 pt-3"><div className="flex min-w-0 items-center gap-2"><h2 className="font-display text-sm font-semibold tracking-tight text-foreground">@@ -226,7 +230,7 @@ export function RosterRail({)}><button type="button" onClick={() => setProfileId(agent.agentId)} aria-label={t("society.profile_card.open").replace("{0}", agent.name)} className="shrink-0 rounded-full focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">- <AgentSwatch agent={agent} size={34} />+ <AgentSwatch agent={agent} size={48} /></button><button type="button" onClick={() => onOpen(agent.agentId)} aria-current={agent.agentId === activeAgentId ? "true" : undefined} className="flex min-w-0 flex-1 select-none items-center gap-2.5 rounded-md py-2 pl-2.5 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"><span className="min-w-0 flex-1">diff --git a/jarvis/ui/web/frontend/src/components/society/world/Walkers.tsx b/jarvis/ui/web/frontend/src/components/society/world/Walkers.tsxindex 27b676463d..be3ea3e534 100644--- a/jarvis/ui/web/frontend/src/components/society/world/Walkers.tsx+++ b/jarvis/ui/web/frontend/src/components/society/world/Walkers.tsx@@ -12,6 +12,8 @@ import { Html } from "@react-three/drei";import { useFrame, useThree, type ThreeEvent } from "@react-three/fiber";import type { Group } from "three";+import { AgentFollower } from "../companion/AgentFollower";+import { resolveCompanion } from "../companion/appearance";import type { AgentCheckpoint, AgentRunState, SocietyAgent } from "../data";import { useBuildingPoses } from "./buildingPoses";import { useCameraStore } from "./cameraStore";@@ -380,6 +382,7 @@ function Walker({};return (+ <><groupref={group}rotation-order="YXZ"@@ -398,6 +401,8 @@ function Walker({</div></Html></group>+ <AgentFollower owner={group} appearance={resolveCompanion(agent.agentId, agent.figure?.companion)} paused={paused} lead={agent.tier === "lead"} />+ </>);}diff --git a/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.test.tsx b/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.test.tsxindex d462609e9a..6cfd9b874f 100644--- a/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.test.tsx+++ b/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.test.tsx@@ -81,9 +81,13 @@ describe("BrowserRealtimeControl", () => {setBrowserVoiceInputOwnership(false);delete (window as unknown as { pywebview?: unknown }).pywebview;useEventStore.setState({+ events: [],voiceState: "idle",transcription: "",transcriptionFinal: true,+ solo: false,+ activeSection: "chats",+ detachedViews: [],});});@@ -102,7 +106,7 @@ describe("BrowserRealtimeControl", () => {fakes.browserAudio = true;const visibility = vi.spyOn(document, "visibilityState", "get").mockReturnValue("hidden");try {- const { unmount } = render(<BrowserRealtimeControl />);+ const { unmount } = render(<BrowserRealtimeControl controlOnly />);act(() => {useEventStore.setState({ events: [{id: "wake-hidden", name: "BrowserVoiceRequested", ts: Date.now(),@@ -131,6 +135,65 @@ describe("BrowserRealtimeControl", () => {expect(screen.queryByRole("button")).toBeNull();});+ it("starts a desktop wake immediately even when the WebView is hidden", async () => {+ fakes.native = true;+ fakes.browserAudio = true;+ (window as unknown as { pywebview?: unknown }).pywebview = { api: {} };+ const visibility = vi.spyOn(document, "visibilityState", "get").mockReturnValue("hidden");+ try {+ render(<BrowserRealtimeControl controlOnly />);+ act(() => useEventStore.getState().pushEvent({+ id: "background-wake", name: "BrowserVoiceRequested", ts: Date.now(),+ payload: { action: "start" },+ }));+ await waitFor(() => expect(fakes.connect).toHaveBeenCalledTimes(1));+ } finally {+ visibility.mockRestore();+ }+ });++ it("handles the latest stop and a second wake without replaying the first", async () => {+ fakes.browserAudio = true;+ render(<BrowserRealtimeControl controlOnly />);+ const request = (id: string, action: string) => act(() => useEventStore.getState().pushEvent({+ id, name: "BrowserVoiceRequested", ts: Date.now(), payload: { action },+ }));+ request("start-1", "start");+ await waitFor(() => expect(fakes.connect).toHaveBeenCalledTimes(1));+ request("stop-1", "stop");+ await waitFor(() => expect(fakes.disconnect).toHaveBeenCalledTimes(1));+ request("start-2", "start");+ await waitFor(() => expect(fakes.connect).toHaveBeenCalledTimes(2));+ });++ it("does not consume a wake before the provider becomes available", async () => {+ fakes.browserAudio = true;+ fakes.available = false;+ const view = render(<BrowserRealtimeControl controlOnly />);+ act(() => useEventStore.getState().pushEvent({+ id: "early-wake", name: "BrowserVoiceRequested", ts: Date.now(), payload: { action: "start" },+ }));+ expect(fakes.connect).not.toHaveBeenCalled();+ fakes.available = true;+ view.rerender(<BrowserRealtimeControl controlOnly />);+ await waitFor(() => expect(fakes.connect).toHaveBeenCalledTimes(1));+ });++ it.each([false, true])("keeps other desktop windows from claiming the microphone (embedded=%s)", async embedded => {+ fakes.native = true;+ fakes.browserAudio = true;+ if (embedded) {+ (window as unknown as { pywebview?: unknown }).pywebview = { api: {} };+ useEventStore.setState({ solo: true, activeSection: "settings" });+ }+ render(<BrowserRealtimeControl controlOnly />);+ act(() => useEventStore.getState().pushEvent({+ id: "wrong-owner", name: "BrowserVoiceRequested", ts: Date.now(), payload: { action: "start" },+ }));+ await act(async () => undefined);+ expect(fakes.connect).not.toHaveBeenCalled();+ });+it("stays visible in external Chrome connected to the desktop backend", () => {fakes.native = true;render(<BrowserRealtimeControl />);diff --git a/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.tsx b/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.tsxindex 9fb78e72e3..dbc1d4018b 100644--- a/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.tsx+++ b/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.tsx@@ -23,6 +23,7 @@ import {import {clearVoiceOutputLevel,setBrowserVoiceOutputOwnership,+ setBrowserPlaybackActive,setVoiceOutputLevel,} from "@/lib/voiceOutputLevel";@@ -106,6 +107,16 @@ export function BrowserRealtimeControl({ controlOnly = false }: { controlOnly?:const levelRef = useRef(0);const clientRef = useRef<RealtimeAudioClient | null>(null);const events = useEventStore((store) => store.events);+ const solo = useEventStore((store) => store.solo);+ const activeSection = useEventStore((store) => store.activeSection);+ const detachedViews = useEventStore((store) => store.detachedViews);+ const embedded = hasEmbeddedDesktopBridge();+ // Match the desktop's media owner across main and detached windows. An+ // external tab must never compete with the desktop for a wake request.+ const wakeOwner = controlOnly && (embedded+ ? (solo ? activeSection === "chats" : !detachedViews.includes("chats"))+ : capabilities.data?.native_file_actions === false);+ const canStartInBackground = embedded && wakeOwner;const handledRequest = useRef<string | null>(null);// A wake that lands while the tab is hidden must not be consumed: the// desktop is already waiting for this call, and dropping the request@@ -155,20 +166,15 @@ export function BrowserRealtimeControl({ controlOnly = false }: { controlOnly?:}, [setVoice]);const start = useCallback(async () => {- if (!realtimeAvailable || state === "connecting") return;+ if (!realtimeAvailable || clientRef.current || state === "connecting") return;const generation = connectionGenerationRef.current + 1;connectionGenerationRef.current = generation;- const previousClient = clientRef.current;- clientRef.current = null;setState("connecting");setError("");setEffectiveProvider("");levelRef.current = 0;clearVoiceInputLevel("browser");clearVoiceOutputLevel("browser");- await previousClient?.disconnect();- if (connectionGenerationRef.current !== generation) return;-let client: RealtimeAudioClient;const isCurrent = () =>connectionGenerationRef.current === generation && clientRef.current === client;@@ -176,6 +182,9 @@ export function BrowserRealtimeControl({ controlOnly = false }: { controlOnly?:{onTranscript: (text, isFinal, role) => {if (!isCurrent()) return;+ // Live adapters project all speaker snapshots onto the shared bus.+ // Keeping a second local caption would overwrite the conversation.+ if (browserAudio) return;if (role === "user") setTranscription(text, isFinal);if (role === "user" && isFinal) setVoice("thinking");},@@ -184,6 +193,9 @@ export function BrowserRealtimeControl({ controlOnly = false }: { controlOnly?:setError("");setVoice("speaking");},+ onPlaybackState: (active) => {+ if (isCurrent()) setBrowserPlaybackActive(active);+ },onInputLevel: (value) => {if (!isCurrent()) return;levelRef.current = value;@@ -334,10 +346,10 @@ export function BrowserRealtimeControl({ controlOnly = false }: { controlOnly?:]);useEffect(() => {- if (!browserAudio) return;+ if (!browserAudio || !wakeOwner) return;const onVisible = () => {const pending = pendingStart.current;- if (document.visibilityState !== "visible" || !pending) return;+ if ((!canStartInBackground && document.visibilityState !== "visible") || !pending || !realtimeAvailable) return;if (Date.now() - pending.ts > 45_000) {pendingStart.current = null;return;@@ -348,15 +360,18 @@ export function BrowserRealtimeControl({ controlOnly = false }: { controlOnly?:};document.addEventListener("visibilitychange", onVisible);return () => document.removeEventListener("visibilitychange", onVisible);- }, [browserAudio, start]);+ }, [browserAudio, wakeOwner, canStartInBackground, realtimeAvailable, start]);useEffect(() => {- if (!browserAudio) return;- const event = [...events].reverse().find(e => e.name === "BrowserVoiceRequested");+ if (!browserAudio || !wakeOwner) return;+ // EventStore prepends events. Reversing picked the oldest request and+ // swallowed every subsequent start/stop until it aged out of the store.+ const event = events.find(e => e.name === "BrowserVoiceRequested");if (!event || event.id === handledRequest.current || Date.now() - event.ts > 45_000) return;const action = (event.payload as { action?: string })?.action;if (action === "start") {- if (document.visibilityState === "visible") {+ if (!realtimeAvailable) return;+ if (canStartInBackground || document.visibilityState === "visible") {handledRequest.current = event.id;pendingStart.current = null;void start();@@ -372,7 +387,7 @@ export function BrowserRealtimeControl({ controlOnly = false }: { controlOnly?:pendingStart.current = null;void stop();}- }, [events, browserAudio, start, stop]);+ }, [events, browserAudio, wakeOwner, canStartInBackground, realtimeAvailable, start, stop]);useEffect(() => {// This surface owns BOTH directions while it is live: it holds thediff --git a/jarvis/ui/web/frontend/src/hooks/useProviders.ts b/jarvis/ui/web/frontend/src/hooks/useProviders.tsindex 2794028714..fd14e3d43c 100644--- a/jarvis/ui/web/frontend/src/hooks/useProviders.ts+++ b/jarvis/ui/web/frontend/src/hooks/useProviders.ts@@ -137,6 +137,8 @@ export interface ProviderDescriptor {optional?: boolean;/** Unstable provider protocol. The card shows a clear fallback notice. */experimental?: boolean;+ /** Continuous voice uses one profile form instead of legacy inline pickers. */+ configuration_surface?: "provider" | "live";/*** Dictation-polish cards only: the value `[dictation].polish_provider`* actually stores ("groq"), which is NOT this card's `id` ("groq-polish") —diff --git a/jarvis/ui/web/frontend/src/hooks/useSectionHistory.test.ts b/jarvis/ui/web/frontend/src/hooks/useSectionHistory.test.tsnew file mode 100644index 0000000000..c03531b819--- /dev/null+++ b/jarvis/ui/web/frontend/src/hooks/useSectionHistory.test.ts@@ -0,0 +1,137 @@+import { renderHook, act } from "@testing-library/react";+import { beforeEach, describe, expect, it } from "vitest";++import { useEventStore } from "@/store/events";+import {+ resetSectionHistory,+ useSectionHistory,+ useSectionNavHistory,+} from "./useSectionHistory";++function visit(section: "chats" | "agents" | "dictation" | "tasks"): void {+ act(() => useEventStore.getState().setActiveSection(section));+}++beforeEach(() => {+ resetSectionHistory();+ useEventStore.setState({ activeSection: "chats" });+});++describe("useSectionHistory", () => {+ it("starts with both directions disabled", () => {+ const { result } = renderHook(() => useSectionHistory());+ expect(result.current.canGoBack).toBe(false);+ expect(result.current.canGoForward).toBe(false);+ });++ it("goes back to the previously visited section", () => {+ const { result } = renderHook(() => useSectionHistory());+ visit("agents");+ visit("dictation");++ expect(result.current.canGoBack).toBe(true);++ let target: string | null = null;+ act(() => {+ target = result.current.goBack();+ });++ expect(target).toBe("agents");+ expect(useEventStore.getState().activeSection).toBe("agents");+ });++ it("keeps forward disabled until a step was undone", () => {+ const { result } = renderHook(() => useSectionHistory());+ visit("agents");+ visit("dictation");++ // Forward leads nowhere before any back step — a section never visited+ // cannot be gone to.+ expect(result.current.canGoForward).toBe(false);+ expect(useSectionNavHistory.getState().goForward()).toBeNull();++ act(() => {+ result.current.goBack();+ });+ expect(result.current.canGoForward).toBe(true);++ let target: string | null = null;+ act(() => {+ target = result.current.goForward();+ });+ expect(target).toBe("dictation");+ expect(useEventStore.getState().activeSection).toBe("dictation");+ // Redone: nothing left to redo.+ expect(result.current.canGoForward).toBe(false);+ });++ it("clears the redo stack on a new visit", () => {+ const { result } = renderHook(() => useSectionHistory());+ visit("agents");+ visit("dictation");++ act(() => {+ result.current.goBack();+ });+ expect(result.current.canGoForward).toBe(true);++ visit("tasks");+ expect(result.current.canGoForward).toBe(false);+ expect(result.current.canGoBack).toBe(true);+ });++ it("walks several steps back and forward in order", () => {+ const { result } = renderHook(() => useSectionHistory());+ visit("agents");+ visit("dictation");+ visit("tasks");++ act(() => {+ result.current.goBack();+ });+ expect(useEventStore.getState().activeSection).toBe("dictation");++ act(() => {+ result.current.goBack();+ });+ expect(useEventStore.getState().activeSection).toBe("agents");+ expect(result.current.canGoBack).toBe(true);++ act(() => {+ result.current.goBack();+ });+ expect(useEventStore.getState().activeSection).toBe("chats");+ expect(result.current.canGoBack).toBe(false);++ act(() => {+ result.current.goForward();+ });+ expect(useEventStore.getState().activeSection).toBe("agents");+ });++ it("ignores a back step with no history", () => {+ const { result } = renderHook(() => useSectionHistory());+ expect(result.current.canGoBack).toBe(false);++ let target: string | null = null;+ act(() => {+ target = result.current.goBack();+ });++ expect(target).toBeNull();+ expect(useEventStore.getState().activeSection).toBe("chats");+ });++ it("does not record re-selecting the same section", () => {+ const { result } = renderHook(() => useSectionHistory());+ visit("agents");+ visit("agents");++ act(() => {+ result.current.goBack();+ });+ // One genuine visit back — not stuck on a duplicate entry.+ expect(useEventStore.getState().activeSection).toBe("chats");+ expect(result.current.canGoBack).toBe(false);+ });+});diff --git a/jarvis/ui/web/frontend/src/hooks/useSectionHistory.ts b/jarvis/ui/web/frontend/src/hooks/useSectionHistory.tsnew file mode 100644index 0000000000..40e808f7ef--- /dev/null+++ b/jarvis/ui/web/frontend/src/hooks/useSectionHistory.ts@@ -0,0 +1,144 @@+import { useEffect } from "react";+import { create } from "zustand";++import { useEventStore, type SectionId } from "@/store/events";++/**+ * How many visited sections the back stack keeps.+ *+ * A section change is cheap (one id), but an unbounded array in a long-lived+ * desktop session is not — 50 steps back is far past what anyone reaches for.+ */+const MAX_HISTORY = 50;++interface SectionNavHistoryState {+ /** The section the stacks were last reconciled with. Null until observed. */+ current: SectionId | null;+ /** Older sections, oldest first. The last entry is where "back" goes. */+ past: SectionId[];+ /** Sections undone by "back", oldest first. Cleared by any new visit. */+ future: SectionId[];+ /** True while a back/forward navigation is in flight to the store. */+ navigating: boolean;+ /** Reconcile the stacks with a newly observed section. */+ record: (section: SectionId) => void;+ /** Step one section back. Returns the target, or null when there is none. */+ goBack: () => SectionId | null;+ /** Re-apply one undone step. Returns the target, or null when there is none. */+ goForward: () => SectionId | null;+ /** Test-only reset to a pristine history. */+ reset: () => void;+}++export const useSectionNavHistory = create<SectionNavHistoryState>((set, get) => ({+ current: null,+ past: [],+ future: [],+ navigating: false,++ record: (section) => {+ const { current, past, navigating } = get();+ if (current === section) {+ // A back/forward navigation lands here through the store subscription:+ // the stacks were already moved by goBack/goForward, so only clear the+ // in-flight flag instead of recording a duplicate visit.+ if (navigating) set({ navigating: false });+ return;+ }+ if (navigating) {+ // Same flight, observed before goBack/goForward set `current` — adopt.+ set({ current: section, navigating: false });+ return;+ }+ if (current === null) {+ set({ current: section });+ return;+ }+ set({+ current: section,+ past: [...past, current].slice(-MAX_HISTORY),+ future: [],+ });+ },++ goBack: () => {+ const { current, past, future } = get();+ if (current === null || past.length === 0) return null;+ const target = past[past.length - 1];+ if (target === current) {+ set({ past: past.slice(0, -1) });+ return get().goBack();+ }+ set({+ current: target,+ past: past.slice(0, -1),+ future: [current, ...future].slice(0, MAX_HISTORY),+ navigating: true,+ });+ useEventStore.getState().setActiveSection(target);+ return target;+ },++ goForward: () => {+ const { current, past, future } = get();+ if (current === null || future.length === 0) return null;+ const [target, ...rest] = future;+ if (target === current) {+ set({ future: rest });+ return get().goForward();+ }+ set({+ current: target,+ past: [...past, current].slice(-MAX_HISTORY),+ future: rest,+ navigating: true,+ });+ useEventStore.getState().setActiveSection(target);+ return target;+ },++ reset: () => set({ current: null, past: [], future: [], navigating: false }),+}));++/** Clear the navigation history — tests only. */+export function resetSectionHistory(): void {+ useSectionNavHistory.getState().reset();+}++export interface SectionHistory {+ canGoBack: boolean;+ canGoForward: boolean;+ goBack: () => SectionId | null;+ goForward: () => SectionId | null;+}++/**+ * Browser-style section history for the caption back/forward buttons.+ *+ * Mounted once per window (the TopBar owns it): every section change flows+ * through `activeSection` — sidebar clicks, voice commands, deck jumps, staged+ * requests — so watching the value covers all of them, where hooking one click+ * path would cover one. "Back" returns to the previously visited section and+ * "forward" only re-applies an undone step: it stays disabled until a step was+ * undone, and any new visit clears the redo stack, because a section never+ * visited cannot be gone to.+ */+export function useSectionHistory(): SectionHistory {+ const activeSection = useEventStore((s) => s.activeSection);+ const record = useSectionNavHistory((s) => s.record);+ const past = useSectionNavHistory((s) => s.past);+ const future = useSectionNavHistory((s) => s.future);+ const goBack = useSectionNavHistory((s) => s.goBack);+ const goForward = useSectionNavHistory((s) => s.goForward);++ useEffect(() => {+ record(activeSection);+ }, [activeSection, record]);++ return {+ canGoBack: past.length > 0,+ canGoForward: future.length > 0,+ goBack,+ goForward,+ };+}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex 74e5bb92cc..dc5336948a 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -1,13 +1,48 @@{"live": {+ "active": "Aktiv",+ "pipeline_fallback": "Dieses Gespräch nutzt ersatzweise die Pipeline. Neue Einstellungen gelten ab dem nächsten Gespräch.","open_browser": "Sprache im Browser öffnen",- "loading": "Spracheinstellungen werden geladen…", "description": "Natürlich sprechen, Denkmodell selbst wählen und Jarvis-Tools nutzen — mit einem OpenAI-Key.",- "key_required": "Verbinde unten deinen OpenAI-Key, um GPT-Live zu nutzen.", "voice_model": "Sprachmodell", "voice": "Stimme", "thinking_model": "Denkmodell",- "choose_model": "Modell auswählen", "reasoning": "Denkaufwand", "model_default": "Modellstandard", "web_search": "Websuche",- "prompts": "Anweisungen anpassen", "conversation_prompt": "Gesprächsstil", "backend_prompt": "Anweisungen für Denken und Tools",- "billing": "Sprachdauer und Denkmodell werden getrennt abgerechnet. Computersteuerung nutzt dasselbe Denkmodell. OpenAI speichert keine Gesprächsaufzeichnung.",- "save": "Speichern und GPT-Live nutzen", "saved": "Gespeichert. Die Auswahl gilt ab dem nächsten Gespräch; die bisherige Konfiguration wurde gesichert.",- "use_for_agents": "Diesen Key und dieses Modell für Agenten und Textchat nutzen", "agent_saved": "Agenten und Textchat nutzen jetzt dieses OpenAI-Modell."+ "loading": "Spracheinstellungen werden geladen…",+ "description": "Natürlich sprechen, Denkmodell selbst wählen und Jarvis-Tools nutzen — mit einem OpenAI-Key.",+ "key_required": "Verbinde oben deinen OpenAI-Key für Sprache und Denken.",+ "voice_model": "Sprachmodell",+ "voice": "Stimme",+ "thinking_model": "Denkmodell",+ "choose_model": "Modell auswählen",+ "reasoning": "Denkaufwand",+ "model_default": "Modellstandard",+ "web_search": "Websuche",+ "prompts": "Erweitert · Anweisungen & Modell-ID",+ "conversation_prompt": "Gesprächsstil",+ "backend_prompt": "Anweisungen für Denken und Tools",+ "billing": "Sprachdauer und Denkmodell werden getrennt abgerechnet. Cloud-Aufzeichnung ist aus.",+ "save": "Speichern und GPT-Live nutzen",+ "saved": "Gespeichert. Dein nächstes Gespräch nutzt diese Einstellungen.",+ "use_for_agents": "Diesen Key und dieses Modell für Agenten und Textchat nutzen",+ "agent_saved": "Agenten und Textchat nutzen jetzt dieses OpenAI-Modell.",+ "setup_title": "Sprache & Denken",+ "setup_description": "Wähle, wie Jarvis zuhört, antwortet und deine Werkzeuge nutzt.",+ "provider_selection": "Sprachanbieter einrichten",+ "call_active": "Gespräch läuft",+ "next_call": "Änderungen gelten ab dem nächsten Gespräch",+ "connected": "Key verbunden",+ "connect": "Einrichten",+ "local_provider": "Auf deiner Hardware",+ "show_cloud": "Cloud-Anbieter anzeigen",+ "agents_separate": "Textchat und Hintergrundaufgaben nutzen deine Auswahl unter Agents. Die Sprache hat ihre eigenen Modelleinstellungen.",+ "shared_key_ready": "OpenAI verbunden · ein Key für Sprache und Denken",+ "shared_key_help": "Dieser OpenAI-Key versorgt GPT-Live und sein Denkmodell.",+ "manage_key": "Key verwalten",+ "conversation_heading": "Gespräch",+ "conversation_help": "Kontinuierliches Zuhören und natürliche Sprache, auch bei Unterbrechungen.",+ "thinking_heading": "Denken & Werkzeuge",+ "thinking_help": "Dieses Modell denkt nach, nutzt Jarvis-Werkzeuge und steuert den Computer mit demselben Key.",+ "search_models": "Denkmodell suchen…",+ "web_search_help": "Das Denkmodell darf aktuelle Informationen im Web nachschlagen.",+ "custom_model": "Eigene Denkmodell-ID",+ "ready": "Gespeichert & aktiv",+ "save_changes": "Änderungen speichern"},"input_isolation": {"title": "Diktier- und Tipphilfen erreichen dieses Fenster nicht",@@ -79,7 +114,13 @@"detached_title": "Diese Ansicht ist in einem eigenen Fenster geöffnet","detached_body": "Arbeite dort weiter oder hole sie hierher zurück.","detach_focus": "Fenster zeigen",- "detach_bring_back": "Zurückholen"+ "detach_bring_back": "Zurückholen",+ "minimize": "Minimieren",+ "maximize": "Vergrößern",+ "restore": "Wiederherstellen",+ "close": "Schließen",+ "nav_back": "Zurück",+ "nav_forward": "Vor"},"nav": {"chat_workspace": "Chat",@@ -2248,6 +2289,11 @@"settings_hub": {"subtitle": "Alles über dich, deine Schlüssel und diese App — an einem Ort.","search_placeholder": "Einstellungen durchsuchen...",+ "back_to_app": "Zurück zur App",+ "search_results": "Einstellungsoptionen",+ "search_pages": "Einstellungsseiten",+ "no_results": "Keine Einstellungen gefunden",+ "clear_search": "Suche löschen","group_general": "Allgemein","group_system": "System","group_activity": "Aktivität"diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex da6156d9a4..6090a82ecb 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -1,13 +1,48 @@{"live": {+ "active": "Active",+ "pipeline_fallback": "This conversation fell back to Pipeline. New settings apply to your next call.","open_browser": "Open voice in your browser",- "loading": "Loading voice setup…", "description": "Natural conversation, your chosen thinking model, and Jarvis tools — one OpenAI key.",- "key_required": "Connect your OpenAI key below to enable GPT-Live.", "voice_model": "Voice model", "voice": "Voice", "thinking_model": "Thinking model",- "choose_model": "Choose a model", "reasoning": "Reasoning effort", "model_default": "Model default", "web_search": "Web search",- "prompts": "Customize instructions", "conversation_prompt": "Conversation style", "backend_prompt": "Thinking and tool instructions",- "billing": "Voice duration and thinking-model usage are billed separately. Computer control uses this same thinking model. Recordings are not stored by OpenAI.",- "save": "Save and use GPT-Live", "saved": "Saved. Your selection applies to the next call; the previous configuration was backed up.",- "use_for_agents": "Use this key and model for agents and text chat", "agent_saved": "Agents and text chat now use this OpenAI model."+ "loading": "Loading voice setup…",+ "description": "Natural conversation, your chosen thinking model, and Jarvis tools — one OpenAI key.",+ "key_required": "Connect your OpenAI key above to enable voice and thinking.",+ "voice_model": "Voice model",+ "voice": "Voice",+ "thinking_model": "Thinking model",+ "choose_model": "Choose a model",+ "reasoning": "Reasoning effort",+ "model_default": "Model default",+ "web_search": "Web search",+ "prompts": "Advanced · instructions & model ID",+ "conversation_prompt": "Conversation style",+ "backend_prompt": "Thinking and tool instructions",+ "billing": "Voice time and thinking usage are billed separately. Cloud recording is off.",+ "save": "Save and use GPT-Live",+ "saved": "Saved. Your next call will use these settings.",+ "use_for_agents": "Use this key and model for agents and text chat",+ "agent_saved": "Agents and text chat now use this OpenAI model.",+ "setup_title": "Voice & thinking",+ "setup_description": "Choose how Jarvis listens, responds and uses your tools.",+ "provider_selection": "Voice provider settings",+ "call_active": "Call in progress",+ "next_call": "Changes apply to the next call",+ "connected": "Key connected",+ "connect": "Set up",+ "local_provider": "On your hardware",+ "show_cloud": "Show cloud providers",+ "agents_separate": "Text chat and background tasks use your selection in Agents. Voice has its own model settings.",+ "shared_key_ready": "OpenAI connected · one key for voice and thinking",+ "shared_key_help": "This OpenAI key serves both GPT-Live and its thinking model.",+ "manage_key": "Manage key",+ "conversation_heading": "Conversation",+ "conversation_help": "Continuous listening and natural speech, including interruptions.",+ "thinking_heading": "Thinking & tools",+ "thinking_help": "This model reasons, uses Jarvis tools and handles computer control with the same key.",+ "search_models": "Search thinking models…",+ "web_search_help": "Let the thinking model look up current information.",+ "custom_model": "Custom thinking-model ID",+ "ready": "Saved & active",+ "save_changes": "Save changes"},"input_isolation": {"title": "Dictation and typing tools can't reach this window",@@ -79,7 +114,13 @@"detached_title": "This view is open in its own window","detached_body": "Keep working there, or bring it back into this window.","detach_focus": "Show window",- "detach_bring_back": "Bring it back"+ "detach_bring_back": "Bring it back",+ "minimize": "Minimize",+ "maximize": "Maximize",+ "restore": "Restore",+ "close": "Close",+ "nav_back": "Go back",+ "nav_forward": "Go forward"},"nav": {"chat_workspace": "Chat",@@ -2281,6 +2322,11 @@"settings_hub": {"subtitle": "Everything about you, your keys and this app — in one place.","search_placeholder": "Search settings...",+ "back_to_app": "Back to app",+ "search_results": "Settings options",+ "search_pages": "Settings pages",+ "no_results": "No settings found",+ "clear_search": "Clear search","group_general": "General","group_system": "System","group_activity": "Activity"diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/de.json b/jarvis/ui/web/frontend/src/i18n/locales/society/de.jsonindex 2feb058067..bd867cba80 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/society/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/de.json@@ -46,6 +46,16 @@"model": "Modell"},"routine_detail": {+ "back_to_agent": "Zurück zum Agenten-Chat",+ "saved_result": "Gespeichertes Ausführungsergebnis",+ "historical_chat": "Diese ältere Ausführung wurde im Hauptchat des Agenten gespeichert. Hier siehst du nur diese Ausführung, schreibgeschützt.",+ "trace_unavailable": "Für diese Ausführung ist kein passender Chatverlauf verfügbar. Falls vorhanden, wird unten ihr gespeichertes Ergebnis angezeigt.",+ "latest_chat": "Letzten Chat öffnen",+ "open_chat": "Chat öffnen",+ "background_chat": "Hintergrund-Ausführung",+ "follow_up": "Zu dieser Ausführung nachfragen…",+ "stop_run": "Ausführung stoppen",+ "send": "Senden","test_started": "Testlauf gestartet.","active": "Aktiv","delete": "Löschen",@@ -54,6 +64,14 @@"cancel": "Abbrechen","name": "Name","prompt": "Anweisung",+ "model": "Modell",+ "model_follows_agent": "Läuft auf dem aktuellen Modell des Agenten. Wähle eines, um diese Routine darauf festzulegen.",+ "model_name": "Modell",+ "provider": "Anbieter",+ "effort": "Aufwand",+ "account": "Konto",+ "follow_agent": "Agent folgen",+ "change": "Ändern","save": "Speichern","saved": "Gespeichert.","when": "Wann ausführen",@@ -540,6 +558,166 @@"allow": "Erlauben","deny": "Ablehnen","repair": "Browser reparieren"+ },+ "mars": {+ "rover_title": "Agenten-Rover",+ "rover_scope": "Reserviere einen Sitz für diesen Agenten, lass ihn einsteigen und wähle eine Route. Seine Arbeit läuft unabhängig weiter. Der Gehprototyp ist separat.",+ "rover_active_required": "Wähle einen aktiven Agenten, um seine Fahrt zu steuern.",+ "rover_pending": "Unbestätigte Rover-Anfrage",+ "rover_retry": "Dieselbe Rover-Anfrage wiederholen",+ "rover_pending_other": "Wiederhole zuerst die gespeicherte Anfrage für den oben genannten Agenten. Ihre ursprüngliche Kennung bleibt erhalten.",+ "rover_vehicle": "Fahrzeug",+ "rover_vehicle_outpost-rover": "Outpost-Rover",+ "rover_reserve": "Sitz reservieren und hingehen",+ "rover_unavailable": "Der Rover ist belegt, unterwegs oder nicht an einem Haltepunkt verfügbar.",+ "rover_route": "Zielhaltestelle",+ "rover_dock_outpost-a": "Zugang zum Betriebsgebäude",+ "rover_dock_outpost-b": "Südlicher Aussichtspunkt",+ "rover_board": "In den Rover einsteigen",+ "rover_travel": "Zur Haltestelle fahren",+ "rover_stop": "Rover anhalten",+ "rover_cancel": "Reservierung abbrechen",+ "rover_exit": "Sicher aussteigen",+ "rover_attached": "Der Agent bleibt sitzen, bis ein sicherer Ausstieg bestätigt ist.",+ "rover_exit_blocked": "Kein sicherer Ausstieg verfügbar. Der Sitz bleibt belegt. Versuche den Ausstieg erneut oder wähle eine erreichbare Haltestelle.",+ "rover_offline": "Warte auf den aktuellen Rover-Status. Die Steuerung ist offline nicht verfügbar.",+ "rover_uncertain": "Zustellung unklar. Ein erneuter Versuch behält die ursprüngliche Aktion und Anfragekennung.",+ "rover_marker": "Bestätigter Standort · Rover-Gestaltung ausstehend",+ "rover_state_approaching": "Auf dem Weg zum Rover",+ "rover_state_ready_to_board": "Bereit zum Einsteigen",+ "rover_state_boarded": "An Bord",+ "rover_state_traveling": "Unterwegs",+ "rover_state_arrived": "An der Haltestelle angekommen",+ "rover_state_stopped": "Angehalten · noch an Bord",+ "rover_state_exit_blocked": "Ausstieg blockiert · noch an Bord",+ "rover_state_completed": "Sicher ausgestiegen",+ "rover_state_canceled": "Reservierung abgebrochen",+ "rover_action_reserve": "Sitz reservieren",+ "rover_action_board": "Einsteigen",+ "rover_action_travel": "Fahren",+ "rover_action_cancel": "Anhalten oder abbrechen",+ "rover_action_exit": "Aussteigen",+ "shadows": "Schatten",+ "gigi_focus": "Gigi ansehen",+ "follow": "Folgen",+ "follow_agent": "Einem Agenten folgen",+ "follow_named_agent": "{0} folgen",+ "stop_follow": "Folgen beenden",+ "stop_follow_agent": "{0} nicht mehr folgen",+ "following_agent": "Die Kamera folgt {0}. Ziehe die Ansicht oder drücke Escape im Sichtfeld, um das Folgen zu beenden.",+ "follow_waiting": "Warte auf eine bestätigte Position für {0}.",+ "follow_offline": "Folgen pausiert: Positionen sind offline. Die zuletzt bestätigte Ansicht von {0} bleibt erhalten.",+ "gigi_recall": "Gigi zurückrufen",+ "gigi_hide": "Gigi ausblenden",+ "gigi_show": "Gigi einblenden",+ "gigi_unavailable": "Gigi-Modell nicht verfügbar",+ "visits": "Agentenbesuche",+ "visit_scope": "Besuche ändern den Aufenthaltsort. Aufträge laufen unabhängig weiter.",+ "destination": "Ziel",+ "destination_communications-console": "Kommunikationskonsole",+ "destination_outpost-bridge-staging": "Wartefläche an der Brücke",+ "destination_outpost-approach": "Betriebseingang",+ "approach_hint": "Ein Agent am Eingang blockiert den Konsolenweg. Die Wartefläche an der Brücke hält ihn frei.",+ "start_visit": "Zu Fuß besuchen",+ "retry_visit": "Offenen Besuch erneut versuchen",+ "pending_visit": "Offener Besuch",+ "stop_visit": "Besuch stoppen",+ "park_by_bridge": "An der Brücke warten",+ "waiting_entry": "Wartet auf Zutritt",+ "stopped_in_place": "Der Agent bleibt an seinem Standort. Schicke ihn zur Wartefläche an der Brücke, um den Weg freizugeben.",+ "positions_offline": "Positionen sind nicht verfügbar. Angezeigt werden höchstens die zuletzt bestätigten Standorte.",+ "last_known_position": "Zuletzt bestätigter Standort",+ "visit_uncertain": "Die Zustellung ist unklar. Erneut versuchen verwendet denselben Besuchsauftrag.",+ "move_state_queueing": "Wartet auf freien Platz",+ "move_state_moving": "Unterwegs",+ "move_state_temporarily_blocked": "Weg vorübergehend blockiert",+ "move_state_rerouting": "Sucht einen anderen Weg",+ "move_state_arrived": "Angekommen",+ "move_state_unreachable": "Ziel nicht erreichbar",+ "move_state_canceled": "Besuch gestoppt",+ "viewpoint": "Outpost-Blickwinkel",+ "view_reference": "Referenzansicht",+ "view_close_reference": "Referenzansicht aus der Nähe",+ "view_front": "Vorderseite",+ "view_rear": "Rückseite",+ "view_left": "Linke Seite",+ "view_right": "Rechte Seite",+ "view_top": "Dachansicht",+ "background_unavailable": "Hintergrundbetrieb ist in dieser Umgebung nicht verfügbar. Lass das Fenster offen oder nutze den Headless-Server.",+ "headless_background": "Backend läuft ohne Fenster",+ "background_on": "Hintergrundmodus an",+ "background_off": "Beim Schließen weiterarbeiten",+ "background_failed": "Hintergrundmodus konnte nicht geändert werden. Lass das Fenster offen und versuche es erneut.",+ "headless_hint": "Arbeit läuft weiter, solange dieser Backend-Prozess aktiv ist. Explizites Stoppen beendet die Ausführung.",+ "background_hint": "Beim Schließen läuft Backend-Arbeit weiter. Öffnen oder Beenden über das Tray-Menü. Browser-Sprachsitzungen enden mit ihrem Client.",+ "background_enable_hint": "Aktivieren, damit diese Sitzung nach dem Schließen weiterläuft. Explizites Beenden stoppt sie immer.",+ "reference_pending": "Gestaltete Referenz · Freigabe ausstehend",+ "credential_input": "Zugangsdaten gehören in den Bereich API Keys der App, nicht in einen Entwurf. Es wurde nichts eingereicht.",+ "colony": "Mars-Kolonie",+ "foundation": "Weltgrundlage · unfertiger Bauprototyp",+ "overview": "Übersicht",+ "outpost": "Outpost",+ "walk": "Laufprototyp",+ "neutral": "Neutrales Licht",+ "ledger": "Agentenstatus",+ "viewport": "Mars-Bewegungs- und Kameraprototyp",+ "loading": "Mars-Weltgrundlage wird geladen…",+ "no_graphics": "3D ist nicht verfügbar. Status und Stopp bleiben über die Übersicht und Kommunikationsstation erreichbar.",+ "player_help": "Szene anklicken · WASD / Pfeile bewegen · Ziehen blickt · Umschalt rennt · Leertaste springt · E nutzt nahe Konsole · Esc löst Eingabe",+ "orbit_help": "Ziehen dreht 360° · Rechtsziehen verschiebt · Scrollen zoomt · Gebäude anklicken zur Ansicht",+ "interior_pending": "Innenraum für Bewegungstests; finale Gestaltung offen",+ "access_pending": "unfertiger Baukörper; finaler Zugang offen",+ "placeholder_actor": "Gelbe Kapsel: Bewegungsprototyp. Neue Figuren, Rover und die finale Outpost-Gestaltung stehen noch aus.",+ "district_blockout": "Bauprototyp · unfertig",+ "entrance": "Betriebseingang · Bewegungsprototyp",+ "station_title": "Kommunikationsstation",+ "close": "Schließen",+ "station_scope": "Erstelle einen Entwurf mit einem vorhandenen Agenten. Es wird nichts gesendet oder veröffentlicht. Bei laufendem Backend geht die Arbeit auch nach dem Schließen dieser Ansicht weiter.",+ "agent": "Agent",+ "draft": "Entwurfsauftrag",+ "prepare_draft": "Entwurf erstellen",+ "retry_same": "Denselben Auftrag erneut prüfen",+ "uncertain": "Der Ausgang ist unklar. Wiederhole denselben Auftrag, bevor du einen neuen Entwurf startest.",+ "request_failed": "Die Anfrage ist fehlgeschlagen. Prüfe die Agentenunterhaltung und versuche es erneut.",+ "recorded_work": "Gespeicherte Aufträge",+ "offline": "Das Backend ist nicht erreichbar. Laufende Arbeit kann nicht bestätigt werden.",+ "no_agents": "Erstelle oder aktiviere zuerst einen Agenten unter Jarvis Agents.",+ "inspect_reason": "Prüfe den gespeicherten Grund in der Unterhaltung.",+ "open_conversation": "Unterhaltung öffnen",+ "stop": "Stoppen",+ "stopping": "Wird gestoppt…",+ "state_queued": "Wartet",+ "state_active": "Läuft",+ "state_completed": "Abgeschlossen",+ "state_failed": "Fehlgeschlagen",+ "state_canceled": "Abgebrochen",+ "state_interrupted": "Unterbrochen",+ "state_unknown": "Ausgang unklar",+ "open_preview": "Mars-Vorschau",+ "previous_world": "Bisherige Welt"+ },+ "companion": {+ "title": "Dein Begleiter",+ "hint": "Dein Profilbild folgt deinem Charakter auf der Map. Charakter und Begleiter kannst du getrennt gestalten.",+ "appearance": "Charakter & Begleiter",+ "character": "Charakter",+ "companion": "Begleiter",+ "shape": "Form",+ "color": "Farbe",+ "custom_color": "Eigene Farbe",+ "eyes": "Augen",+ "dots": "Runde Augen",+ "lines": "Strichaugen",+ "visible": "Auf der Map folgen",+ "shapes": {+ "circle": "Kreis",+ "squircle": "Weiches Quadrat",+ "pill": "Kapsel",+ "triangle": "Dreieck",+ "hexagon": "Sechseck",+ "cloud": "Wolke",+ "drop": "Tropfen"+ }}}}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/en.json b/jarvis/ui/web/frontend/src/i18n/locales/society/en.jsonindex a2305bda83..5c8edd6b90 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/society/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/en.json@@ -46,6 +46,16 @@"model": "Model"},"routine_detail": {+ "back_to_agent": "Back to agent chat",+ "saved_result": "Saved execution result",+ "historical_chat": "This older execution was stored in the agent's main chat. Only this execution is shown here, read-only.",+ "trace_unavailable": "No matching chat transcript is available for this execution. Its saved result is shown below when available.",+ "latest_chat": "Open latest chat",+ "open_chat": "Open chat",+ "background_chat": "Background execution",+ "follow_up": "Ask about this execution…",+ "stop_run": "Stop execution",+ "send": "Send","test_started": "Test run started.","active": "Active","delete": "Delete",@@ -54,6 +64,14 @@"cancel": "Cancel","name": "Name","prompt": "Instruction",+ "model": "Model",+ "model_follows_agent": "Runs on the agent's current model. Pick one to pin this routine to it.",+ "model_name": "Model",+ "provider": "Provider",+ "effort": "Effort",+ "account": "Account",+ "follow_agent": "Follow agent",+ "change": "Change","save": "Save","saved": "Saved.","when": "When to run",@@ -540,6 +558,166 @@"allow": "Allow","deny": "Deny","repair": "Repair browser"+ },+ "mars": {+ "rover_title": "Agent rover",+ "rover_scope": "Reserve a seat for this agent, board, then choose a route. Agent work continues independently. The walk prototype is separate.",+ "rover_active_required": "Select an active agent to control its ride.",+ "rover_pending": "Unconfirmed rover request",+ "rover_retry": "Retry the same rover request",+ "rover_pending_other": "Retry the saved request for the agent named above before starting another. Its original identity is preserved.",+ "rover_vehicle": "Vehicle",+ "rover_vehicle_outpost-rover": "Outpost rover",+ "rover_reserve": "Reserve seat and approach",+ "rover_unavailable": "The rover is occupied, moving, or unavailable at a dock.",+ "rover_route": "Destination dock",+ "rover_dock_outpost-a": "Operations approach",+ "rover_dock_outpost-b": "South overlook",+ "rover_board": "Board rover",+ "rover_travel": "Travel to dock",+ "rover_stop": "Stop rover",+ "rover_cancel": "Cancel reservation",+ "rover_exit": "Exit safely",+ "rover_attached": "The agent remains seated until a safe exit is confirmed.",+ "rover_exit_blocked": "No safe exit is available. The seat remains occupied; retry exit or choose a reachable dock.",+ "rover_offline": "Waiting for current rover status. Controls are unavailable while offline.",+ "rover_uncertain": "Delivery is uncertain. Retry keeps the original action and request identity.",+ "rover_marker": "Confirmed location · rover art pending",+ "rover_state_approaching": "Approaching rover",+ "rover_state_ready_to_board": "Ready to board",+ "rover_state_boarded": "On board",+ "rover_state_traveling": "Traveling",+ "rover_state_arrived": "Arrived at dock",+ "rover_state_stopped": "Stopped · still seated",+ "rover_state_exit_blocked": "Exit blocked · still seated",+ "rover_state_completed": "Exited safely",+ "rover_state_canceled": "Reservation canceled",+ "rover_action_reserve": "Reserve seat",+ "rover_action_board": "Board",+ "rover_action_travel": "Travel",+ "rover_action_cancel": "Stop or cancel",+ "rover_action_exit": "Exit",+ "shadows": "Shadows",+ "gigi_focus": "Focus Gigi",+ "follow": "Follow",+ "follow_agent": "Follow an agent",+ "follow_named_agent": "Follow {0}",+ "stop_follow": "Stop following",+ "stop_follow_agent": "Stop following {0}",+ "following_agent": "Following {0}. Drag the view or press Escape in the viewport to stop.",+ "follow_waiting": "Waiting for a confirmed position for {0}.",+ "follow_offline": "Following paused: positions are offline. Holding the last confirmed view of {0}.",+ "gigi_recall": "Recall Gigi",+ "gigi_hide": "Hide Gigi",+ "gigi_show": "Show Gigi",+ "gigi_unavailable": "Gigi model unavailable",+ "visits": "Agent visits",+ "visit_scope": "Visits change an agent's location. Work continues independently.",+ "destination": "Destination",+ "destination_communications-console": "Communications console",+ "destination_outpost-bridge-staging": "Waiting area by the bridge",+ "destination_outpost-approach": "Operations entrance",+ "approach_hint": "Waiting at the entrance blocks the console route. Use the bridge waiting area to leave it clear.",+ "start_visit": "Visit on foot",+ "retry_visit": "Retry pending visit",+ "pending_visit": "Pending visit",+ "stop_visit": "Stop visit",+ "park_by_bridge": "Wait by the bridge",+ "waiting_entry": "Waiting to enter",+ "stopped_in_place": "The agent stays at its current location. Move it to the bridge waiting area to clear the route.",+ "positions_offline": "Positions are unavailable. Any shown locations are the last confirmed positions.",+ "last_known_position": "Last confirmed position",+ "visit_uncertain": "Delivery is uncertain. Retry keeps the same visit request.",+ "move_state_queueing": "Waiting for space",+ "move_state_moving": "On the way",+ "move_state_temporarily_blocked": "Route temporarily blocked",+ "move_state_rerouting": "Finding another route",+ "move_state_arrived": "Arrived",+ "move_state_unreachable": "Cannot reach destination",+ "move_state_canceled": "Visit stopped",+ "viewpoint": "Outpost viewpoint",+ "view_reference": "Reference view",+ "view_close_reference": "Close reference",+ "view_front": "Front",+ "view_rear": "Rear",+ "view_left": "Left side",+ "view_right": "Right side",+ "view_top": "Roof view",+ "background_unavailable": "Background mode is unavailable in this environment. Keep the window open or use the headless server.",+ "headless_background": "Backend running without a window",+ "background_on": "Background mode on",+ "background_off": "Keep working when window closes",+ "background_failed": "Background mode could not change. Keep the window open and try again.",+ "headless_hint": "Work continues while this backend process is running. An explicit stop ends execution.",+ "background_hint": "Closing the window keeps backend work running. Reopen or Quit from the tray. Browser-based voice ends when its client closes.",+ "background_enable_hint": "Enable to keep this session running after closing its window. Explicit Quit always stops it.",+ "reference_pending": "Authored reference · approval pending",+ "credential_input": "Credentials belong in API Keys in the app, not in a draft. Nothing was submitted.",+ "colony": "Mars colony",+ "foundation": "Foundation prototype · unfinished blockout",+ "overview": "Overview",+ "outpost": "Outpost",+ "walk": "Walk prototype",+ "neutral": "Neutral light",+ "ledger": "Agent status",+ "viewport": "Mars movement and camera prototype",+ "loading": "Loading the Mars foundation…",+ "no_graphics": "3D rendering is unavailable. Agent status and stop controls remain available in the Ledger and communications station.",+ "player_help": "Click scene · WASD / arrows move · Drag looks · Shift runs · Space jumps · E uses nearby console · Esc releases input",+ "orbit_help": "Drag to orbit 360° · Right-drag pans · Scroll zooms · Click a building to inspect",+ "interior_pending": "movement-test interior; final art pending",+ "access_pending": "unfinished massing; final access pending",+ "placeholder_actor": "Yellow capsule: movement prototype. New characters, rover and final Outpost art are pending.",+ "district_blockout": "Blockout · unfinished",+ "entrance": "Operations entrance · movement prototype",+ "station_title": "Communications station",+ "close": "Close",+ "station_scope": "Prepare a draft with an existing agent. Nothing is sent or published. Work continues while the backend is running, even after this view closes.",+ "agent": "Agent",+ "draft": "Draft request",+ "prepare_draft": "Prepare draft",+ "retry_same": "Retry same request",+ "uncertain": "The outcome is uncertain. Retry with the same request identity before starting another draft.",+ "request_failed": "The request failed. Inspect the agent conversation and try again.",+ "recorded_work": "Recorded work",+ "offline": "The backend is unavailable. Current work cannot be confirmed.",+ "no_agents": "Create or activate an agent in Jarvis Agents first.",+ "inspect_reason": "Inspect the conversation for the recorded reason.",+ "open_conversation": "Open conversation",+ "stop": "Stop",+ "stopping": "Stopping…",+ "state_queued": "Queued",+ "state_active": "Running",+ "state_completed": "Completed",+ "state_failed": "Failed",+ "state_canceled": "Canceled",+ "state_interrupted": "Interrupted",+ "state_unknown": "Outcome unknown",+ "open_preview": "Mars preview",+ "previous_world": "Previous world"+ },+ "companion": {+ "title": "Your companion",+ "hint": "Your profile picture follows your character on the map. Character and companion are customized separately.",+ "appearance": "Character & companion",+ "character": "Character",+ "companion": "Companion",+ "shape": "Shape",+ "color": "Colour",+ "custom_color": "Custom colour",+ "eyes": "Eyes",+ "dots": "Round eyes",+ "lines": "Line eyes",+ "visible": "Follow on the map",+ "shapes": {+ "circle": "Circle",+ "squircle": "Soft square",+ "pill": "Pill",+ "triangle": "Triangle",+ "hexagon": "Hexagon",+ "cloud": "Cloud",+ "drop": "Drop"+ }}}}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/es.json b/jarvis/ui/web/frontend/src/i18n/locales/society/es.jsonindex 4f7d964113..f310f30b38 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/society/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/es.json@@ -46,6 +46,16 @@"model": "Modelo"},"routine_detail": {+ "back_to_agent": "Volver al chat del agente",+ "saved_result": "Resultado guardado de la ejecución",+ "historical_chat": "Esta ejecución antigua se guardó en el chat principal del agente. Aquí se muestra solo esta ejecución, en modo de lectura.",+ "trace_unavailable": "No hay una transcripción coincidente para esta ejecución. Su resultado guardado se muestra abajo, si está disponible.",+ "latest_chat": "Abrir último chat",+ "open_chat": "Abrir chat",+ "background_chat": "Ejecución en segundo plano",+ "follow_up": "Preguntar sobre esta ejecución…",+ "stop_run": "Detener ejecución",+ "send": "Enviar","test_started": "Prueba iniciada.","active": "Activo","delete": "Eliminar",@@ -54,6 +64,14 @@"cancel": "Cancelar","name": "Nombre","prompt": "Instrucción",+ "model": "Modelo",+ "model_follows_agent": "Se ejecuta con el modelo actual del agente. Elige uno para fijar esta rutina.",+ "model_name": "Modelo",+ "provider": "Proveedor",+ "effort": "Esfuerzo",+ "account": "Cuenta",+ "follow_agent": "Seguir al agente",+ "change": "Cambiar","save": "Guardar","saved": "Guardado.","when": "Cuándo ejecutar",@@ -540,6 +558,166 @@"allow": "Permitir","deny": "Denegar","repair": "Reparar navegador"+ },+ "mars": {+ "rover_title": "Rover de agentes",+ "rover_scope": "Reserva un asiento para este agente, haz que suba y elige una ruta. Su trabajo continúa de forma independiente. El prototipo a pie es independiente.",+ "rover_active_required": "Selecciona un agente activo para controlar su viaje.",+ "rover_pending": "Solicitud del rover sin confirmar",+ "rover_retry": "Reintentar la misma solicitud del rover",+ "rover_pending_other": "Reintenta la solicitud guardada para el agente indicado antes de iniciar otra. Se conserva su identidad original.",+ "rover_vehicle": "Vehículo",+ "rover_vehicle_outpost-rover": "Rover del puesto",+ "rover_reserve": "Reservar asiento y acercarse",+ "rover_unavailable": "El rover está ocupado, en movimiento o no está disponible en una parada.",+ "rover_route": "Parada de destino",+ "rover_dock_outpost-a": "Acceso a operaciones",+ "rover_dock_outpost-b": "Mirador sur",+ "rover_board": "Subir al rover",+ "rover_travel": "Viajar a la parada",+ "rover_stop": "Detener el rover",+ "rover_cancel": "Cancelar reserva",+ "rover_exit": "Bajar con seguridad",+ "rover_attached": "El agente permanece sentado hasta que se confirme una salida segura.",+ "rover_exit_blocked": "No hay una salida segura. El asiento sigue ocupado; reintenta la salida o elige una parada accesible.",+ "rover_offline": "Esperando el estado actual del rover. Los controles no están disponibles sin conexión.",+ "rover_uncertain": "La entrega es incierta. El reintento conserva la acción y la identidad de la solicitud original.",+ "rover_marker": "Ubicación confirmada · diseño del rover pendiente",+ "rover_state_approaching": "Acercándose al rover",+ "rover_state_ready_to_board": "Listo para subir",+ "rover_state_boarded": "A bordo",+ "rover_state_traveling": "Viajando",+ "rover_state_arrived": "Llegó a la parada",+ "rover_state_stopped": "Detenido · sigue a bordo",+ "rover_state_exit_blocked": "Salida bloqueada · sigue a bordo",+ "rover_state_completed": "Bajó con seguridad",+ "rover_state_canceled": "Reserva cancelada",+ "rover_action_reserve": "Reservar asiento",+ "rover_action_board": "Subir",+ "rover_action_travel": "Viajar",+ "rover_action_cancel": "Detener o cancelar",+ "rover_action_exit": "Bajar",+ "shadows": "Sombras",+ "gigi_focus": "Enfocar a Gigi",+ "follow": "Seguir",+ "follow_agent": "Seguir a un agente",+ "follow_named_agent": "Seguir a {0}",+ "stop_follow": "Dejar de seguir",+ "stop_follow_agent": "Dejar de seguir a {0}",+ "following_agent": "Siguiendo a {0}. Arrastra la vista o pulsa Escape en el visor para dejar de seguir.",+ "follow_waiting": "Esperando una posición confirmada de {0}.",+ "follow_offline": "Seguimiento pausado: las posiciones no están disponibles. Se conserva la última vista confirmada de {0}.",+ "gigi_recall": "Llamar a Gigi",+ "gigi_hide": "Ocultar a Gigi",+ "gigi_show": "Mostrar a Gigi",+ "gigi_unavailable": "Modelo de Gigi no disponible",+ "visits": "Visitas de agentes",+ "visit_scope": "Las visitas cambian la ubicación. El trabajo continúa de forma independiente.",+ "destination": "Destino",+ "destination_communications-console": "Consola de comunicaciones",+ "destination_outpost-bridge-staging": "Zona de espera junto al puente",+ "destination_outpost-approach": "Entrada de operaciones",+ "approach_hint": "Esperar en la entrada bloquea la ruta a la consola. Usa la zona junto al puente para dejarla libre.",+ "start_visit": "Visitar a pie",+ "retry_visit": "Reintentar visita pendiente",+ "pending_visit": "Visita pendiente",+ "stop_visit": "Detener visita",+ "park_by_bridge": "Esperar junto al puente",+ "waiting_entry": "Esperando para entrar",+ "stopped_in_place": "El agente permanece en su ubicación. Envíalo a la zona de espera del puente para liberar la ruta.",+ "positions_offline": "Las posiciones no están disponibles. Se muestran las últimas ubicaciones confirmadas.",+ "last_known_position": "Última ubicación confirmada",+ "visit_uncertain": "La entrega es incierta. El reintento conserva la misma solicitud de visita.",+ "move_state_queueing": "Esperando espacio",+ "move_state_moving": "En camino",+ "move_state_temporarily_blocked": "Ruta bloqueada temporalmente",+ "move_state_rerouting": "Buscando otra ruta",+ "move_state_arrived": "Llegó al destino",+ "move_state_unreachable": "Destino inaccesible",+ "move_state_canceled": "Visita detenida",+ "viewpoint": "Vista del puesto",+ "view_reference": "Vista de referencia",+ "view_close_reference": "Referencia cercana",+ "view_front": "Frente",+ "view_rear": "Parte posterior",+ "view_left": "Lado izquierdo",+ "view_right": "Lado derecho",+ "view_top": "Vista del techo",+ "background_unavailable": "El modo en segundo plano no está disponible aquí. Mantén la ventana abierta o usa el servidor sin interfaz.",+ "headless_background": "Servidor activo sin ventana",+ "background_on": "Modo en segundo plano activo",+ "background_off": "Continuar al cerrar la ventana",+ "background_failed": "No se pudo cambiar el modo. Mantén la ventana abierta e inténtalo de nuevo.",+ "headless_hint": "El trabajo continúa mientras este proceso siga activo. Una parada explícita termina la ejecución.",+ "background_hint": "Cerrar la ventana mantiene el trabajo activo. Abre o sal desde la bandeja. La voz del navegador termina al cerrar su cliente.",+ "background_enable_hint": "Actívalo para mantener esta sesión tras cerrar la ventana. Salir explícitamente siempre la detiene.",+ "reference_pending": "Referencia creada · aprobación pendiente",+ "credential_input": "Las credenciales se configuran en API Keys de la app, no en un borrador. No se envió nada.",+ "colony": "Colonia de Marte",+ "foundation": "Base del mundo · prototipo sin terminar",+ "overview": "Vista general",+ "outpost": "Puesto avanzado",+ "walk": "Prototipo a pie",+ "neutral": "Luz neutra",+ "ledger": "Estado de agentes",+ "viewport": "Prototipo de movimiento y cámara en Marte",+ "loading": "Cargando la base de Marte…",+ "no_graphics": "El renderizado 3D no está disponible. El estado y la parada siguen disponibles en el Registro y la estación.",+ "player_help": "Clic en escena · WASD / flechas mueven · Arrastrar mira · Mayús corre · Espacio salta · E usa consola cercana · Esc libera entrada",+ "orbit_help": "Arrastrar gira 360° · Arrastrar con botón derecho desplaza · Rueda amplía · Clic inspecciona edificio",+ "interior_pending": "interior de prueba de movimiento; arte final pendiente",+ "access_pending": "volumen sin terminar; acceso final pendiente",+ "placeholder_actor": "Cápsula amarilla: prototipo de movimiento. Personajes, rover y arte final pendientes.",+ "district_blockout": "Prototipo · sin terminar",+ "entrance": "Entrada de operaciones · prototipo",+ "station_title": "Estación de comunicaciones",+ "close": "Cerrar",+ "station_scope": "Prepara un borrador con un agente existente. No se envía ni publica nada. El trabajo continúa mientras el servidor siga activo, aunque cierres esta vista.",+ "agent": "Agente",+ "draft": "Solicitud de borrador",+ "prepare_draft": "Preparar borrador",+ "retry_same": "Reintentar la misma solicitud",+ "uncertain": "El resultado es incierto. Reintenta con la misma identidad antes de iniciar otro borrador.",+ "request_failed": "La solicitud falló. Revisa la conversación del agente e inténtalo de nuevo.",+ "recorded_work": "Trabajo registrado",+ "offline": "El servidor no está disponible. No se puede confirmar el trabajo actual.",+ "no_agents": "Crea o activa primero un agente en Jarvis Agents.",+ "inspect_reason": "Revisa el motivo registrado en la conversación.",+ "open_conversation": "Abrir conversación",+ "stop": "Detener",+ "stopping": "Deteniendo…",+ "state_queued": "En cola",+ "state_active": "En ejecución",+ "state_completed": "Completado",+ "state_failed": "Fallido",+ "state_canceled": "Cancelado",+ "state_interrupted": "Interrumpido",+ "state_unknown": "Resultado desconocido",+ "open_preview": "Vista previa de Marte",+ "previous_world": "Mundo anterior"+ },+ "companion": {+ "title": "Tu compañero",+ "hint": "Tu imagen de perfil sigue a tu personaje en el mapa. Personaliza el personaje y su compañero por separado.",+ "appearance": "Personaje y compañero",+ "character": "Personaje",+ "companion": "Compañero",+ "shape": "Forma",+ "color": "Color",+ "custom_color": "Color personalizado",+ "eyes": "Ojos",+ "dots": "Ojos redondos",+ "lines": "Ojos de línea",+ "visible": "Seguir en el mapa",+ "shapes": {+ "circle": "Círculo",+ "squircle": "Cuadrado suave",+ "pill": "Cápsula",+ "triangle": "Triángulo",+ "hexagon": "Hexágono",+ "cloud": "Nube",+ "drop": "Gota"+ }}}}diff --git a/jarvis/ui/web/frontend/src/index.css b/jarvis/ui/web/frontend/src/index.cssindex 3dfd4faf06..e6f5c5f173 100644--- a/jarvis/ui/web/frontend/src/index.css+++ b/jarvis/ui/web/frontend/src/index.css@@ -950,6 +950,23 @@ body {background: hsl(var(--sidebar));}+ /*+ * The reading surface under the gray window bar.+ *+ * The fill, the stroke and the corner are one box, so the line bends with+ * the corner instead of staying square while the fill curves under it.+ * Children are clipped to that same corner.+ */+ .jarvis-sheet {+ min-width: 0;+ min-height: 0;+ overflow: hidden;+ border-top: 1px solid hsl(var(--border));+ border-left: 1px solid hsl(var(--border));+ border-top-left-radius: 12px;+ background: hsl(var(--background));+ }+.jarvis-shell-surface {background: hsl(var(--background));}diff --git a/jarvis/ui/web/frontend/src/lib/agentChatApi.ts b/jarvis/ui/web/frontend/src/lib/agentChatApi.tsindex 8589d2c5f9..b8da28c237 100644--- a/jarvis/ui/web/frontend/src/lib/agentChatApi.ts+++ b/jarvis/ui/web/frontend/src/lib/agentChatApi.ts@@ -93,6 +93,7 @@ export interface AgentChatSession {permission_mode: string;/** Absent on a backend older than the surface split; the store keeps such rows. */surface?: AgentChatSurface;+ account_id?: string;vendor_session: string | null;created_ms: number;updated_ms: number;@@ -188,8 +189,16 @@ async function json<T>(res: Response, what: string): Promise<T> {// caching completed requests: explicit refreshes must still reach the server.const catalogRequests = new Map<string, Promise<AgentChatCatalog>>();-export function fetchAgentChatCatalog(surface?: AgentChatSurface): Promise<AgentChatCatalog> {- const query = surface ? `?surface=${encodeURIComponent(surface)}` : "";+export function fetchAgentChatCatalog(+ surface?: AgentChatSurface,+ scope: { accountId?: string; sessionId?: string; cwd?: string } = {},+): Promise<AgentChatCatalog> {+ const params = new URLSearchParams();+ if (surface) params.set("surface", surface);+ if (scope.accountId) params.set("account_id", scope.accountId);+ if (scope.sessionId) params.set("session_id", scope.sessionId);+ if (scope.cwd) params.set("cwd", scope.cwd);+ const query = params.size ? `?${params}` : "";const pending = catalogRequests.get(query);if (pending) return pending;const request = fetch(`/api/agent-chat/catalog${query}`)diff --git a/jarvis/ui/web/frontend/src/lib/agentChatCatalogRequests.test.ts b/jarvis/ui/web/frontend/src/lib/agentChatCatalogRequests.test.tsindex c95932434f..2dcc5e65d8 100644--- a/jarvis/ui/web/frontend/src/lib/agentChatCatalogRequests.test.ts+++ b/jarvis/ui/web/frontend/src/lib/agentChatCatalogRequests.test.ts@@ -43,3 +43,21 @@ test("a rejected discovery request is released so a later retry can succeed", asawait expect(fetchAgentChatCatalog("society")).resolves.toEqual({ providers: [] });expect(request).toHaveBeenCalledTimes(2);});+++test("catalog requests are isolated by account, session and working folder", async () => {+ const request = vi.fn(async (_url: string) => ({ ok: true, json: async () => ({ providers: [] }) }) as Response);+ vi.stubGlobal("fetch", request);+ const first = fetchAgentChatCatalog("society", { accountId: "one" });+ const same = fetchAgentChatCatalog("society", { accountId: "one" });+ const second = fetchAgentChatCatalog("society", { accountId: "two" });+ const session = fetchAgentChatCatalog("society", { sessionId: "chat-two", cwd: "/project" });+ expect(first).toBe(same);+ expect(first).not.toBe(second);+ await Promise.all([first, second, session]);+ expect(request.mock.calls.map(([url]) => url)).toEqual([+ "/api/agent-chat/catalog?surface=society&account_id=one",+ "/api/agent-chat/catalog?surface=society&account_id=two",+ "/api/agent-chat/catalog?surface=society&session_id=chat-two&cwd=%2Fproject",+ ]);+});diff --git a/jarvis/ui/web/frontend/src/lib/homeTranscript.ts b/jarvis/ui/web/frontend/src/lib/homeTranscript.tsindex d025724025..af033eb8a5 100644--- a/jarvis/ui/web/frontend/src/lib/homeTranscript.ts+++ b/jarvis/ui/web/frontend/src/lib/homeTranscript.ts@@ -39,6 +39,7 @@ import {reduceThinkingSteps,type ThinkingStep,} from "@/lib/thinkingSteps";+import { readVoiceTranscript } from "@/lib/liveTranscript";export type TranscriptWho = "user" | "assistant" | "steps";@@ -59,6 +60,7 @@ export interface TranscriptTextLine extends TranscriptLineBase {* follows the tool call.*/kind?: string;+ revision?: number;}/** The reasoning steps of one turn — tools, workers, the brain call. */@@ -386,6 +388,22 @@ export function reduceTranscript(lines = closeStaleTurn(lines, tsMs);switch (name) {+ case "VoiceTranscriptUpdated": {+ const snapshot = readVoiceTranscript(payload);+ if (!snapshot || !snapshot.text.trim()) return lines;+ const id = `live:${snapshot.session_id}:${snapshot.segment_id}`;+ const index = lines.findIndex(line => line.id === id);+ if (index >= 0) {+ const previous = lines[index] as TranscriptTextLine;+ if ((previous.revision ?? 0) >= snapshot.revision) return lines;+ return replaceAt(lines, index, { ...previous, text: snapshot.text, revision: snapshot.revision });+ }+ // Captions are independent of model turns and can overlap a running+ // tool. A new user segment must not mark background work as complete.+ return cap([...lines, {+ id, ts: tsMs, who: snapshot.role, text: snapshot.text, revision: snapshot.revision,+ }]);+ }case "TranscriptFinal": {const transcript = (p.transcript ?? {}) as Record<string, unknown>;const text = clean(transcript.text);@@ -435,6 +453,12 @@ export function reduceTranscript(// assistant spoke: whatever the turn was doing, it is over.const next = str(p.new_state).toLowerCase();const previous = str(p.previous).toLowerCase();+ const continuous = lines.some(line => line.who !== "steps" && line.revision !== undefined);+ if (continuous && next === "listening" && previous === "speaking") {+ // GPT-Live can listen while delegated work is still running. Only+ // the model/tool completion events settle that work, not playback.+ return lines;+ }if (next === "idle" || (next === "listening" && previous === "speaking")) {return closeOpenTurn(lines, tsMs);}diff --git a/jarvis/ui/web/frontend/src/lib/liveTranscript.test.ts b/jarvis/ui/web/frontend/src/lib/liveTranscript.test.tsnew file mode 100644index 0000000000..35a346109f--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/liveTranscript.test.ts@@ -0,0 +1,49 @@+import { describe, expect, it } from "vitest";+import { reduceTranscript, type TranscriptLine } from "./homeTranscript";+import { useHomeStore } from "@/store/home";+import { useEventStore } from "@/store/events";++function caption(segment_id: string, role: "user" | "assistant", text: string, revision = 1) {+ return { session_id: "call", segment_id, role, text, start_ms: 0, end_ms: 500, revision };+}++describe("continuous voice conversation", () => {+ it("does not mark delegated work complete when the user interrupts speech", () => {+ let lines = reduceTranscript([], "VoiceTranscriptUpdated", caption("u", "user", "Read settings"), 1);+ lines = reduceTranscript(lines, "BrainTurnStarted", { model: "chosen" }, 2);+ lines = reduceTranscript(lines, "SystemStateChanged", { previous: "SPEAKING", new_state: "LISTENING" }, 3);+ const trace = lines.find(line => line.who === "steps");+ expect(trace?.who === "steps" && trace.live).toBe(true);+ expect(trace?.who === "steps" && trace.steps[0].status).toBe("active");+ });+ it("keeps user, trace and assistant rows while successive snapshots grow in place", () => {+ let lines: TranscriptLine[] = [];+ lines = reduceTranscript(lines, "VoiceTranscriptUpdated", caption("u1", "user", "Read settings"), 1);+ lines = reduceTranscript(lines, "BrainTurnStarted", { model: "chosen" }, 2);+ lines = reduceTranscript(lines, "ReasoningSummaryUpdated", { response_id: "r", text: "Checking the setting", done: true }, 3);+ lines = reduceTranscript(lines, "BrainTurnCompleted", { model: "chosen" }, 4);+ lines = reduceTranscript(lines, "VoiceTranscriptUpdated", caption("a1", "assistant", "It is"), 5);+ lines = reduceTranscript(lines, "VoiceTranscriptUpdated", caption("a1", "assistant", "It is enabled", 2), 6);+ lines = reduceTranscript(lines, "VoiceTranscriptUpdated", caption("u2", "user", "Read settings"), 7);+ lines = reduceTranscript(lines, "VoiceTranscriptUpdated", caption("a2", "assistant", "Still enabled"), 8);+ expect(lines.map(line => line.who)).toEqual(["user", "steps", "assistant", "user", "assistant"]);+ expect(lines[2].text).toBe("It is enabled");+ const duplicate = reduceTranscript(lines, "VoiceTranscriptUpdated", caption("a1", "assistant", "old", 1), 9);+ expect(duplicate).toBe(lines);+ const trace = lines[1];+ expect(trace.who === "steps" && trace.steps.some(step => step.detail === "Checking the setting")).toBe(true);+ });++ it("ignores late captions and hangups from the previous session", () => {+ const home = useHomeStore.getState();+ home.resetTranscript();+ home.ingest("VoiceSessionStarted", { session_id: "call" }, 1);+ useEventStore.getState().setTranscription("legacy preview", false);+ home.ingest("VoiceTranscriptUpdated", caption("u", "user", "Hello"), 2);+ expect(useEventStore.getState().transcription).toBe("");+ home.ingest("VoiceTranscriptUpdated", { ...caption("old", "user", "Stale"), session_id: "old" }, 3);+ home.ingest("VoiceSessionEnded", { session_id: "old" }, 4);+ expect(useHomeStore.getState().transcript.map(line => line.text)).toEqual(["Hello"]);+ home.resetTranscript();+ });+});diff --git a/jarvis/ui/web/frontend/src/lib/liveTranscript.ts b/jarvis/ui/web/frontend/src/lib/liveTranscript.tsnew file mode 100644index 0000000000..e0674fa780--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/liveTranscript.ts@@ -0,0 +1,27 @@+/** Mirrors the persisted VoiceTranscriptUpdated payload. */+export interface VoiceTranscriptSnapshot {+ session_id: string;+ segment_id: string;+ role: "user" | "assistant";+ text: string;+ start_ms: number;+ end_ms: number;+ revision: number;+}++export interface ReasoningSummarySnapshot {+ response_id: string;+ text: string;+ done: boolean;+}++export function readVoiceTranscript(value: unknown): VoiceTranscriptSnapshot | null {+ if (!value || typeof value !== "object") return null;+ const p = value as Record<string, unknown>;+ if (typeof p.session_id !== "string" || !p.session_id ||+ typeof p.segment_id !== "string" || !p.segment_id ||+ (p.role !== "user" && p.role !== "assistant") || typeof p.text !== "string" ||+ !Number.isInteger(p.revision) || Number(p.revision) < 1 ||+ !Number.isFinite(p.start_ms) || !Number.isFinite(p.end_ms)) return null;+ return p as unknown as VoiceTranscriptSnapshot;+}diff --git a/jarvis/ui/web/frontend/src/lib/mediaLevels.test.ts b/jarvis/ui/web/frontend/src/lib/mediaLevels.test.tsnew file mode 100644index 0000000000..413abbac9d--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/mediaLevels.test.ts@@ -0,0 +1,44 @@+import { afterEach, expect, it } from "vitest";+import { MediaActivity } from "./mediaLevels";+import { setBrowserPlaybackActive, setBrowserVoiceOutputOwnership } from "./voiceOutputLevel";+import { useEventStore } from "@/store/events";++afterEach(() => {+ setBrowserVoiceOutputOwnership(false);+ useEventStore.getState().setVoice("idle");+});++it("keeps audible playback above delayed thinking and listening messages", () => {+ setBrowserVoiceOutputOwnership(true);+ setBrowserPlaybackActive(true);+ useEventStore.getState().setVoice("thinking");+ expect(useEventStore.getState().voiceState).toBe("speaking");+ useEventStore.getState().setVoice("listening");+ expect(useEventStore.getState().voiceState).toBe("speaking");+ setBrowserPlaybackActive(false);+ useEventStore.getState().setVoice("thinking");+ expect(useEventStore.getState().voiceState).toBe("thinking");+});++it("never hides errors, hangups or connection loss behind playback", () => {+ setBrowserVoiceOutputOwnership(true);+ setBrowserPlaybackActive(true);+ for (const state of ["error", "idle", "connecting"] as const) {+ useEventStore.getState().setVoice(state);+ expect(useEventStore.getState().voiceState).toBe(state);+ }+ setBrowserVoiceOutputOwnership(false);+ useEventStore.getState().setVoice("listening");+ expect(useEventStore.getState().voiceState).toBe("listening");+});++it("does not turn word gaps into repeated speaking/thinking changes", () => {+ const voice = new MediaActivity(0.004, 21);+ expect(voice.update(0.1)).toBe(true);+ for (let i = 0; i < 20; i++) expect(voice.update(0)).toBe(false);+ expect(voice.active).toBe(true);+ expect(voice.update(0.1)).toBe(false);+ for (let i = 0; i < 20; i++) voice.update(0);+ expect(voice.update(0)).toBe(true);+ expect(voice.active).toBe(false);+});diff --git a/jarvis/ui/web/frontend/src/lib/mediaLevels.ts b/jarvis/ui/web/frontend/src/lib/mediaLevels.tsnew file mode 100644index 0000000000..d619e4f7b0--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/mediaLevels.ts@@ -0,0 +1,32 @@+/** Ephemeral /ws/audio snapshot. Values are normalized, never PCM or text. */+export interface MediaLevels {+ type: "media_levels";+ input_level: number;+ output_level: number;+ input_active: boolean;+ playback_active: boolean;+}++/** Audio-clock hysteresis: short gaps between words keep the speaking look. */+export class MediaActivity {+ active = false;+ private quietFrames = 0;++ constructor(private threshold: number, private hangoverFrames: number) {}++ update(rms: number): boolean {+ const previous = this.active;+ if (Number.isFinite(rms) && rms > this.threshold) {+ this.quietFrames = 0;+ this.active = true;+ } else if (++this.quietFrames >= this.hangoverFrames) {+ this.active = false;+ }+ return previous !== this.active;+ }++ reset(): void {+ this.active = false;+ this.quietFrames = 0;+ }+}diff --git a/jarvis/ui/web/frontend/src/lib/pcm-worklet.ts b/jarvis/ui/web/frontend/src/lib/pcm-worklet.tsindex ce20af4ca2..8360c1f63e 100644--- a/jarvis/ui/web/frontend/src/lib/pcm-worklet.ts+++ b/jarvis/ui/web/frontend/src/lib/pcm-worklet.ts@@ -5,6 +5,7 @@// script these ambient declarations would otherwise leak into the rest of the// app's type-check).import { JitterBufferedPcm16Queue, Pcm16Packetizer } from "./pcmWorkletBuffer";+import { StartupAudioQueue } from "./startupAudio";export {};@@ -48,6 +49,39 @@ class PcmCapture extends AudioWorkletProcessor {}}+class StartupCapture extends AudioWorkletProcessor {+ private queue = new StartupAudioQueue(sampleRate);+ private failed = false;++ constructor() {+ super();+ this.port.onmessage = (event: MessageEvent) => {+ try {+ if (event.data.type === "start") this.queue.start();+ else if (event.data.type === "suspend") this.queue.suspend();+ else if (event.data.type === "prefix") this.queue.prepend(event.data.samples);+ } catch (error) { this.fail(error); }+ };+ }++ private fail(error: unknown): void {+ this.failed = true;+ this.queue.suspend();+ this.port.postMessage({ type: "error", message: String(error) });+ }++ process(inputs: Float32Array[][], outputs: Float32Array[][]): boolean {+ const output = outputs[0]?.[0];+ if (!output) return true;+ if (this.failed) { output.fill(0); return true; }+ try { this.queue.process(inputs[0]?.[0] ?? new Float32Array(output.length), output); }+ catch (error) { this.fail(error); }+ return true;+ }+}++registerProcessor("pcm-startup", StartupCapture);+class PcmPlayback extends AudioWorkletProcessor {private readonly queue = new JitterBufferedPcm16Queue(sampleRate);private levelSum = 0;@@ -94,5 +128,30 @@ class PcmPlayback extends AudioWorkletProcessor {}}+// A meter on the audio render thread keeps reporting while the WebView is+// hidden. requestAnimationFrame stops in background windows and cannot own+// the desktop's speaking/listening transitions.+class PcmLevel extends AudioWorkletProcessor {+ private sum = 0;+ private count = 0;++ process(inputs: Float32Array[][], outputs: Float32Array[][]): boolean {+ const input = inputs[0]?.[0];+ const size = input?.length ?? outputs[0]?.[0]?.length ?? 128;+ if (input) {+ for (const sample of input) this.sum += sample * sample;+ }+ this.count += size;+ if (this.count >= sampleRate / 30) {+ this.port.postMessage({ type: "level", rms: Math.sqrt(this.sum / this.count) });+ this.sum = 0;+ this.count = 0;+ }+ // Output remains silent; the HTML audio element owns audible playback.+ return true;+ }+}+registerProcessor("pcm-capture", PcmCapture);registerProcessor("pcm-playback", PcmPlayback);+registerProcessor("pcm-level", PcmLevel);diff --git a/jarvis/ui/web/frontend/src/lib/pcmLevel.test.ts b/jarvis/ui/web/frontend/src/lib/pcmLevel.test.tsnew file mode 100644index 0000000000..06f8a9a7a9--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/pcmLevel.test.ts@@ -0,0 +1,28 @@+import { afterEach, expect, it, vi } from "vitest";++afterEach(() => vi.unstubAllGlobals());++it("measures remote audio on the render thread without animation frames or audible duplication", async () => {+ const messages: { type: string; rms: number }[] = [];+ const processors = new Map<string, new () => { process(inputs: Float32Array[][], outputs: Float32Array[][]): boolean }>();+ vi.stubGlobal("sampleRate", 48_000);+ vi.stubGlobal("AudioWorkletProcessor", class {+ port = { postMessage: (message: { type: string; rms: number }) => messages.push(message) };+ });+ vi.stubGlobal("registerProcessor", (name: string, processor: never) => processors.set(name, processor));+ // A hidden WebView does not deliver animation callbacks. Audio still does.+ const animate = vi.fn();+ vi.stubGlobal("requestAnimationFrame", animate);+ await import("./pcm-worklet");+ const Meter = processors.get("pcm-level")!;+ const meter = new Meter();+ const output = new Float32Array(128);+ for (let frame = 0; frame < 13; frame++) {+ expect(meter.process([[new Float32Array(128).fill(0.125)]], [[output]])).toBe(true);+ }+ expect(messages).toEqual([{ type: "level", rms: 0.125 }]);+ expect(output.every(sample => sample === 0)).toBe(true);+ for (let frame = 0; frame < 13; frame++) meter.process([], [[output]]);+ expect(messages.at(-1)).toEqual({ type: "level", rms: 0 });+ expect(animate).not.toHaveBeenCalled();+});diff --git a/jarvis/ui/web/frontend/src/lib/realtimeAudio.test.ts b/jarvis/ui/web/frontend/src/lib/realtimeAudio.test.tsindex db98f8e5e2..0cc026cfb8 100644--- a/jarvis/ui/web/frontend/src/lib/realtimeAudio.test.ts+++ b/jarvis/ui/web/frontend/src/lib/realtimeAudio.test.ts@@ -21,7 +21,7 @@ class FakeAudioNode {connect = vi.fn(() => this);disconnect = vi.fn();- constructor() {+ constructor(_context?: unknown, readonly name?: string) {FakeAudioNode.instances.push(this);}}@@ -34,15 +34,21 @@ class FakeAudioContext {close = vi.fn(async () => undefined);createMediaStreamSource = vi.fn(() => new FakeAudioNode());createGain = vi.fn(() => Object.assign(new FakeAudioNode(), { gain: { value: 1 } }));+ createMediaStreamDestination = vi.fn(() => Object.assign(new FakeAudioNode(), {+ stream: { getAudioTracks: () => ["buffered-track"], getTracks: () => [] },+ }));}class FakePeerConnection {static instances: FakePeerConnection[] = [];+ static offerSdp = "offer-sdp";iceGatheringState: RTCIceGatheringState = "complete";localDescription: RTCSessionDescription | null = null;remoteDescriptions: RTCSessionDescriptionInit[] = [];addTransceiver = vi.fn();- createDataChannel = vi.fn();+ addTrack = vi.fn();+ channel = Object.assign(new EventTarget(), { close: vi.fn() });+ createDataChannel = vi.fn(() => this.channel);close = vi.fn();addEventListener = vi.fn();removeEventListener = vi.fn();@@ -52,12 +58,13 @@ class FakePeerConnection {FakePeerConnection.instances.push(this);}- createOffer = vi.fn(async () => ({ type: "offer" as const, sdp: "offer-sdp" }));+ createOffer = vi.fn(async () => ({ type: "offer" as const, sdp: FakePeerConnection.offerSdp }));setLocalDescription = vi.fn(async (description: RTCSessionDescriptionInit) => {this.localDescription = description as RTCSessionDescription;});setRemoteDescription = vi.fn(async (description: RTCSessionDescriptionInit) => {this.remoteDescriptions.push(description);+ this.channel.dispatchEvent(new MessageEvent("message", { data: '{"type":"session.started"}' }));});}@@ -65,6 +72,7 @@ class FakeWebSocket {static OPEN = 1;static instances: FakeWebSocket[] = [];readyState = 0;+ bufferedAmount = 0;binaryType = "";sent: unknown[] = [];onopen: (() => void) | null = null;@@ -103,7 +111,7 @@ class FakeWebSocket {function installVoiceBrowserFakes() {const track = { stop: vi.fn() };vi.stubGlobal("navigator", {- mediaDevices: { getUserMedia: vi.fn(async () => ({ getTracks: () => [track] })) },+ mediaDevices: { getUserMedia: vi.fn(async () => ({ getTracks: () => [track], getAudioTracks: () => [track] })) },});vi.stubGlobal("AudioContext", FakeAudioContext);vi.stubGlobal("AudioWorkletNode", FakeAudioNode);@@ -113,6 +121,124 @@ function installVoiceBrowserFakes() {}describe("realtime audio client", () => {+ it("uses buffered RTP and forwards input levels before the media handshake completes", async () => {+ installVoiceBrowserFakes();+ vi.stubGlobal("Audio", class { play = async () => undefined; pause = () => undefined; });+ const client = new RealtimeAudioClient({}, { browserAudio: true, requiresWebRtcOffer: true });+ const connecting = client.connect();+ await vi.waitFor(() => expect(FakeWebSocket.instances).toHaveLength(1));+ const socket = FakeWebSocket.instances[0];+ const peer = FakePeerConnection.instances[0];+ const gate = FakeAudioNode.instances.find(node => node.name === "pcm-startup")!;+ const capture = FakeAudioNode.instances.find(node => node.name === "pcm-capture")!;+ expect(peer.addTrack.mock.calls[0][0]).toBe("buffered-track");+ expect(gate.port.postMessage).not.toHaveBeenCalled();+ socket.open();+ expect(JSON.parse(String(socket.sent[0])).capture_started_at_ms).toBeGreaterThan(0);+ socket.receive({ type: "input_prefix", sample_rate: 48000, audio: "AQACAA==" });+ expect(gate.port.postMessage.mock.calls[0][0].type).toBe("prefix");+ let release!: () => void;+ peer.setRemoteDescription = vi.fn(async () => { await new Promise<void>(resolve => { release = resolve; }); });+ socket.receive({ type: "audio_ready", requires_webrtc_answer: true, webrtc_answer_sdp: "answer" });+ capture.port.onmessage!({ data: { type: "level", rms: 0.2 } } as MessageEvent);+ expect(socket.sent.map(v => JSON.parse(String(v))).at(-1)).toMatchObject({ type: "media_levels", input_active: true });+ expect(gate.port.postMessage.mock.calls.some(([m]) => m.type === "start")).toBe(false);+ peer.channel.dispatchEvent(new MessageEvent("message", { data: '{"type":"session.started"}' }));+ release();+ await connecting;+ expect(gate.port.postMessage.mock.calls.filter(([m]) => m.type === "start")).toHaveLength(1);+ socket.receive({ type: "reconnecting" });+ expect(gate.port.postMessage).toHaveBeenLastCalledWith({ type: "suspend" });+ socket.receive({ type: "audio_closed" });+ await client.disconnect();+ });++ it("precedes browser PCM with native wake audio on the local/Gemini path", async () => {+ installVoiceBrowserFakes();+ const client = new RealtimeAudioClient({}, { browserAudio: true });+ const connecting = client.connect();+ await vi.waitFor(() => expect(FakeWebSocket.instances).toHaveLength(1));+ const socket = FakeWebSocket.instances[0];+ socket.open();+ const capture = FakeAudioNode.instances.find(node => node.name === "pcm-capture")!;+ capture.port.onmessage!({ data: new Int16Array([3, 4]).buffer } as MessageEvent);+ socket.receive({ type: "input_prefix", sample_rate: 48000, audio: "AQACAA==" });+ socket.receive({ type: "audio_ready", requires_webrtc_answer: false });+ await connecting;+ expect(socket.sent.filter(v => v instanceof ArrayBuffer).map(v => [...new Int16Array(v as ArrayBuffer)])).toEqual([[1, 2], [3, 4]]);+ socket.receive({ type: "audio_closed" });+ await client.disconnect();+ });++ it.each([true, false])("forwards measured microphone/output levels and releases them on close (WebRTC=%s)", async (webrtc) => {+ installVoiceBrowserFakes();+ vi.stubGlobal("Audio", class { play = async () => undefined; pause = () => undefined; });+ const onPlaybackState = vi.fn();+ const onStatus = vi.fn();+ const onAudio = vi.fn();+ const client = new RealtimeAudioClient({ onPlaybackState, onStatus, onAudio }, { browserAudio: true, requiresWebRtcOffer: webrtc });+ const connecting = client.connect();+ await vi.waitFor(() => expect(FakeWebSocket.instances).toHaveLength(1));+ const socket = FakeWebSocket.instances[0];+ socket.open();+ socket.receive({ type: "audio_ready", requires_webrtc_answer: webrtc, ...(webrtc ? { webrtc_answer_sdp: "answer" } : {}) });+ await connecting;+ if (webrtc) {+ FakePeerConnection.instances[0].ontrack?.({ streams: [{}] } as unknown as RTCTrackEvent);+ } else {+ socket.receiveBinary(new Int16Array(4800).buffer);+ expect(onAudio).not.toHaveBeenCalled();+ }+ const capture = FakeAudioNode.instances.find(node => node.name === "pcm-capture")!;+ const output = FakeAudioNode.instances.find(node => node.name === (webrtc ? "pcm-level" : "pcm-playback"))!;+ const emit = (node: FakeAudioNode, rms: number) => node.port.onmessage?.({ data: { type: "level", rms } } as MessageEvent);+ const frames = () => socket.sent.map(value => JSON.parse(String(value))).filter(value => value.type === "media_levels");+ const tick = performance.now() + 100;+ const clock = vi.spyOn(performance, "now").mockReturnValue(tick);+ try {+ emit(capture, 0.12);+ expect(frames().at(-1)).toMatchObject({ input_active: true, playback_active: false });+ expect(frames().at(-1).input_level).toBeGreaterThan(0);+ emit(output, 0.1);+ expect(onPlaybackState).toHaveBeenLastCalledWith(true);+ expect(frames().at(-1).output_level).toBeGreaterThan(0);+ expect(frames().at(-1).playback_active).toBe(true);+ const count = frames().length;+ for (let i = 0; i < 20; i++) emit(capture, 0.12);+ expect(frames()).toHaveLength(count);+ clock.mockReturnValue(tick + 101);+ emit(capture, 0.12);+ expect(frames()).toHaveLength(count + 1);+ for (let i = 0; i < 20; i++) emit(output, 0);+ expect(onPlaybackState).toHaveBeenLastCalledWith(true);+ emit(output, 0);+ expect(onPlaybackState).toHaveBeenLastCalledWith(false);+ expect(frames().at(-1).playback_active).toBe(false);+ // The backend decides whether silence means thinking or listening.+ expect(onStatus.mock.calls.some(([status]) => status === "listening")).toBe(false);+ const beforeStall = frames().length;+ socket.bufferedAmount = 2048;+ clock.mockReturnValue(tick + 201);+ emit(output, 0.1);+ expect(frames()).toHaveLength(beforeStall);+ socket.bufferedAmount = 0;+ clock.mockReturnValue(tick + 202);+ emit(capture, 0.12);+ expect(frames()).toHaveLength(beforeStall + 1);+ expect(frames().at(-1).playback_active).toBe(true);+ const staleMeter = output.port.onmessage!;+ const closing = client.disconnect();+ socket.receive({ type: "audio_closed" });+ await closing;+ const sent = socket.sent.length;+ if (webrtc) staleMeter({ data: { type: "level", rms: 0.3 } } as MessageEvent);+ expect(socket.sent).toHaveLength(sent);+ expect(onPlaybackState).toHaveBeenLastCalledWith(false);+ } finally {+ clock.mockRestore();+ }+ });+beforeEach(() => {vi.stubGlobal("window", {location: { protocol: "https:", host: "app.example", hostname: "app.example" },@@ -122,6 +248,7 @@ describe("realtime audio client", () => {clearTimeout: globalThis.clearTimeout,});FakePeerConnection.instances = [];+ FakePeerConnection.offerSdp = "offer-sdp";FakeWebSocket.instances = [];FakeAudioNode.instances = [];wsFakes.mintWsTicket.mockClear();@@ -238,6 +365,8 @@ describe("realtime audio client", () => {it("sends a WebRTC offer and applies the matching answer while PCM stays active", async () => {const { track } = installVoiceBrowserFakes();+ const offerSdp = "v=0\r\no=- 123 1 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n";+ FakePeerConnection.offerSdp = offerSdp;const client = new RealtimeAudioClient({}, { requiresWebRtcOffer: true });const connecting = client.connect();@@ -248,7 +377,7 @@ describe("realtime audio client", () => {expect(start).toMatchObject({type: "audio_start",sample_rate: 48_000,- webrtc_offer_sdp: "offer-sdp",+ webrtc_offer_sdp: offerSdp,});expect(FakePeerConnection.instances[0].addTransceiver).toHaveBeenCalledWith("audio",diff --git a/jarvis/ui/web/frontend/src/lib/realtimeAudio.ts b/jarvis/ui/web/frontend/src/lib/realtimeAudio.tsindex 4a768a0f37..f065da86ce 100644--- a/jarvis/ui/web/frontend/src/lib/realtimeAudio.ts+++ b/jarvis/ui/web/frontend/src/lib/realtimeAudio.ts@@ -2,6 +2,7 @@// JSON-only WSClient: this socket carries raw mono PCM16 in both directions.import { LevelMeter } from "./levelMeter";+import { MediaActivity, type MediaLevels } from "./mediaLevels";import { requestConnect } from "./connectBudget";import { mintWsTicket } from "./ws";import pcmWorkletUrl from "./pcm-worklet.ts?worker&url";@@ -19,6 +20,7 @@ export type RealtimeCallbacks = {onTranscript?: (text: string, isFinal: boolean, role: string) => void;onStatus?: (status: string, payload: RealtimeStatusPayload) => void;onAudio?: () => void;+ onPlaybackState?: (active: boolean) => void;/** Normalized 0..1 microphone input level, ~30 Hz while capturing. */onInputLevel?: (level: number) => void;/**@@ -57,10 +59,10 @@ const DEFAULT_START_BUDGET_MS = 20_000;/*** Consecutive quiet analyser frames before the WebRTC voice tap reports- * listening (~700 ms at 60 fps). Word gaps must not flip the Jarvis bar+ * listening (~700 ms at 30 Hz). Word gaps must not flip the Jarvis bar* back to listening mid-sentence.*/-const REMOTE_SILENCE_HANGOVER_FRAMES = 42;+const REMOTE_SILENCE_HANGOVER_FRAMES = 21;/** Bounded startup pre-roll, mirroring the desktop's 30 s replay window.*@@ -370,6 +372,11 @@ export class RealtimeAudioClient {private captureSink: GainNode | null = null;private playbackNode: AudioWorkletNode | null = null;private stream: MediaStream | null = null;+ private startupNode: AudioWorkletNode | null = null;+ private rtcInput: MediaStreamAudioDestinationNode | null = null;+ private captureStartedAtMs = 0;+ private controlReady = false;+ private receivedPrefix = false;private playbackResampler: StreamingPcm16Resampler | null = null;private connecting: Promise<void> | null = null;private ready = false;@@ -402,52 +409,72 @@ export class RealtimeAudioClient {this.webRtcTransport = new RealtimeWebRtcTransport(stream => this.observeRemoteAudio(stream));}- private mediaFrame = 0;+ private remoteMeter: AudioWorkletNode | null = null;private remoteSource: MediaStreamAudioSourceNode | null = null;- private lastPlaybackActive = false;- private remoteSilenceFrames = 0;+ private outputActivity = new MediaActivity(0.004, REMOTE_SILENCE_HANGOVER_FRAMES);+ private inputActivity = new MediaActivity(0.008, 8);+ private inputLevel = 0;+ private outputLevel = 0;+ private lastMediaSendAt = Number.NEGATIVE_INFINITY;++ private sendMediaLevels(force = false): void {+ if (!this.options.browserAudio || !this.controlReady || this.intentionalClose || this.ws?.readyState !== WebSocket.OPEN) return;+ // Drop obsolete meter snapshots when the control transport stalls. The+ // next audio-clock tick sends current measurements after it drains.+ if (this.ws.bufferedAmount > 1024) return;+ const now = performance.now();+ if (!force && now - this.lastMediaSendAt < 100) return;+ const snapshot: MediaLevels = {+ type: "media_levels",+ input_level: this.inputLevel,+ output_level: this.outputLevel,+ input_active: this.inputActivity.active,+ playback_active: this.outputActivity.active,+ };+ this.ws.send(JSON.stringify(snapshot));+ this.lastMediaSendAt = now;+ }++ private observeOutputLevel(rms: number): void {+ this.outputLevel = this.outputMeter.push(rms);+ this.cb.onOutputLevel?.(this.outputLevel);+ const changed = this.outputActivity.update(rms);+ if (changed) {+ const active = this.outputActivity.active;+ this.cb.onPlaybackState?.(active);+ if (active) {+ this.cb.onAudio?.();+ this.cb.onStatus?.("speaking", {});+ }+ // Older Live servers still consume the edge. The level snapshot adds+ // microphone/output meters; only the server resolves the quiet phase.+ if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(JSON.stringify({ type: "playback_state", active }));+ }+ this.sendMediaLevels(changed);+ }private observeRemoteAudio(stream: MediaStream): void {if (!this.ctx) return;// A suspended context measures only zeros: the assistant would talk// while the bar keeps showing listening. The call started from a user// gesture, so resuming here is allowed and makes the tap truthful.- void this.ctx.resume().catch(() => undefined);- cancelAnimationFrame(this.mediaFrame);+ void this.ctx.resume().catch(error => console.warn("Voice meter could not resume", error));+ this.remoteMeter?.disconnect();+ if (this.remoteMeter) this.remoteMeter.port.onmessage = null;this.remoteSource?.disconnect();- this.lastPlaybackActive = false;- this.remoteSilenceFrames = 0;- const analyser = this.ctx.createAnalyser();- analyser.fftSize = 256;+ this.outputActivity.reset();+ this.cb.onPlaybackState?.(false);+ const meter = new AudioWorkletNode(this.ctx, "pcm-level");+ this.remoteMeter = meter;this.remoteSource = this.ctx.createMediaStreamSource(stream);- this.remoteSource.connect(analyser);- const samples = new Float32Array(analyser.fftSize);- const measure = () => {- analyser.getFloatTimeDomainData(samples);- const rms = Math.sqrt(samples.reduce((sum, x) => sum + x * x, 0) / samples.length);- this.cb.onOutputLevel?.(this.outputMeter.push(rms));- const active = rms > 0.004;- if (active) {- this.remoteSilenceFrames = 0;- if (!this.lastPlaybackActive) {- this.lastPlaybackActive = true;- this.cb.onAudio?.();- this.cb.onStatus?.("speaking", {});- if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(JSON.stringify({ type: "playback_state", active: true }));- }- } else if (this.lastPlaybackActive) {- // Word gaps are silence too: only report listening after the tail- // of the reply is really over, or the bar flickers mid-sentence.- this.remoteSilenceFrames += 1;- if (this.remoteSilenceFrames >= REMOTE_SILENCE_HANGOVER_FRAMES) {- this.lastPlaybackActive = false;- this.cb.onStatus?.("listening", {});- if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(JSON.stringify({ type: "playback_state", active: false }));- }- }- this.mediaFrame = requestAnimationFrame(measure);+ this.remoteSource.connect(meter);+ meter.connect(this.ctx.destination);+ meter.port.onmessage = (event: MessageEvent) => {+ if (this.remoteMeter !== meter || this.intentionalClose) return;+ const rms = event.data?.rms;+ if (event.data?.type !== "level" || typeof rms !== "number" || !Number.isFinite(rms)) return;+ this.observeOutputLevel(rms);};- measure();}connect(): Promise<void> {@@ -509,12 +536,19 @@ export class RealtimeAudioClient {const setupMs = Math.round(performance.now() - setupStartedAt);const source = this.ctx.createMediaStreamSource(this.stream);this.captureNode = new AudioWorkletNode(this.ctx, "pcm-capture");+ // Install capture before any offer/ticket/network await. No opening+ // frame may depend on the handshake finishing first.+ this.captureNode.port.onmessage = (event) => this.handleCapture(event);this.playbackNode = new AudioWorkletNode(this.ctx, "pcm-playback");this.playbackNode.port.onmessage = (event: MessageEvent) => {+ // RTP is measured by pcm-level. The unused PCM queue produces zeros+ // and must not erase the real output meter thirty times per second.+ if (this.options.browserAudio && this.options.requiresWebRtcOffer) return;const data = event.data as { type?: string; rms?: number } | null;if (data && data.type === "level" && typeof data.rms === "number") {const live = performance.now() - this.lastPcmAt <= OUTPUT_TAP_TTL_MS;- this.cb.onOutputLevel?.(live ? this.outputMeter.push(data.rms) : null);+ if (this.options.browserAudio) this.observeOutputLevel(live ? data.rms : 0);+ else this.cb.onOutputLevel?.(live ? this.outputMeter.push(data.rms) : null);}};// Keep the capture worklet in the active audio graph without feeding the@@ -522,10 +556,23 @@ export class RealtimeAudioClient {// node connected below and can remove it from captured audio.this.captureSink = this.ctx.createGain();this.captureSink.gain.value = 0;+ this.captureStartedAtMs = Date.now();source.connect(this.captureNode);this.captureNode.connect(this.captureSink);this.captureSink.connect(this.ctx.destination);this.playbackNode.connect(this.ctx.destination);+ if (this.options.browserAudio && this.options.requiresWebRtcOffer) {+ this.startupNode = new AudioWorkletNode(this.ctx, "pcm-startup");+ this.rtcInput = this.ctx.createMediaStreamDestination();+ this.rtcInput.channelCount = 1;+ source.connect(this.startupNode);+ this.startupNode.connect(this.rtcInput);+ this.startupNode.port.onmessage = (event: MessageEvent) => {+ if (event.data?.type !== "error" || this.intentionalClose) return;+ this.cb.onStatus?.("provider_error", { error: "Voice startup audio could not be retained. Please start again." });+ void this.disconnect();+ };+ }// Required transport bootstrap for subscription-backed Realtime. API// providers do not set this option and continue to use the PCM socket@@ -533,7 +580,7 @@ export class RealtimeAudioClient {// without its WebRTC peer, so this path fails closed.if (this.options.requiresWebRtcOffer) {const result = this.options.browserAudio- ? { sdp: await this.webRtcTransport.createOffer(this.stream), error: null }+ ? { sdp: await this.webRtcTransport.createOffer(this.rtcInput?.stream ?? this.stream), error: null }: await webRtcOffer;if (result?.error) {this.webRtcTransport.close();@@ -562,22 +609,6 @@ export class RealtimeAudioClient {if (this.intentionalClose) throw new Error("Voice start cancelled");this.ws = new WebSocket(buildAudioSocketUrl(ticket));this.ws.binaryType = "arraybuffer";- this.captureNode.port.onmessage = (event) => {- const data = event.data as ArrayBuffer | { type?: string; rms?: number };- if (data instanceof ArrayBuffer) {- if (this.options.browserAudio && this.options.requiresWebRtcOffer) return;- if (this.ready && this.ws?.readyState === WebSocket.OPEN) {- this.ws.send(data);- } else if (!this.ready && !this.reconnecting) {- this.retainStartupFrame(data);- }- return;- }- if (data && data.type === "level" && typeof data.rms === "number") {- this.cb.onInputLevel?.(this.inputMeter.push(data.rms));- }- };-await this.waitUntilReady(this.ws);} catch (error) {await this.teardown(false);@@ -585,6 +616,26 @@ export class RealtimeAudioClient {}}+ private handleCapture(event: MessageEvent): void {+ if (this.intentionalClose) return;+ const data = event.data as ArrayBuffer | { type?: string; rms?: number };+ if (data instanceof ArrayBuffer) {+ if (this.options.browserAudio && this.options.requiresWebRtcOffer) return;+ if (this.ready && this.ws?.readyState === WebSocket.OPEN) {+ this.ws.send(data);+ } else if (!this.ready && !this.reconnecting) {+ this.retainStartupFrame(data);+ }+ return;+ }+ if (data && data.type === "level" && typeof data.rms === "number") {+ this.inputLevel = this.inputMeter.push(data.rms);+ this.cb.onInputLevel?.(this.inputLevel);+ const changed = this.inputActivity.update(data.rms);+ this.sendMediaLevels(changed);+ }+ }+private waitUntilReady(socket: WebSocket): Promise<void> {// Never shorter than the historical budget, and long enough for whatever// the active provider chain declared it needs. A cold subscription@@ -616,6 +667,7 @@ export class RealtimeAudioClient {JSON.stringify({type: "audio_start",sample_rate: this.ctx?.sampleRate ?? 48_000,+ capture_started_at_ms: this.captureStartedAtMs,...(this.webRtcOfferSdp? { webrtc_offer_sdp: this.webRtcOfferSdp }: {}),@@ -651,11 +703,16 @@ export class RealtimeAudioClient {} else if (type === "reconnecting") {this.reconnecting = true;this.ready = false;+ this.controlReady = false;+ this.startupNode?.port.postMessage({ type: "suspend" });+ this.outputActivity.reset();+ this.inputActivity.reset();+ this.cb.onPlaybackState?.(false);this.startupPreroll = [];this.startupPrerollBytes = 0;this.playbackNode?.port.postMessage({ type: "flush" });} else if (type === "reconnect_offer") {- void this.webRtcTransport.createOffer(this.stream ?? undefined).then(sdp => {+ void this.webRtcTransport.createOffer(this.rtcInput?.stream ?? this.stream ?? undefined).then(sdp => {if (sdp && socket.readyState === WebSocket.OPEN && !this.intentionalClose) {socket.send(JSON.stringify({ type: "reconnect_offer", request_id: message.request_id, sdp }));}@@ -664,6 +721,7 @@ export class RealtimeAudioClient {this.cb.onStatus?.("provider_error", { error: "Voice reconnection failed." });});} else if (type === "audio_stopping") {+ this.startupNode?.port.postMessage({ type: "suspend" });this.webRtcTransport.muteOutput();this.stream?.getAudioTracks().forEach(track => { track.enabled = false; });} else if (type === "audio_closed") {@@ -673,12 +731,31 @@ export class RealtimeAudioClient {this.browserSpeech.cancel();this.playbackResampler?.reset();this.playbackNode?.port.postMessage({ type: "flush" });+ if (this.options.browserAudio && !this.options.requiresWebRtcOffer) {+ this.outputActivity.reset();+ this.outputLevel = 0;+ this.cb.onPlaybackState?.(false);+ this.sendMediaLevels(true);+ }+ } else if (type === "input_prefix") {+ try { this.receiveInputPrefix(message); }+ catch (error) {+ fail(error instanceof Error ? error : new Error(String(error)));+ socket.close();+ }+ return;} else if (type === "audio_ready") {+ // The local control channel can already relay levels while RTP+ // finishes its handshake. Native and browser bars share this input.+ this.controlReady = true;+ this.sendMediaLevels(true);this.setOutputRate(message.output_sample_rate);void this.finishAudioReady(message).then(() => {this.ready = true;+ this.startupNode?.port.postMessage({ type: "start" });this.reconnecting = false;+ this.sendMediaLevels(true);this.flushStartupPreroll();if (!settled) {settled = true;@@ -731,6 +808,33 @@ export class RealtimeAudioClient {}}+ private receiveInputPrefix(message: RealtimeStatusPayload): void {+ if (this.ready || this.reconnecting || this.receivedPrefix || !this.ctx) {+ throw new Error("Unexpected wake audio prefix");+ }+ const rate = message.sample_rate;+ const encoded = message.audio;+ if (typeof rate !== "number" || !Number.isInteger(rate) || rate < 8_000 || rate > 192_000 ||+ typeof encoded !== "string" || encoded.length > rate * 2 * 30 * 4 / 3 + 4) {+ throw new Error("Invalid wake audio prefix");+ }+ const raw = atob(encoded);+ if (raw.length % 2) throw new Error("Invalid wake PCM16 prefix");+ const bytes = Uint8Array.from(raw, char => char.charCodeAt(0));+ const resampler = new StreamingPcm16Resampler(rate, this.ctx.sampleRate);+ const pcm = resampler.process(bytes.buffer);+ this.receivedPrefix = true;+ if (this.startupNode) {+ const samples = Float32Array.from(new Int16Array(pcm), value => value / 32768);+ this.startupNode.port.postMessage({ type: "prefix", samples }, [samples.buffer]);+ } else {+ // Gemini/local use the existing PCM socket, with the same once-only+ // prefix ahead of the browser's already retained opening.+ this.startupPreroll.unshift(pcm);+ this.startupPrerollBytes += pcm.byteLength;+ }+ }+/** Replay the retained opening once the socket accepts audio. */private flushStartupPreroll(): void {const retained = this.startupPreroll;@@ -789,7 +893,7 @@ export class RealtimeAudioClient {if (converted.byteLength === 0) return;this.playbackNode?.port.postMessage({ type: "pcm", data: converted }, [converted]);this.lastPcmAt = performance.now();- this.cb.onAudio?.();+ if (!this.options.browserAudio) this.cb.onAudio?.();}private handleBrowserSpeech(message: RealtimeStatusPayload): void {@@ -836,11 +940,17 @@ export class RealtimeAudioClient {}private async teardown(sendStop: boolean): Promise<void> {- cancelAnimationFrame(this.mediaFrame);+ if (this.remoteMeter) this.remoteMeter.port.onmessage = null;+ this.remoteMeter?.disconnect();+ this.remoteMeter = null;this.remoteSource?.disconnect();this.remoteSource = null;- this.lastPlaybackActive = false;- this.remoteSilenceFrames = 0;+ this.outputActivity.reset();+ this.inputActivity.reset();+ this.inputLevel = 0;+ this.outputLevel = 0;+ this.lastMediaSendAt = Number.NEGATIVE_INFINITY;+ this.cb.onPlaybackState?.(false);const socket = this.ws;this.ws = null;this.ready = false;@@ -848,6 +958,13 @@ export class RealtimeAudioClient {// opening into the next connection attempt.this.startupPreroll = [];this.startupPrerollBytes = 0;+ this.controlReady = false;+ this.receivedPrefix = false;+ this.startupNode?.port.postMessage({ type: "suspend" });+ this.startupNode?.disconnect();+ this.rtcInput?.stream.getTracks().forEach(track => track.stop());+ this.startupNode = null;+ this.rtcInput = null;if (sendStop && socket?.readyState === WebSocket.OPEN) {try {socket.send(JSON.stringify({ type: "audio_stop" }));diff --git a/jarvis/ui/web/frontend/src/lib/startupAudio.test.ts b/jarvis/ui/web/frontend/src/lib/startupAudio.test.tsnew file mode 100644index 0000000000..eff8355d2c--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/startupAudio.test.ts@@ -0,0 +1,127 @@+import { describe, expect, it } from "vitest";+import { StartupAudioQueue } from "./startupAudio";++describe("startup RTP audio", () => {+ it.each([16000, 24000, 44100, 48000])("pays down a two-second backlog despite constant room noise at %s Hz", rate => {+ const queue = new StartupAudioQueue(rate);+ const block = 128;+ const output = new Float32Array(block);+ for (let n = 0; n < rate * 2; n += block) queue.process(new Float32Array(block).fill(0.02), output);+ queue.start();+ for (let n = 0; n < rate * 5; n += block) queue.process(new Float32Array(block).fill(0.0005), output);+ expect(queue.pendingMs).toBeLessThan(10);+ const fresh = Float32Array.from({ length: block }, (_, i) => Math.sin(i / 7) * 0.15);+ queue.process(fresh, output);+ expect(output).toEqual(fresh); // Bit-exact live capture once the debt is paid.+ });++ it("preserves the pitch and quiet amplitude of buffered speech instead of gating it away", () => {+ const rate = 48000, pitch = 200, block = 128;+ const queue = new StartupAudioQueue(rate);+ const output = new Float32Array(block);+ const tone = (n: number) => Float32Array.from({ length: block }, (_, i) => Math.sin(2 * Math.PI * pitch * (n + i) / rate) * 0.0005);+ for (let n = 0; n < rate; n += block) queue.process(tone(n), output);+ queue.start();+ const heard: number[] = [];+ for (let n = rate; n < rate * 1.5; n += block) {+ queue.process(tone(n), output);+ heard.push(...output);+ }+ const crossings = heard.slice(1).filter((sample, i) => sample >= 0 && heard[i] < 0).length;+ expect(crossings / (heard.length / rate)).toBeCloseTo(pitch, -1);+ expect(Math.max(...heard.map(Math.abs))).toBeGreaterThan(0.00045);+ expect(queue.pendingMs).toBeLessThan(850);+ });++ it.each([0, 50, 60])("also catches up with random noise and mains hum (%s Hz)", frequency => {+ const rate = 48000, block = 128;+ const queue = new StartupAudioQueue(rate), output = new Float32Array(block);+ let random = 12345;+ const frame = (n: number) => Float32Array.from({ length: block }, (_, i) => {+ random = (1664525 * random + 1013904223) >>> 0;+ return frequency ? Math.sin((n + i) * 2 * Math.PI * frequency / rate) * 0.0005 : (random / 4294967296 - 0.5) * 0.001;+ });+ for (let n = 0; n < rate * 2; n += block) queue.process(frame(n), output);+ queue.start();+ for (let n = 0; n < rate * 10; n += block) queue.process(frame(n), output);+ expect(queue.pendingMs).toBe(0);+ });++ it("clears a partly rendered catch-up grain when a connection is replaced", () => {+ const queue = new StartupAudioQueue(48000);+ const out = new Float32Array(128);+ queue.process(new Float32Array(48000).fill(0.1), out);+ queue.start();+ queue.process(new Float32Array(128).fill(0.1), out);+ queue.suspend();+ queue.process(new Float32Array(128).fill(0.8), out);+ queue.start();+ const fresh = new Float32Array(128).fill(0.2);+ queue.process(fresh, out);+ expect(out).toEqual(fresh);+ expect(queue.pendingMs).toBe(0);+ });++ it("keeps gain bounded at waveform joins", () => {+ const queue = new StartupAudioQueue(48000);+ const output = new Float32Array(128);+ for (let i = 0; i < 600; i++) queue.process(new Float32Array(128).fill(i % 2 ? 0.7 : -0.7), output);+ queue.start();+ for (let i = 0; i < 1800; i++) {+ queue.process(new Float32Array(128).fill(i % 2 ? 0.4 : -0.4), output);+ expect(output.every(value => Number.isFinite(value) && Math.abs(value) <= 0.701)).toBe(true);+ }+ });++ it("retains the first sentence during negotiation and prepends the wake mic exactly once", () => {+ const queue = new StartupAudioQueue(100);+ const output = new Float32Array(2);+ queue.process(new Float32Array([0.3, 0.4]), output);+ expect([...output]).toEqual([0, 0]);+ queue.process(new Float32Array([0.5, 0.6]), output);+ queue.prepend(new Float32Array([0.1, 0.2]));+ queue.start();+ queue.start();+ const heard: number[] = [];+ for (let i = 0; i < 3; i++) {+ queue.process(new Float32Array(2), output);+ heard.push(...output);+ }+ expect(heard.map(v => Math.round(v * 10))).toEqual([1, 2, 3, 4, 5, 6]);+ expect(() => queue.prepend(new Float32Array([1]))).toThrow();+ });++ it("catches up during digital silence without discarding quiet speech", () => {+ const queue = new StartupAudioQueue(100);+ const output = new Float32Array(10);+ for (let i = 0; i < 10; i++) queue.process(new Float32Array(10).fill(0.0005), output);+ queue.start();+ for (let i = 0; i < 20; i++) queue.process(new Float32Array(10), output);+ queue.process(new Float32Array(10).fill(0.7), output);+ expect(output[0]).toBeCloseTo(0.7); // Live again, no permanent startup delay.+ });++ it("never carries microphone frames over reconnect or cancellation", () => {+ const queue = new StartupAudioQueue(100);+ const output = new Float32Array(2);+ queue.process(new Float32Array([0.1, 0.2]), output);+ queue.suspend();+ queue.process(new Float32Array([0.3, 0.4]), output);+ queue.start();+ queue.process(new Float32Array([0.5, 0.6]), output);+ expect([...output].map(v => Math.round(v * 10))).toEqual([5, 6]);+ });++ it("refuses overflow instead of silently truncating an opening command", () => {+ const queue = new StartupAudioQueue(1);+ const output = new Float32Array(31);+ expect(() => queue.process(new Float32Array(31).fill(0.1), output)).toThrow(/buffer exceeded/);+ });++ it("includes the native prefix in the startup memory bound before media starts", () => {+ const queue = new StartupAudioQueue(100);+ queue.prepend(new Float32Array(2000));+ expect(queue.pendingMs).toBe(20000);+ expect(() => queue.process(new Float32Array(1500), new Float32Array(2))).toThrow(/buffer exceeded/);+ });+});diff --git a/jarvis/ui/web/frontend/src/lib/startupAudio.ts b/jarvis/ui/web/frontend/src/lib/startupAudio.tsnew file mode 100644index 0000000000..9a2fd7132f--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/startupAudio.ts@@ -0,0 +1,165 @@+/** Transient wake prefix; never persisted or reused across connections. */+export interface InputPrefix {+ type: "input_prefix";+ sample_rate: number;+ audio: string;+}++/** Capture gate for an RTP track: retain the opening until session.started.+ * A short, pitch-preserving overlap-add pass pays down the startup backlog.+ * It does not classify low-amplitude speech as silence. Once caught up, audio+ * passes through unchanged. Only the microphone input is time-compressed;+ * assistant playback never runs through this queue.+ */+export class StartupAudioQueue {+ private frames: Float32Array[] = [];+ private head = 0;+ private offset = 0;+ private samples = 0;+ private started = false;+ private suspended = false;+ private prefix: Float32Array | null = null;+ private catchingUp = false;+ private readonly grain: Float32Array;+ private readonly analysis: Float32Array;+ private grainOffset = 0;+ private grainLength = 0;++ constructor(private readonly rate: number) {+ if (!Number.isFinite(rate) || rate <= 0) throw new Error("Invalid microphone sample rate");+ this.grain = new Float32Array(Math.max(1, Math.round(rate * 0.02)));+ this.analysis = new Float32Array(this.grain.length + Math.max(1, Math.ceil(rate * 0.015)));+ }++ /** Unsent input, including the remaining rendered grain; useful for diagnostics. */+ get pendingMs(): number {+ return (this.samples + (this.prefix?.length ?? 0) + this.grainLength - this.grainOffset) / this.rate * 1000;+ }++ prepend(pcm: Float32Array): void {+ if (this.started || this.suspended || this.prefix) throw new Error("Unexpected wake prefix");+ if (pcm.length + this.samples > this.rate * 30) throw new Error("Voice startup buffer exceeded");+ this.prefix = pcm;+ }++ start(): void {+ if (this.started) return;+ if (this.prefix) {+ this.frames.unshift(this.prefix);+ this.samples += this.prefix.length;+ this.prefix = null;+ }+ this.suspended = false;+ this.started = true;+ // A tiny device quantum needs no speech processing. A real handshake+ // backlog does: waiting for exactly zero microphone samples stranded it+ // indefinitely in rooms with even very faint background noise.+ this.catchingUp = this.samples > this.rate * 0.1;+ }++ suspend(): void {+ this.frames = [];+ this.samples = this.offset = this.head = 0;+ this.grainOffset = this.grainLength = 0;+ this.grain.fill(0);+ this.analysis.fill(0);+ this.catchingUp = false;+ this.prefix = null;+ this.started = false;+ this.suspended = true;+ }++ process(input: Float32Array, output: Float32Array): void {+ output.fill(0);+ if (this.suspended) return;+ if (this.samples + (this.prefix?.length ?? 0) + input.length > this.rate * 30) throw new Error("Voice startup buffer exceeded");+ if (input.length) this.frames.push(input.slice());+ this.samples += input.length;+ if (!this.started) return;+ let written = 0;+ while (written < output.length) {+ if (this.grainOffset < this.grainLength) {+ const count = Math.min(output.length - written, this.grainLength - this.grainOffset);+ output.set(this.grain.subarray(this.grainOffset, this.grainOffset + count), written);+ this.grainOffset += count;+ written += count;+ continue;+ }+ if (!this.samples) break;+ const needed = output.length - written;+ const backlog = this.samples - needed;+ if (this.catchingUp && backlog > 0) {+ this.renderCatchup(backlog);+ continue;+ }+ this.catchingUp = false;+ const count = Math.min(needed, this.samples);+ this.peek(output.subarray(written, written + count));+ this.consume(count);+ written += count;+ }+ }++ private peek(target: Float32Array): void {+ let frameIndex = this.head, offset = this.offset, written = 0;+ while (written < target.length) {+ const frame = this.frames[frameIndex];+ const count = Math.min(frame.length - offset, target.length - written);+ target.set(frame.subarray(offset, offset + count), written);+ written += count;+ offset = 0;+ frameIndex++;+ }+ }++ private consume(count: number): void {+ this.samples -= count;+ while (count) {+ const available = this.frames[this.head].length - this.offset;+ if (count < available) { this.offset += count; break; }+ count -= available;+ this.head++;+ this.offset = 0;+ }+ if (this.head > 256 || !this.samples) {+ this.frames.splice(0, this.head);+ this.head = 0;+ }+ }++ private renderCatchup(backlog: number): void {+ // Remove 5–15 ms per 20 ms grain, aligned to a similar waveform. The+ // convex crossfade preserves amplitude bounds and avoids pitch shifts+ // from naive resampling. At the tail, consume only the outstanding lag.+ const maximum = Math.min(backlog, Math.floor(this.samples / 2), Math.max(1, Math.round(this.rate * 0.015)));+ const minimum = Math.min(maximum, Math.max(1, Math.round(this.rate * 0.005)));+ const desired = Math.min(maximum, Math.max(1, Math.round(this.rate * 0.01)));+ const length = Math.min(this.grain.length, this.samples - maximum);+ this.peek(this.analysis.subarray(0, length + maximum));+ const stride = Math.max(1, Math.floor(this.rate / 6000));+ const step = Math.max(1, Math.floor(this.rate / 12000));+ let chosen = desired, best = Number.NEGATIVE_INFINITY;+ for (let shift = minimum; shift <= maximum; shift += step) {+ let dot = 0, leftEnergy = 0, rightEnergy = 0;+ for (let i = 0; i < length; i += stride) {+ const left = this.analysis[i], right = this.analysis[i + shift];+ dot += left * right;+ leftEnergy += left * left;+ rightEnergy += right * right;+ }+ const energy = Math.sqrt(leftEnergy * rightEnergy);+ const similarity = energy > 1e-20 ? dot / energy : 1;+ // On silence/constant noise, choose the desired advance, not the first+ // candidate. Search cost and progress are bounded at every sample rate.+ const score = similarity - 0.001 * Math.abs(shift - desired) / Math.max(1, maximum);+ if (score > best) { best = score; chosen = shift; }+ }+ for (let i = 0; i < length; i++) {+ const blend = length > 1 ? i / (length - 1) : 0.5;+ this.grain[i] = this.analysis[i] * (1 - blend) + this.analysis[i + chosen] * blend;+ }+ this.consume(length + chosen);+ this.grainOffset = 0;+ this.grainLength = length;+ }+}diff --git a/jarvis/ui/web/frontend/src/lib/thinkingSteps.ts b/jarvis/ui/web/frontend/src/lib/thinkingSteps.tsindex a630fcc581..f84e6302bf 100644--- a/jarvis/ui/web/frontend/src/lib/thinkingSteps.ts+++ b/jarvis/ui/web/frontend/src/lib/thinkingSteps.ts@@ -218,6 +218,21 @@ export function reduceThinkingSteps(const p = (payload ?? {}) as Record<string, unknown>;switch (eventName) {+ case "ReasoningSummaryUpdated": {+ const id = `reasoning:${str(p.response_id)}`;+ const text = str(p.text).trim();+ if (!text) return null;+ const index = steps.findIndex(step => step.id === id);+ const step: ThinkingStep = {+ id, kind: "thought", labelKey: "thinking.step_thought", detail: text,+ status: p.done === true ? "done" : "active",+ startedTs: index >= 0 ? steps[index].startedTs : tsMs,+ };+ if (index < 0) return push(steps, step);+ const next = [...steps];+ next[index] = step;+ return next;+ }case "BrainTurnStarted": {// The fallback chain may publish several BrainTurnStarted per turn —// close the previous attempt before opening the next one.diff --git a/jarvis/ui/web/frontend/src/lib/voiceOutputLevel.ts b/jarvis/ui/web/frontend/src/lib/voiceOutputLevel.tsindex 1c11df8840..c37bc0cd31 100644--- a/jarvis/ui/web/frontend/src/lib/voiceOutputLevel.ts+++ b/jarvis/ui/web/frontend/src/lib/voiceOutputLevel.ts@@ -32,6 +32,15 @@ export type VoiceOutputLevelSource = "native" | "browser";export const voiceOutputLevelRef: { current: number | null } = { current: null };let browserOwnsOutput = false;+let browserPlaybackActive = false;++export function setBrowserPlaybackActive(active: boolean): void {+ browserPlaybackActive = active;+}++export function browserPlaybackIsActive(): boolean {+ return browserOwnsOutput && browserPlaybackActive;+}export function setVoiceOutputLevel(value: number,@@ -49,5 +58,6 @@ export function clearVoiceOutputLevel(source: VoiceOutputLevelSource = "native")export function setBrowserVoiceOutputOwnership(active: boolean): void {browserOwnsOutput = active;+ if (!active) browserPlaybackActive = false;voiceOutputLevelRef.current = null;}diff --git a/jarvis/ui/web/frontend/src/store/agentChat.ts b/jarvis/ui/web/frontend/src/store/agentChat.tsindex aa8d948e2e..125224d8c4 100644--- a/jarvis/ui/web/frontend/src/store/agentChat.ts+++ b/jarvis/ui/web/frontend/src/store/agentChat.ts@@ -268,9 +268,10 @@ function onLadder(value: string, ladder: readonly string[], fallback: string): s/** How many left-behind transcripts the store keeps for an instant switch-back. */const TIMELINE_CACHE_LIMIT = 24;-export function createAgentChatStore(surface: AgentChatSurface) {- const DRAFT_KEY = draftKey(surface);+export function createAgentChatStore(surface: AgentChatSurface, draftNamespace = "") {+ const DRAFT_KEY = draftKey(surface) + (draftNamespace ? `:${draftNamespace}` : "");+ let catalogRequest = 0;let socket: WebSocket | null = null;let socketSession: string | null = null;/** Cancels the reconnect waiting in the shared connect budget. */@@ -351,6 +352,7 @@ export function createAgentChatStore(surface: AgentChatSurface) {draft: draftFromSession(frame.session, prev.draft),});writeDraft(DRAFT_KEY, get().draft);+ if (prev.activeSession?.account_id !== frame.session.account_id) void get().loadCatalog();return;}if (frame.type === "event" && frame.event) get().ingest(frame.event);@@ -401,11 +403,14 @@ export function createAgentChatStore(surface: AgentChatSurface) {lastError: null,loadCatalog: async () => {+ const requestId = ++catalogRequest;+ const sessionId = get().activeSessionId;try {const [raw, connections] = await Promise.all([- fetchAgentChatCatalog(surface),+ fetchAgentChatCatalog(surface, { sessionId: sessionId ?? undefined, cwd: get().draft.cwd || undefined }),fetchAgentConnections().catch(() => [] as AgentConnectionRow[]),]);+ if (requestId !== catalogRequest || sessionId !== get().activeSessionId) return;// A backend older than this bundle (the app not yet restarted after// an update) may lack the newer arrays; an empty ladder is honest,// a crash is not — and the composer tells the person to restart.@@ -479,7 +484,7 @@ export function createAgentChatStore(surface: AgentChatSurface) {}if (draft.provider) void get().loadModels(draft.provider);} catch (err) {- set({ catalogError: errorText(err) });+ if (requestId === catalogRequest && sessionId === get().activeSessionId) set({ catalogError: errorText(err) });}},@@ -589,13 +594,16 @@ export function createAgentChatStore(surface: AgentChatSurface) {newChat: () => {closeSocket();+ ++catalogRequest;set({activeSessionId: null,activeSession: null,timeline: EMPTY_TIMELINE,socketState: "idle",lastError: null,+ catalog: null,});+ void get().loadCatalog();},openSession: (sessionId) => {@@ -611,6 +619,7 @@ export function createAgentChatStore(surface: AgentChatSurface) {busy: false,lastError: null,});+ void get().loadCatalog();connect(sessionId, 0);},diff --git a/jarvis/ui/web/frontend/src/store/events.ts b/jarvis/ui/web/frontend/src/store/events.tsindex ccd47fe2a0..a03e707e66 100644--- a/jarvis/ui/web/frontend/src/store/events.ts+++ b/jarvis/ui/web/frontend/src/store/events.ts@@ -1,4 +1,5 @@import { create } from "zustand";+import { browserPlaybackIsActive } from "@/lib/voiceOutputLevel";import type { MessageRole } from "@/types/messages";import { readCachedAssistantName } from "@/lib/assistantNameCache";import {@@ -626,7 +627,10 @@ export const useEventStore = create<EventStore>((set, get) => ({return { events: next };}),- setVoice: (v) => set({ voiceState: v }),+ setVoice: (v) => set({+ voiceState: browserPlaybackIsActive() && ["thinking", "listening", "speaking"].includes(v)+ ? "speaking" : v,+ }),setVoiceReady: (ready) => set({ voiceReady: ready }),setConnected: (c) => set({ connected: c }),setWarming: (warming) => set({ wsWarming: warming }),diff --git a/jarvis/ui/web/frontend/src/store/home.ts b/jarvis/ui/web/frontend/src/store/home.tsindex de74a96049..91f1634cfa 100644--- a/jarvis/ui/web/frontend/src/store/home.ts+++ b/jarvis/ui/web/frontend/src/store/home.ts@@ -31,6 +31,7 @@ interface HomeStore {* live line under the lane until the spoken line (SpeechSpoken) lands.*/liveReply: string;+ liveSessionId: string | null;ingest: (name: string, payload: unknown, tsMs: number) => void;/*** Replace the lane with a stored conversation (a reopened voice session);@@ -90,8 +91,19 @@ export const useHomeStore = create<HomeStore>((set, get) => ({},transcript: [],liveReply: "",+ liveSessionId: null,ingest: (name, payload, tsMs) => {+ if (name === "VoiceTranscriptUpdated") {+ const sessionId = (payload as { session_id?: string } | null)?.session_id;+ if (get().liveSessionId && sessionId !== get().liveSessionId) return;+ // The continuous caption has a stable row of its own. Clear the legacy+ // single-line preview so it cannot appear a second time at the bottom.+ useEventStore.getState().setTranscription("", true);+ set({ liveReply: "", liveSessionId: sessionId || null });+ }if (name === "VoiceSessionEnded") {+ const sessionId = (payload as { session_id?: string } | null)?.session_id;+ if (sessionId && get().liveSessionId && sessionId !== get().liveSessionId) return;const reason = (payload as { hangup_reason?: string } | null)?.hangup_reason;// A provider handover continues the same call. A real hangup opens an// empty lane; the completed conversation remains in the history rail.@@ -115,7 +127,7 @@ export const useHomeStore = create<HomeStore>((set, get) => ({}if (name === "VoiceSessionStarted") {// A call already started elsewhere must not be ended on card re-entry.- set({ freshVoicePending: false });+ set({ freshVoicePending: false, liveSessionId: (payload as { session_id?: string })?.session_id || null });}const before = get().transcript;const after = reduceTranscript(before, name, payload, tsMs);@@ -125,5 +137,5 @@ export const useHomeStore = create<HomeStore>((set, get) => ({}},seedTranscript: (lines) => set({ transcript: lines, liveReply: "", freshVoicePending: false }),- resetTranscript: () => set({ transcript: [], liveReply: "" }),+ resetTranscript: () => set({ transcript: [], liveReply: "", liveSessionId: null }),}));diff --git a/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx b/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsxindex 24b3cf681e..7f57d173b3 100644--- a/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx+++ b/jarvis/ui/web/frontend/src/views/AgenticIdeView.tsx@@ -37,7 +37,7 @@ import {groupFor,} from "@/lib/agentAccountsApi";import { openScratchProject } from "@/lib/chatLibraryApi";-import { TopBarActions } from "@/components/layout/TopBar";+import { WorkspaceBar } from "@/components/agentic/WorkspaceBar";import {isEmptyPayload,@@ -1004,18 +1004,9 @@ export function AgenticIdeView({ onScreen = true }: AgenticIdeViewProps) {? { ...workspace, terminals: session.terminals.length }: workspace,);- /*- * `actions` only in the standalone bar.- *- * With a workspace open the grid owns the row and puts the app's actions at- * its far right itself; the wizard has no grid, so the bar carries them — and- * carries them even with nothing open, which is why it renders at all in that- * case. Passing them here as well would put Restart on screen twice.- */const renderBar = (embedded: boolean) => (<WorkspaceBarembedded={embedded}- actions={embedded ? undefined : <TopBarActions />}workspaces={barWorkspaces}activeId={session?.id ?? null}addingNew={addingNew}@@ -1045,7 +1036,6 @@ export function AgenticIdeView({ onScreen = true }: AgenticIdeViewProps) {key={session.id}session={session}workspaceBar={renderBar(true)}- appActions={<TopBarActions />}onJumpToWorkspace={(id, pane) => void jumpToPane(id, pane)}jumpTo={jumpTo}focusMode={focusMode}diff --git a/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx b/jarvis/ui/web/frontend/src/views/ApiKeysView.tsxindex 2d0ba45516..5dcb1947c2 100644--- a/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx+++ b/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx@@ -1,8 +1,18 @@import { useEffect, useRef, useState } from "react";-import { Bot, Brain, KeyRound, Mic, Phone, Radio, SlidersHorizontal, Terminal, Volume2, Wand2 } from "lucide-react";+import {+ Bot,+ Brain,+ KeyRound,+ Mic,+ Phone,+ Radio,+ SlidersHorizontal,+ Volume2,+ Wand2,+} from "lucide-react";import { ViewHeader } from "@/views/ChatsView";import { JarvisAgentSection } from "@/components/JarvisAgentSection";-import { LiveProfile } from "@/components/providers/LiveProfile";+import { VoiceProviderSettings } from "@/components/providers/VoiceProviderSettings";import { TelephonyPanel } from "@/views/TelephonyView";import { WikiProviderCard } from "@/views/settings/WikiProviderCard";import { JarvisApiGroup } from "@/views/settings/JarvisApiGroup";@@ -13,19 +23,14 @@ import { TeamProxyGroup } from "@/views/settings/TeamProxyGroup";import {CategoryHero,EngineModeSwitch,- GuidancePanel,LocalModeSwitch,makeProviderCategories,ProviderCategory,useTierHealth,- VoiceEngineContext,- type CategoryMeta,type LucideIcon,- type RecommendationTab,type VoiceEngineMode,} from "@/components/providers/ProviderTierSection";import {- type ProviderDescriptor,type ProviderTier,type SectionHealth,useProviders,@@ -35,24 +40,13 @@ import { useLocalMode } from "@/lib/localMode";import { cn } from "@/lib/utils";import { useT } from "@/i18n";-// The view is organised around exactly five primary categories — Brain, Voice-// Output (TTS), Voice Input (STT), Realtime and Subagents — surfaced as a-// segmented tab bar. The per-install Control Key gets its OWN de-emphasized-// tab ("jarvis-key", labelled "<Name> Key" after the configured wake word) so-// a user hunting for the key the lock screen asks about finds a section named-// like their assistant. Everything else (team key proxy, telephony, Wiki)-// lives in the "Advanced" tab so it never competes with the core categories.-type CategoryKey = ProviderTier | "subagents" | "jarvis-key" | "advanced";+// Voice owns its thinking backend. Text and background work use the Agents selection.+type CategoryKey =+ | Exclude<ProviderTier, "computer-use">+ | "subagents"+ | "jarvis-key"+ | "advanced";-// Realtime replaces STT+Brain+TTS with one full-duplex model, so those three-// tiers don't apply in Realtime mode — that's the whole reason for the split.-// "computer-use" is GLOBAL (not mode-specific — Computer-Use is one engine for-// the whole app), so it appears right after the main chat-model tab in BOTH-// tab sets.-// "dictation" sits right behind "stt" because that is the order the text-// travels in: speech becomes a transcript, then the optional wording pass-// tidies it. It rides with the Pipeline tab set for the same reason "stt"-// does — it only ever works on a transcript that tier produced.const PIPELINE_TABS: CategoryKey[] = ["brain","tts",@@ -71,7 +65,8 @@ const REALTIME_TABS: CategoryKey[] = [export function ApiKeysView() {const t = useT();- const { providers, loading, error, refetch, setActiveOptimistic } = useProviders();+ const { providers, loading, error, refetch, setActiveOptimistic } =+ useProviders();// Per-tab health (amber = the active provider isn't set up, red = it's set up// but failing a live check). Best-effort and off the render-blocking path.const health = useTierHealth(providers);@@ -84,18 +79,6 @@ export function ApiKeysView() {const {mode: liveMode,realtimeAvailable,- statusKnown,- connecting,- requiresWebRtcOffer,- transportOfferReady,- transportOfferDetail,- transportIssue,- sessionActive,- activeSessionMode,- activeSessionProvider,- activeSessionModel,- transitioning,- lastStartError,setMode: setVoiceMode,isLoading: liveModeLoading,} = useVoiceMode();@@ -123,14 +106,6 @@ export function ApiKeysView() {const modeTabs = engineMode === "realtime" ? REALTIME_TABS : PIPELINE_TABS;- // A recommendation row navigates to the tab it talks about. This is VIEW- // navigation only: opening the Realtime tab set here never persists- // `[voice].mode` (only the segmented switch does that, key-gated).- function openRecommendedTab(tab: RecommendationTab) {- if (tab === "realtime") setEngineMode("realtime");- setActive(tab);- }-return (<div className="flex h-full min-h-0 flex-col"><ViewHeader@@ -151,84 +126,57 @@ export function ApiKeysView() {}/>- <CategoryTabs active={active} onSelect={setActive} health={health} tabs={modeTabs} />+ <CategoryTabs+ active={active}+ onSelect={setActive}+ health={health}+ tabs={modeTabs}+ /><divdata-testid="api-keys-provider-scroll"className="min-h-0 flex-1 overflow-y-auto scrollbar-jarvis px-6 py-3">- <VoiceEngineContext- mode={engineMode}- realtimeAvailable={realtimeAvailable}- statusKnown={statusKnown}- connecting={connecting}- requiresWebRtcOffer={requiresWebRtcOffer}- transportOfferReady={transportOfferReady}- transportOfferDetail={transportOfferDetail}- transportIssue={transportIssue}- sessionActive={sessionActive}- activeSessionMode={activeSessionMode}- activeSessionProvider={activeSessionProvider}- activeSessionModel={activeSessionModel}- transitioning={transitioning}- lastStartError={lastStartError}- liveMode={liveMode}- onOpenRecommendedTab={openRecommendedTab}- />{/* Readability: the provider cards used to stretch across the fullwindow width (2000px+ on wide screens). One centered measure keepsevery card scannable; the key prop re-runs the rise animation oneach tab/mode change (respects prefers-reduced-motion). */}- <div key={`${engineMode}-${active}`} className="profile-rise mx-auto w-full max-w-4xl">- {(active === "brain" ||- active === "tts" ||- active === "stt" ||- active === "dictation") && (- <ProviderCategory- meta={categories[active]}- tier={active}- providers={providers}- loading={loading}- error={error}- onChanged={refetch}- onActivateOptimistic={setActiveOptimistic}- health={health[active]}- localMode={localMode}- onDisableLocalMode={() => setLocalMode(false)}- />- )}- {active === "realtime" && (- <>- {!localMode && <LiveProfile />}- <RealtimeCategory- meta={categories.realtime}- providers={providers}- loading={loading}- error={error}- onChanged={refetch}- onActivateOptimistic={setActiveOptimistic}- health={health.realtime}- localMode={localMode}- onDisableLocalMode={() => setLocalMode(false)}- />- </>- )}- {active === "computer-use" && (- <ComputerUseCategory- meta={categories["computer-use"]}- providers={providers}- loading={loading}- error={error}- onChanged={refetch}- onActivateOptimistic={setActiveOptimistic}- health={health["computer-use"]}- localMode={localMode}- onDisableLocalMode={() => setLocalMode(false)}- />- )}- {active === "subagents" && <SubagentCategory />}- {active === "jarvis-key" && <JarvisKeyCategory />}- {active === "advanced" && <AdvancedCategory />}+ <div+ key={`${engineMode}-${active}`}+ className="profile-rise w-full max-w-5xl"+ >+ {(active === "brain" ||+ active === "tts" ||+ active === "stt" ||+ active === "dictation") && (+ <ProviderCategory+ meta={categories[active]}+ tier={active}+ providers={providers}+ loading={loading}+ error={error}+ onChanged={refetch}+ onActivateOptimistic={setActiveOptimistic}+ health={health[active]}+ localMode={localMode}+ onDisableLocalMode={() => setLocalMode(false)}+ />+ )}+ {active === "realtime" && (+ <VoiceProviderSettings+ providers={providers}+ loading={loading}+ error={error}+ onChanged={refetch}+ onActivateOptimistic={setActiveOptimistic}+ health={health.realtime}+ localMode={localMode}+ onDisableLocalMode={() => setLocalMode(false)}+ />+ )}+ {active === "subagents" && <SubagentCategory />}+ {active === "jarvis-key" && <JarvisKeyCategory />}+ {active === "advanced" && <AdvancedCategory />}</div></div></div>@@ -262,7 +210,6 @@ function CategoryTabs({tts: { label: t("apikeys_view.tab_tts"), icon: Volume2 },stt: { label: t("apikeys_view.tab_stt"), icon: Mic },realtime: { label: t("apikeys_view.tab_realtime"), icon: Radio },- "computer-use": { label: t("apikeys_view.tab_computer_use"), icon: Terminal },dictation: { label: t("apikeys_view.tab_dictation"), icon: Wand2 },subagents: { label: t("apikeys_view.tab_subagents"), icon: Bot },};@@ -279,7 +226,10 @@ function CategoryTabs({{/* Underline tabs on the header's own rule — no pill group inside aframe inside a bar. The core tabs and the two secondary ones shareone baseline; a hairline separates them. */}- <div role="tablist" className="flex min-w-max flex-nowrap items-center gap-1">+ <div+ role="tablist"+ className="flex min-w-max flex-nowrap items-center gap-1"+ >{coreTabs.map((key) => (<TabButtonkey={key}@@ -396,123 +346,6 @@ function TabButton({);}-/**- * The Realtime category (Feature B): the two realtime provider cards, via the- * SAME `ProviderCategory` used for brain/tts/stt (unchanged). Realtime- * speech-to-speech models can't see the screen, so Computer-Use during a- * realtime turn runs on the dedicated Computer-Use provider (or the active- * Brain provider, until one is picked) — now its own "Computer-Use" tab- * (see `ComputerUseCategory` below) rather than a panel embedded here. This- * wrapper mirrors `SubagentCategory` below: it owns nothing itself, it just- * composes the existing tier section.- */-function RealtimeCategory({- meta,- providers,- loading,- error,- onChanged,- onActivateOptimistic,- health,- localMode = false,- onDisableLocalMode,-}: {- meta: CategoryMeta;- providers: ProviderDescriptor[];- loading: boolean;- error: string | null;- onChanged: () => void;- onActivateOptimistic: (tier: ProviderTier, id: string) => void;- health?: SectionHealth;- localMode?: boolean;- onDisableLocalMode?: () => void;-}) {- const t = useT();- return (- <ProviderCategory- meta={meta}- tier="realtime"- providers={providers}- loading={loading}- error={error}- onChanged={onChanged}- onActivateOptimistic={onActivateOptimistic}- health={health}- localMode={localMode}- onDisableLocalMode={onDisableLocalMode}- intro={- <GuidancePanel- title={t("apikeys_view.guide_realtime_title")}- body={t("apikeys_view.guide_realtime_body")}- />- }- />- );-}--/**- * The Computer-Use tab: an OVERLAY over the brain-tier provider cards- * (Claude/OpenAI/OpenRouter/Gemini), NOT a new provider tier. Reuses the SAME- * `ProviderCategory`/`TierSection`/`ProviderCard` machinery as Brain/TTS/STT- * by mapping every brain-switchable provider to a synthetic `"computer-use"`- * tier descriptor whose `active` mirrors `computer_use_active` — a SEPARATE- * selection from the Brain tab's `active`/`brain.primary`. The synthetic- * `tier` value forks the shared machinery cleanly: the radio group's- * `name="active-computer-use"` never collides with `name="active-brain"`,- * and `ProviderCard.activate()` routes to `switchComputerUseProvider` instead- * of `switchBrainProvider`. The CU provider is GLOBAL (one engine for the- * whole app), so this tab renders identically in Pipeline and Realtime mode —- * it replaces the old `RealtimeComputerUsePanel`, which only displayed the- * delegation without letting the user pick a provider.- */-function ComputerUseCategory({- meta,- providers,- loading,- error,- onChanged,- onActivateOptimistic,- health,- localMode = false,- onDisableLocalMode,-}: {- meta: CategoryMeta;- providers: ProviderDescriptor[];- loading: boolean;- error: string | null;- onChanged: () => void;- onActivateOptimistic: (tier: ProviderTier, id: string) => void;- health?: SectionHealth;- localMode?: boolean;- onDisableLocalMode?: () => void;-}) {- const t = useT();- const cuProviders: ProviderDescriptor[] = providers- .filter((p) => p.tier === "brain" && p.brain_switchable !== false)- .map((p) => ({ ...p, tier: "computer-use", active: !!p.computer_use_active }));-- return (- <ProviderCategory- meta={meta}- tier="computer-use"- providers={cuProviders}- loading={loading}- error={error}- onChanged={onChanged}- onActivateOptimistic={onActivateOptimistic}- health={health}- localMode={localMode}- onDisableLocalMode={onDisableLocalMode}- intro={- <GuidancePanel- title={t("apikeys_view.guide_computer_use_title")}- body={t("apikeys_view.guide_computer_use_body")}- />- }- />- );-}-/*** The Subagents category — the heavy-task worker selection. `SubagentSection`* owns its own data source (/api/jarvis-agent/status) and card system; the hero banddiff --git a/jarvis/ui/web/frontend/src/views/ApiKeysView.two-mode.test.tsx b/jarvis/ui/web/frontend/src/views/ApiKeysView.two-mode.test.tsxindex f7ba25e275..a23520842e 100644--- a/jarvis/ui/web/frontend/src/views/ApiKeysView.two-mode.test.tsx+++ b/jarvis/ui/web/frontend/src/views/ApiKeysView.two-mode.test.tsx@@ -10,7 +10,14 @@* (2) the setMode call pattern for both availability states.*/import { afterEach, describe, expect, it, vi } from "vitest";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { cleanup, fireEvent, render, screen } from "@testing-library/react";+import type { ReactElement } from "react";++function renderKeys(ui: ReactElement = <ApiKeysView />) {+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ return render(<QueryClientProvider client={client}>{ui}</QueryClientProvider>);+}// Mock the data hooks so the view renders deterministically, without a// network round-trip.@@ -70,12 +77,13 @@ afterEach(() => {});describe("ApiKeysView two-mode", () => {- it("keeps the mode switch in the header and scrolls its context with providers", () => {- render(<ApiKeysView />);+ it("keeps mode controls in the header and voice setup in the scrolling content", () => {+ renderKeys();+ fireEvent.click(screen.getByRole("button", { name: /^realtime/i }));const headerControl = screen.getByTestId("voice-engine-header-control");const providerScroll = screen.getByTestId("api-keys-provider-scroll");- const context = screen.getByTestId("voice-engine-context");+ const context = screen.getByRole("tabpanel", { name: "Voice & thinking" });const categoryTabs = screen.getByTestId("api-keys-category-tabs");expect(headerControl.closest("header")).not.toBeNull();@@ -83,21 +91,19 @@ describe("ApiKeysView two-mode", () => {expect(providerScroll.className).toContain("min-h-0");expect(categoryTabs.className).toContain("overflow-x-auto");expect(screen.getByRole("tablist").className).toContain("min-w-max");- expect(screen.getAllByTestId("voice-engine-runtime-status")).toHaveLength(1);+ expect(screen.queryByTestId("voice-engine-context")).toBeNull();});- it("always shows the one-mode-only API-keys hint in the engine context", () => {- render(<ApiKeysView />);- const hint = screen.getByTestId("voice-engine-keys-hint");- expect(screen.getByTestId("voice-engine-context").contains(hint)).toBe(true);- // The load-bearing message: which keys you need depends on the SELECTED mode.- expect(hint.textContent).toMatch(- /realtime needs one live provider, using either a subscription login or an API key\. pipeline needs its own/i,- );+ it("never offers a separate Tool Model in either voice mode", () => {+ renderKeys();+ expect(screen.queryByRole("tab", { name: /tool model/i })).toBeNull();+ fireEvent.click(screen.getByRole("button", { name: /^realtime/i }));+ expect(screen.queryByRole("tab", { name: /tool model/i })).toBeNull();+ expect(screen.getByText(/Text chat and background tasks use your selection in Agents/)).toBeTruthy();});it("defaults to Pipeline mode showing Brain/Voice/Subagents tabs, no Realtime tab", () => {- render(<ApiKeysView />);+ renderKeys();expect(screen.getByRole("tab", { name: /brain/i })).toBeTruthy();expect(screen.getByRole("tab", { name: /voice output/i })).toBeTruthy();expect(screen.getByRole("tab", { name: /voice input/i })).toBeTruthy();@@ -110,7 +116,7 @@ describe("ApiKeysView two-mode", () => {});it("shows the segmented Pipeline|Realtime switch with an Active badge on the live mode", () => {- render(<ApiKeysView />);+ renderKeys();const pipelineSegment = screen.getByRole("button", { name: /pipeline/i });const realtimeSegment = screen.getByRole("button", { name: /^realtime/i });expect(pipelineSegment).toBeTruthy();@@ -122,7 +128,7 @@ describe("ApiKeysView two-mode", () => {});it("marks Realtime as recommended and Pipeline as not recommended", () => {- render(<ApiKeysView />);+ renderKeys();const pipelineSegment = screen.getByRole("button", { name: /pipeline/i });const realtimeSegment = screen.getByRole("button", { name: /^realtime/i });expect(pipelineSegment.textContent).toMatch(/not recommended/i);@@ -131,7 +137,7 @@ describe("ApiKeysView two-mode", () => {});it("keeps the highlighted header segment aligned with the selected provider view", () => {- render(<ApiKeysView />);+ renderKeys();const thumb = screen.getByTestId("voice-engine-selection-thumb");expect(thumb.style.transform).toBe("translateX(100%)");@@ -142,12 +148,11 @@ describe("ApiKeysView two-mode", () => {expect(thumb.style.transform).toBe("translateX(0%)");});- it("shows a research-preview disclaimer when Realtime is selected", () => {- render(<ApiKeysView />);+ it("offers one provider setup instead of the legacy recommendation block", () => {+ renderKeys();fireEvent.click(screen.getByRole("button", { name: /^realtime/i }));- // The caveat is a tag with the full sentence for assistive tech, so the- // phrase appears more than once — what matters is that it is on screen.- expect(screen.getAllByText(/research preview/i).length).toBeGreaterThan(0);+ expect(screen.getByRole("group", { name: "Voice provider settings" })).toBeTruthy();+ expect(screen.queryByText(/personal recommendation/i)).toBeNull();});it("shows when the selected Realtime mode is still served by Pipeline", () => {@@ -155,7 +160,7 @@ describe("ApiKeysView two-mode", () => {mockSessionActive = true;mockActiveSessionMode = "pipeline";- render(<ApiKeysView />);+ renderKeys();expect(screen.getByTestId("voice-engine-runtime-status").textContent).toMatch(/fell back to Pipeline/i,@@ -163,7 +168,7 @@ describe("ApiKeysView two-mode", () => {});it("switching to Realtime mode shows only Realtime/Subagents/Advanced and persists voice-mode (available)", () => {- render(<ApiKeysView />);+ renderKeys();fireEvent.click(screen.getByRole("button", { name: /^realtime/i })); // the segmentexpect(screen.getByRole("tab", { name: /realtime/i })).toBeTruthy();@@ -180,7 +185,7 @@ describe("ApiKeysView two-mode", () => {});it("switching back to Pipeline restores the five pipeline tabs and always persists voice-mode", () => {- render(<ApiKeysView />);+ renderKeys();fireEvent.click(screen.getByRole("button", { name: /^realtime/i }));putVoiceMode.mockClear();fireEvent.click(screen.getByRole("button", { name: /pipeline/i }));@@ -196,7 +201,7 @@ describe("ApiKeysView two-mode — realtime unavailable (no key in any family)",it("does not label unavailable configured Realtime as live", () => {mockVoiceMode = "realtime";mockRealtimeAvailable = false;- render(<ApiKeysView />);+ renderKeys();const realtimeSegment = screen.getByRole("button", { name: /^realtime/i });expect(realtimeSegment.textContent).not.toMatch(/active/i);@@ -206,7 +211,7 @@ describe("ApiKeysView two-mode — realtime unavailable (no key in any family)",it("switching to Realtime still switches the view, but does NOT persist voice-mode", () => {mockRealtimeAvailable = false;- render(<ApiKeysView />);+ renderKeys();fireEvent.click(screen.getByRole("button", { name: /^realtime/i }));// The view still switches, so the user can add a key from the Realtime tab.@@ -217,7 +222,7 @@ describe("ApiKeysView two-mode — realtime unavailable (no key in any family)",it("switching back to Pipeline still persists voice-mode even when realtime is unavailable", () => {mockRealtimeAvailable = false;- render(<ApiKeysView />);+ renderKeys();fireEvent.click(screen.getByRole("button", { name: /^realtime/i }));putVoiceMode.mockClear();fireEvent.click(screen.getByRole("button", { name: /pipeline/i }));diff --git a/jarvis/ui/web/frontend/src/views/AutomationsView.test.tsx b/jarvis/ui/web/frontend/src/views/AutomationsView.test.tsxindex 43c2c71994..a7e296d6b1 100644--- a/jarvis/ui/web/frontend/src/views/AutomationsView.test.tsx+++ b/jarvis/ui/web/frontend/src/views/AutomationsView.test.tsx@@ -334,7 +334,12 @@ describe("AutomationsView", () => {locale: string;};expect(body.inputs).toEqual({ city: "Hamburg" });- expect(body.schedule).toEqual({ kind: "daily", time: "07:30", weekday: 0 });+ expect(body.schedule).toEqual({+ kind: "daily",+ time: "07:30",+ weekday: 0,+ timezone: expect.any(String),+ });expect(body.title).toBe("Morning briefing");expect(body.locale).toBe("en");});diff --git a/jarvis/ui/web/frontend/src/views/HomeView.tsx b/jarvis/ui/web/frontend/src/views/HomeView.tsxindex 7ba4e9269d..769cc20bd7 100644--- a/jarvis/ui/web/frontend/src/views/HomeView.tsx+++ b/jarvis/ui/web/frontend/src/views/HomeView.tsx@@ -6,8 +6,7 @@ import { ChatStage } from "@/components/home/ChatStage";/*** The front page — the "chats" section.*- * One header that carries the app chrome (the shell TopBar steps aside here,- * same rule as the IDE), and under it one of two stages chosen by the+ * One header for who is talking, and under it one of two stages chosen by the* `Voice | Chat` switch at the top of the sidebar (store/home.ts):** Voice — the Jarvis bar, centred, with the live transcript above it.diff --git a/jarvis/ui/web/frontend/src/views/JarvisAgentsView.test.tsx b/jarvis/ui/web/frontend/src/views/JarvisAgentsView.test.tsxnew file mode 100644index 0000000000..3d8ab4df6e--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/JarvisAgentsView.test.tsx@@ -0,0 +1,28 @@+import { cleanup, fireEvent, render, screen } from "@testing-library/react";+import { afterEach, expect, it, vi } from "vitest";+import { JarvisAgentsView } from "./JarvisAgentsView";++vi.mock("@/i18n", () => ({ useLocaleChunk: () => true }));+vi.mock("@/components/society/world/WorldStage", () => ({ WorldStage: () => { throw new Error("Legacy world must not mount"); } }));+vi.mock("@/components/society/mars/MarsWorldStage", () => ({ MarsWorldStage: ({ onOpenLedger, onOpenStation, stationPanel }: any) => <div data-testid="mars-map"><button onClick={onOpenLedger}>Open agents</button><button onClick={onOpenStation}>Open station</button>{stationPanel}</div> }));+vi.mock("@/components/society/mars/MarsStationPanel", () => ({ MarsStationPanel: ({ onClose }: any) => <aside aria-label="Mars station"><button onClick={onClose}>Close station</button></aside> }));+const initialUrl = window.location.href;+afterEach(() => { cleanup(); window.history.replaceState(null, "", initialUrl); });++it.each(["?view=agents", "?view=agents&world=legacy", "?view=agents&world=mars"])("uses only Mars in the normal app for %s", async (url) => {+ window.history.replaceState(null, "", url);+ const openAgents = vi.fn();+ render(<JarvisAgentsView onOpenAgents={openAgents} />);+ expect(await screen.findByTestId("mars-map")).toBeTruthy();+ expect(screen.queryByRole("button", { name: /previous|preview/i })).toBeNull();+ fireEvent.click(screen.getByText("Open agents"));+ expect(openAgents).toHaveBeenCalledOnce();+});++it("keeps the station usable within the replacement map", async () => {+ render(<JarvisAgentsView onOpenAgents={() => undefined} />);+ fireEvent.click(await screen.findByText("Open station"));+ expect(await screen.findByRole("complementary", { name: "Mars station" })).toBeTruthy();+ fireEvent.click(screen.getByText("Close station"));+ expect(screen.queryByRole("complementary", { name: "Mars station" })).toBeNull();+});diff --git a/jarvis/ui/web/frontend/src/views/JarvisAgentsView.tsx b/jarvis/ui/web/frontend/src/views/JarvisAgentsView.tsxindex 560f3554d4..3bc891bc8b 100644--- a/jarvis/ui/web/frontend/src/views/JarvisAgentsView.tsx+++ b/jarvis/ui/web/frontend/src/views/JarvisAgentsView.tsx@@ -1,10 +1,10 @@-/** Lazy map surface for the Agents section. */-import { Suspense, lazy } from "react";+/** Lazy map surface; the parent keeps the existing Agents workspace mounted. */+import { Suspense, lazy, useCallback, useState } from "react";+import { useLocaleChunk } from "@/i18n";import type { PlaceId } from "@/components/society/world/islandLayout";-const WorldStage = lazy(() =>- import("@/components/society/world/WorldStage").then((m) => ({ default: m.WorldStage })),-);+const MarsWorldStage = lazy(() => import("@/components/society/mars/MarsWorldStage").then((m) => ({ default: m.MarsWorldStage })));+const MarsStationPanel = lazy(() => import("@/components/society/mars/MarsStationPanel").then((m) => ({ default: m.MarsStationPanel })));export interface JarvisAgentsViewProps {onSelectAgent?: (agentId: string | null) => void;@@ -12,11 +12,18 @@ export interface JarvisAgentsViewProps {onOpenAgents: () => void;}-export function JarvisAgentsView({ onSelectAgent, onSelectPlace, onOpenAgents }: JarvisAgentsViewProps) {+export function JarvisAgentsView({ onSelectAgent, onOpenAgents }: JarvisAgentsViewProps) {+ const ready = useLocaleChunk("society");+ const [stationOpen, setStationOpen] = useState(false);+ const openStation = useCallback(() => setStationOpen(true), []);+ if (!ready) return null;return (<div className="h-full min-h-0"><Suspense fallback={<div className="h-full w-full animate-pulse bg-secondary" aria-hidden />}>- <WorldStage onOpenAgents={onOpenAgents} onSelectAgent={onSelectAgent} onSelectPlace={onSelectPlace} />+ <MarsWorldStage onOpenLedger={onOpenAgents}+ onSelectAgent={onSelectAgent} onOpenStation={openStation}+ stationPanel={stationOpen ? <MarsStationPanel onClose={() => setStationOpen(false)} onOpenAgent={onSelectAgent} /> : undefined}+ /></Suspense></div>);diff --git a/jarvis/ui/web/frontend/src/views/MissionDeckView.phases.test.tsx b/jarvis/ui/web/frontend/src/views/MissionDeckView.phases.test.tsxindex 827b8d6d04..408c568c6b 100644--- a/jarvis/ui/web/frontend/src/views/MissionDeckView.phases.test.tsx+++ b/jarvis/ui/web/frontend/src/views/MissionDeckView.phases.test.tsx@@ -198,11 +198,11 @@ describe("MissionDeckView — the three acts", { timeout: 15_000 }, () => {expect(requestVoiceCall).toHaveBeenCalledTimes(1);});- test("the header carries Gigi and the chrome actions — one row, not two", () => {+ test("the header carries Gigi and leaves restart to the window caption", () => {render(<MissionDeckView />);expect(screen.getByTestId("deck-header-gigi")).toBeTruthy();- expect(screen.getByRole("button", { name: /^restart$/i })).toBeTruthy();- expect(screen.getByTestId("detach-view-button")).toBeTruthy();+ expect(screen.queryByRole("button", { name: /^restart$/i })).toBeNull();+ expect(screen.queryByTestId("detach-view-button")).toBeNull();});test("a deck that mounts into a running session is simply the board — no reveal", () => {diff --git a/jarvis/ui/web/frontend/src/views/MissionDeckView.tsx b/jarvis/ui/web/frontend/src/views/MissionDeckView.tsxindex 010fed1581..bebb53736b 100644--- a/jarvis/ui/web/frontend/src/views/MissionDeckView.tsx+++ b/jarvis/ui/web/frontend/src/views/MissionDeckView.tsx@@ -13,8 +13,7 @@ import { useDeckStore } from "@/store/deck";import { VoiceWaveform, type WaveformPhase } from "@/components/overlay/VoiceWaveform";import { voiceInputLevelRef } from "@/lib/voiceInputLevel";import { DockRail } from "@/components/layout/DockRail";-import { TopBarActions } from "@/components/layout/TopBar";-import { CodingModeBadge } from "@/components/layout/CodingModeBadge";+import { GigiMark } from "@/components/GigiMark";import { DeckOrb, type OrbReadouts } from "@/components/deck/DeckOrb";import type { ThinkingStep } from "@/lib/thinkingSteps";@@ -242,9 +241,8 @@ export function MissionDeckView({return (<MotionConfig reducedMotion="user"><div className="flex h-full min-h-0 flex-col">- {/* One header. The shell TopBar steps aside on this screen (same- rule as the IDE): Gigi and the chrome actions live here so the- front page is not two bars with a hole between them. */}+ {/* The deck's own instruments. Theme, restart and the window buttons+ live in the window caption, not in a second row here. */}<header className="relative flex flex-wrap items-center gap-x-4 gap-y-2 px-4 py-2"><spanclassName="flex h-8 w-8 shrink-0 items-center justify-center"@@ -300,8 +298,6 @@ export function MissionDeckView({onClick={() => setActiveSection("apikeys")}/>{headerAccessory}- <CodingModeBadge />- <TopBarActions /></div><svgdiff --git a/jarvis/ui/web/frontend/src/views/PluginsView.test.tsx b/jarvis/ui/web/frontend/src/views/PluginsView.test.tsxindex b3a308cbc5..214ab8dd5b 100644--- a/jarvis/ui/web/frontend/src/views/PluginsView.test.tsx+++ b/jarvis/ui/web/frontend/src/views/PluginsView.test.tsx@@ -4,10 +4,12 @@ import { afterEach, describe, expect, it, vi } from "vitest";import {ConnectIconButton,+ matchesNamePrefix,matchesQuery,matchesStatus,PatConnectDialog,PkceConnectDialog,+ sortPluginsByName,type Plugin,PluginsView,} from "@/views/PluginsView";@@ -1082,6 +1084,45 @@ describe("plugin search matches more than the display name", () => {});});+describe("plugin prefix search lists G-starting plugins A-Z", () => {+ const make = (name: string, extra: Record<string, unknown> = {}): Plugin => ({+ id: name.toLowerCase().replace(/[^a-z0-9]+/g, "_"),+ name,+ description: "d",+ category: "Developer",+ logoSlug: "x",+ authMode: "pat_paste",+ authConfig: { mode: "pat_paste" },+ status: "not_connected",+ longevity: "permanent",+ oauthClientConfigured: false,+ fromMarketplace: false,+ selfUploaded: false,+ ...extra,+ });++ it("matches only names starting with the query, case-insensitive", () => {+ const gmail = make("Gmail");+ expect(matchesNamePrefix(gmail, "G")).toBe(true);+ expect(matchesNamePrefix(gmail, "g")).toBe(true);+ expect(matchesNamePrefix(gmail, "Gmail")).toBe(true);+ expect(matchesNamePrefix(make("AgentMail"), "G")).toBe(false);+ expect(matchesNamePrefix(make("Cal.com"), "g")).toBe(false);+ expect(matchesNamePrefix(make("Outlook Mail & Calendar"), "g")).toBe(false);+ });++ it("orders AA before AZ and sorts case-insensitively", () => {+ const names = ["AZ", "AA", "Gmail", "Google Drive", "Google Calendar"].map((n) => make(n));+ const sorted = [...names].sort(sortPluginsByName).map((p) => p.name);+ expect(sorted).toEqual(["AA", "AZ", "Gmail", "Google Calendar", "Google Drive"]);+ });++ it("matches the vendor family prefix, so 'google' still finds Gmail", () => {+ const gmail = make("Gmail", { id: "gmail" });+ expect(matchesNamePrefix(gmail, "google")).toBe(true);+ });+});+describe("plugin status filter", () => {const withStatus = (status: Plugin["status"]): Plugin => ({id: "p",diff --git a/jarvis/ui/web/frontend/src/views/PluginsView.tsx b/jarvis/ui/web/frontend/src/views/PluginsView.tsxindex d0b40cd19d..51e84dbf6f 100644--- a/jarvis/ui/web/frontend/src/views/PluginsView.tsx+++ b/jarvis/ui/web/frontend/src/views/PluginsView.tsx@@ -519,6 +519,29 @@ export function matchesQuery(plugin: Plugin, query: string): boolean {return words.every((word) => haystack.includes(word));}+/** Prefix match on the fields a user types first: plugin name, catalog id,+ * and vendor family label. A single letter such as "G" must list only the+ * plugins starting with G in A-Z order (AA on top, AZ at the bottom) instead+ * of every plugin whose description happens to contain that letter. */+export function matchesNamePrefix(plugin: Plugin, query: string): boolean {+ const normalized = query.trim().toLowerCase();+ if (normalized.length === 0) return true;+ const name = plugin.name.toLowerCase();+ if (name.startsWith(normalized)) return true;+ const id = plugin.id.toLowerCase();+ if (id.startsWith(normalized)) return true;+ const family = oauthClientFamily(plugin)?.label.toLowerCase() ?? "";+ if (family && family.startsWith(normalized)) return true;+ return false;+}++/** A-Z by display name, case-insensitive. Used whenever a search query is+ * active so "G" lists Gmail before Google Drive instead of grouping by+ * category. */+export function sortPluginsByName(a: Plugin, b: Plugin): number {+ return a.name.localeCompare(b.name, undefined, { sensitivity: "base" });+}+/** "attention" groups needs_reauth and error: both mean the same thing to the* user — this plugin is listed but cannot be called until they act. */export function matchesStatus(plugin: Plugin, status: StatusFilterId): boolean {@@ -887,6 +910,14 @@ export function PluginsView({ inDialog = false }: { inDialog?: boolean } = {}) {: listFilter === "attention"? attentionPlugins: allPlugins;+ const inCategory = (p: Plugin) => filter === "all" || p.category === filter;+ const trimmed = query.trim();+ if (trimmed !== "") {+ const candidates = base.filter(inCategory);+ const prefixed = candidates.filter((p) => matchesNamePrefix(p, trimmed));+ if (prefixed.length > 0) return [...prefixed].sort(sortPluginsByName);+ return candidates.filter((p) => matchesQuery(p, trimmed)).sort(sortPluginsByName);+ }const order = inDialog ? [...WINDOW_CATEGORY_ORDER, ...categoryOrder] : categoryOrder;const ranked = [...base].sort((a, b) =>order.indexOf(a.category) - order.indexOf(b.category)@@ -894,7 +925,7 @@ export function PluginsView({ inDialog = false }: { inDialog?: boolean } = {}) {);return ranked.filter((p) => {if (filter !== "all" && p.category !== filter) return false;- return matchesQuery(p, query);+ return true;});}, [listFilter, query, filter, allPlugins, installed, attentionPlugins, categoryOrder, inDialog]);diff --git a/jarvis/ui/web/frontend/src/views/SettingsHubView.test.tsx b/jarvis/ui/web/frontend/src/views/SettingsHubView.test.tsxindex 9c24ca1cff..4ccca9d9c6 100644--- a/jarvis/ui/web/frontend/src/views/SettingsHubView.test.tsx+++ b/jarvis/ui/web/frontend/src/views/SettingsHubView.test.tsx@@ -25,6 +25,7 @@ vi.mock("@/i18n", () => ({// Identity translator: labels resolve to their keys (or the English// fallback where the nav item defines one), so assertions match keys.useT: () => (key: string) => key,+ useUiLanguage: () => "en",}));vi.mock("@/hooks/useProviders", async (importOriginal) => {@@ -62,7 +63,11 @@ function stub(testid: string) {return () => <div data-testid={testid}>{testid}</div>;}-vi.mock("@/views/SettingsView", () => ({ SettingsView: stub("TAB_SETTINGS") }));+vi.mock("@/views/SettingsView", () => ({+ SettingsView: ({ searchTarget }: { searchTarget?: string }) => (+ <div data-testid="TAB_SETTINGS" data-search-target={searchTarget} />+ ),+}));vi.mock("@/views/ProfileView", () => ({ ProfileView: stub("TAB_PROFILE") }));vi.mock("@/views/AgentInstructionsView", () => ({AgentInstructionsView: stub("TAB_INSTRUCTIONS"),@@ -111,6 +116,15 @@ afterEach(() => {});describe("SettingsHubView header and navigation", () => {+ it("separates the navigation from the content and returns to the app", async () => {+ render(<SettingsHubView />);+ await screen.findByTestId("TAB_SETTINGS");+ expect(screen.getByTestId("settings-hub-sidebar").className).toContain("jarvis-nav-surface");+ expect(screen.getByTestId("settings-hub-content").parentElement?.className).toContain("jarvis-sheet");+ fireEvent.click(screen.getByRole("button", { name: "settings_hub.back_to_app" }));+ expect(mockState.setActiveSection).toHaveBeenCalledWith("chats");+ });+it("renders exactly one header titled from nav.settings", async () => {render(<SettingsHubView />);@@ -201,6 +215,39 @@ describe("SettingsHubView tab resolution", () => {});describe("SettingsHubView search", () => {+ it("finds a field on another Settings page", async () => {+ render(<SettingsHubView />);+ await screen.findByTestId("TAB_SETTINGS");+ fireEvent.change(screen.getByPlaceholderText("settings_hub.search_placeholder"), {+ target: { value: "What is it?" },+ });+ fireEvent.click(screen.getByTestId("settings-hub-page-feedback"));+ expect(mockState.setActiveSection).toHaveBeenCalledWith("feedback");+ });++ it("finds an option inside Settings and opens its group", async () => {+ render(<SettingsHubView />);+ await screen.findByTestId("TAB_SETTINGS");++ fireEvent.change(screen.getByPlaceholderText("settings_hub.search_placeholder"), {+ target: { value: "Microphone" },+ });+ fireEvent.click(screen.getByTestId("settings-hub-option-audio-devices"));++ expect(mockState.setActiveSection).toHaveBeenCalledWith("settings");+ expect(screen.getByTestId("TAB_SETTINGS").getAttribute("data-search-target"))+ .toBe("audio-devices");+ });++ it("reports when neither pages nor options match", async () => {+ render(<SettingsHubView />);+ await screen.findByTestId("TAB_SETTINGS");+ fireEvent.change(screen.getByPlaceholderText("settings_hub.search_placeholder"), {+ target: { value: "zzz-unmatched-setting" },+ });+ expect(screen.getByRole("status").textContent).toBe("settings_hub.no_results");+ });+it("filters the nav entries by label", async () => {mockState.activeSection = "settings";render(<SettingsHubView />);diff --git a/jarvis/ui/web/frontend/src/views/SettingsHubView.tsx b/jarvis/ui/web/frontend/src/views/SettingsHubView.tsxindex 9cbdba487e..0a39fc3339 100644--- a/jarvis/ui/web/frontend/src/views/SettingsHubView.tsx+++ b/jarvis/ui/web/frontend/src/views/SettingsHubView.tsx@@ -1,16 +1,16 @@import { lazy, Suspense, useMemo, useState, type ComponentType, type LazyExoticComponent } from "react";-import { Loader2, Settings as SettingsIcon } from "lucide-react";+import { ArrowLeft, Loader2, Search, Settings as SettingsIcon, X } from "lucide-react";import {NAV_FOOTER_ITEMS,NAV_GROUPS,resolveNavLabel,type NavItem,} from "@/components/layout/navGroups";-import { InlineSearch } from "@/components/extensions/primitives";import { useEventStore } from "@/store/events";import { useSectionHealth } from "@/hooks/useProviders";-import { useT } from "@/i18n";+import { useT, useUiLanguage } from "@/i18n";import { ViewHeader } from "@/views/ChatsView";+import { searchSettingsOptions, searchSettingsPages } from "@/views/settings/settingsSearch";import { cn } from "@/lib/utils";/**@@ -187,9 +187,11 @@ function HubLoadingFallback() {export function SettingsHubView() {const t = useT();+ const language = useUiLanguage();const active = useEventStore((s) => s.activeSection);const setActive = useEventStore((s) => s.setActiveSection);const [query, setQuery] = useState("");+ const [searchTarget, setSearchTarget] = useState<string | null>(null);const { health: sectionHealth } = useSectionHealth();const { content, highlight } = resolveHubTab(active);@@ -204,12 +206,17 @@ export function SettingsHubView() {...group,items: group.ids.map(findNavItem).filter(matches),})).filter((group) => group.items.length > 0);+ const optionMatches = searchSettingsOptions(language, query, t);+ const pageMatches = searchSettingsPages(language, query, t)+ .filter((match) => !visibleGroups.some((group) =>+ group.items.some((item) => item.id === match.id)))+ .map((match) => ({ ...match, label: resolveNavLabel(t, findNavItem(match.id)) }));// The same two health signals the sidebar rows used to carry, now on the// hub's own nav: a hard provider error on API Keys, a failing or// half-configured local setup on Local models. Badge only, never a toast.const apikeysHasError = useMemo(- () => Object.values(sectionHealth).some((h) => h?.status === "error"),+ () => Object.entries(sectionHealth).some(([section, health]) => section !== "computer-use" && health?.status === "error"),[sectionHealth],);const localModelsHealth = sectionHealth.local_models;@@ -231,7 +238,11 @@ export function SettingsHubView() {<buttontype="button"data-testid={`settings-hub-nav-${item.id}`}- onClick={() => setActive(item.id)}+ onClick={() => {+ setQuery("");+ setSearchTarget(null);+ setActive(item.id);+ }}title={hint}aria-current={isActive ? "page" : undefined}className={cn(@@ -271,46 +282,113 @@ export function SettingsHubView() {};return (- <div data-testid="settings-hub" className="flex h-full flex-col">- <ViewHeader- icon={<SettingsIcon className="h-4 w-4 text-foreground" />}- title={t("nav.settings")}- subtitle={t("settings_hub.subtitle")}- right={- <div className="w-64 max-w-full">- <InlineSearch- value={query}- onChange={setQuery}+ <div data-testid="settings-hub" className="flex h-full min-h-0 flex-col md:flex-row">+ <aside+ data-testid="settings-hub-sidebar"+ className="jarvis-nav-surface flex max-h-72 w-full shrink-0 flex-col border-b border-border md:max-h-none md:w-72 md:border-b-0"+ >+ <div className="border-b border-border px-3 py-3">+ <button type="button" onClick={() => setActive("chats")}+ className="flex h-9 w-full items-center gap-2 rounded-md px-2 text-base font-medium text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">+ <ArrowLeft className="h-4 w-4 shrink-0" aria-hidden />+ {t("settings_hub.back_to_app")}+ </button>+ </div>+ <div className="px-3 pb-2 pt-3">+ <div className="relative">+ <Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" aria-hidden />+ <input type="text" role="searchbox" value={query} onChange={(event) => setQuery(event.target.value)}+ onKeyDown={(event) => { if (event.key === "Escape") setQuery(""); }}placeholder={t("settings_hub.search_placeholder")}+ aria-label={t("settings_hub.search_placeholder")}+ className="h-9 w-full rounded-md border border-border bg-input pl-9 pr-9 text-base text-foreground placeholder:text-foreground-faint focus:border-accent focus:outline-none focus:ring-2 focus:ring-ring"/>+ {query && <button type="button" onClick={() => setQuery("")}+ aria-label={t("settings_hub.clear_search")}+ className="absolute right-1 top-1/2 flex h-7 w-7 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">+ <X className="h-4 w-4" aria-hidden />+ </button>}</div>- }- />- <div className="flex min-h-0 flex-1 flex-col gap-4 px-8 pb-8 md:flex-row">- <nav- aria-label={t("nav.settings")}- className="shrink-0 overflow-x-auto scrollbar-jarvis md:w-60 md:overflow-y-auto lg:w-64"- >- {/* Narrow screens stack the nav above the content as one horizontal- strip; from `md` up it is the fixed left column of the page. */}- <ul className="flex gap-1 md:flex-col md:gap-0">+ </div>+ <nav aria-label={t("nav.settings")}+ className="min-h-0 flex-1 overflow-y-auto px-3 pb-5 scrollbar-jarvis">+ <ul className="space-y-1">{visibleGroups.map((group) => (- <li key={group.labelKey} className="flex shrink-0 gap-1 md:block md:shrink md:gap-0">- <p className="hidden px-3 pb-1 pt-4 text-sm font-medium uppercase tracking-wide text-foreground-faint md:block">+ <li key={group.labelKey}>+ <p className="px-3 pb-1 pt-4 text-sm font-medium uppercase tracking-wide text-foreground-faint">{t(group.labelKey)}</p>- <ul className="flex gap-1 md:block md:space-y-0.5 md:gap-0">- {group.items.map(renderNavItem)}- </ul>+ <ul className="space-y-0.5">{group.items.map(renderNavItem)}</ul></li>))}</ul>+ {pageMatches.length > 0 && (+ <div data-testid="settings-hub-page-results">+ <p className="px-3 pb-1 pt-5 text-sm font-medium uppercase tracking-wide text-foreground-faint">+ {t("settings_hub.search_pages")}+ </p>+ <ul className="space-y-0.5">+ {pageMatches.map((match) => (+ <li key={match.id}>+ <button type="button" data-testid={`settings-hub-page-${match.id}`}+ onClick={() => {+ setSearchTarget(null);+ setQuery("");+ setActive(match.id);+ }}+ className="flex w-full flex-col rounded-md px-3 py-2 text-left transition-colors hover:bg-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">+ <span className="text-base font-medium text-foreground">{match.label}</span>+ {match.detail && <span className="w-full truncate text-sm text-muted-foreground" title={match.detail}>{match.detail}</span>}+ </button>+ </li>+ ))}+ </ul>+ </div>+ )}+ {optionMatches.length > 0 && (+ <div data-testid="settings-hub-option-results">+ <p className="px-3 pb-1 pt-5 text-sm font-medium uppercase tracking-wide text-foreground-faint">+ {t("settings_hub.search_results")}+ </p>+ <ul className="space-y-0.5">+ {optionMatches.map((match) => (+ <li key={match.id}>+ <button type="button" data-testid={`settings-hub-option-${match.id}`}+ onClick={() => {+ setSearchTarget(match.id);+ setQuery("");+ setActive("settings");+ }}+ className="flex w-full flex-col rounded-md px-3 py-2 text-left transition-colors hover:bg-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">+ <span className="text-base font-medium text-foreground">{match.label}</span>+ {match.detail && <span className="w-full truncate text-sm text-muted-foreground" title={match.detail}>{match.detail}</span>}+ </button>+ </li>+ ))}+ </ul>+ </div>+ )}+ {needle && visibleGroups.length === 0 && pageMatches.length === 0 && optionMatches.length === 0 && (+ <p role="status" className="px-3 py-5 text-base text-muted-foreground">+ {t("settings_hub.no_results")}+ </p>+ )}</nav>- <div- data-testid="settings-hub-content"- className="min-h-0 flex-1 overflow-y-auto scrollbar-jarvis"- >- <Suspense fallback={<HubLoadingFallback />}>{<Content />}</Suspense>+ </aside>+ <div className="jarvis-sheet flex min-h-0 min-w-0 flex-1 flex-col">+ <ViewHeader+ icon={<SettingsIcon className="h-4 w-4 text-foreground" />}+ title={t("nav.settings")}+ subtitle={t("settings_hub.subtitle")}+ />+ <div data-testid="settings-hub-content" className="min-h-0 flex-1 overflow-y-auto scrollbar-jarvis">+ <div className="h-full w-full max-w-[2000px]">+ <Suspense fallback={<HubLoadingFallback />}>+ {content === "settings"+ ? <SettingsTab searchTarget={searchTarget} onSearchTargetHandled={() => setSearchTarget(null)} />+ : <Content />}+ </Suspense>+ </div></div></div></div>diff --git a/jarvis/ui/web/frontend/src/views/SettingsView.tsx b/jarvis/ui/web/frontend/src/views/SettingsView.tsxindex 6a40711cc5..5ed69cfcef 100644--- a/jarvis/ui/web/frontend/src/views/SettingsView.tsx+++ b/jarvis/ui/web/frontend/src/views/SettingsView.tsx@@ -72,7 +72,10 @@ interface SettingRow {value?: string;}-export function SettingsView() {+export function SettingsView({ searchTarget, onSearchTargetHandled }: {+ searchTarget?: string | null;+ onSearchTargetHandled?: () => void;+} = {}) {const t = useT();const scrollRef = useRef<HTMLDivElement>(null);const [activeSection, setActiveSection] = useState<string>(SECTIONS[0].id);@@ -105,6 +108,14 @@ export function SettingsView() {document.getElementById(`settings-${id}`)?.scrollIntoView({ block: "start", behavior: "smooth" });}, []);+ useEffect(() => {+ if (!searchTarget) return;+ const target = document.getElementById(`settings-${searchTarget}`);+ if (!target) return;+ target.scrollIntoView?.({ block: "start", behavior: "smooth" });+ onSearchTargetHandled?.();+ }, [searchTarget, onSearchTargetHandled]);+return (<div className="flex h-full min-h-0 flex-col"><div className="px-8">diff --git a/jarvis/ui/web/frontend/src/views/settings/SettingsResilience.test.tsx b/jarvis/ui/web/frontend/src/views/settings/SettingsResilience.test.tsxindex 5ba9ce1846..451c094c9a 100644--- a/jarvis/ui/web/frontend/src/views/settings/SettingsResilience.test.tsx+++ b/jarvis/ui/web/frontend/src/views/settings/SettingsResilience.test.tsx@@ -109,6 +109,38 @@ describe("SettingsGroupBoundary", () => {});describe("SettingsView against an empty backend", () => {+ it("scrolls to a searched settings group after the view mounts", async () => {+ vi.stubGlobal("fetch", vi.fn(async () => ({+ ok: true,+ status: 200,+ json: async () => ({}),+ text: async () => "{}",+ }) as Response));+ vi.spyOn(console, "error").mockImplementation(() => {});+ const scrollIntoView = vi.fn();+ const previous = HTMLElement.prototype.scrollIntoView;+ Object.defineProperty(HTMLElement.prototype, "scrollIntoView", {+ configurable: true,+ value: scrollIntoView,+ });+ const handled = vi.fn();++ try {+ render(wrap(<SettingsView searchTarget="audio-devices" onSearchTargetHandled={handled} />));+ await waitFor(() => expect(scrollIntoView).toHaveBeenCalledOnce());+ expect(handled).toHaveBeenCalledOnce();+ } finally {+ if (previous) {+ Object.defineProperty(HTMLElement.prototype, "scrollIntoView", {+ configurable: true,+ value: previous,+ });+ } else {+ delete (HTMLElement.prototype as { scrollIntoView?: unknown }).scrollIntoView;+ }+ }+ });+it("renders the whole page when every route answers {}", async () => {// The shape no group expects — the worst case of a version skew.vi.stubGlobal(diff --git a/jarvis/ui/web/frontend/src/views/settings/settingsSearch.test.ts b/jarvis/ui/web/frontend/src/views/settings/settingsSearch.test.tsnew file mode 100644index 0000000000..f8b1319021--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/settings/settingsSearch.test.ts@@ -0,0 +1,26 @@+import { describe, expect, it } from "vitest";+import { searchSettingsOptions, searchSettingsPages } from "./settingsSearch";++const translate = (key: string) => key;++describe("searchSettingsOptions", () => {+ it("finds labels inside a Settings group", () => {+ const matches = searchSettingsOptions("en", "microphone", translate);+ expect(matches.some((match) => match.id === "audio-devices" && match.detail === "Microphone"))+ .toBe(true);+ });++ it("finds localized options in the selected UI language", () => {+ const matches = searchSettingsOptions("de", "Denkpause", translate);+ expect(matches.some((match) => match.id === "silence-window")).toBe(true);+ });++ it("finds a field in another Settings page", () => {+ const matches = searchSettingsPages("en", "What is it?", translate);+ expect(matches.some((match) => match.id === "feedback")).toBe(true);+ });++ it("ignores empty queries", () => {+ expect(searchSettingsOptions("en", " ", translate)).toEqual([]);+ });+});diff --git a/jarvis/ui/web/frontend/src/views/settings/settingsSearch.ts b/jarvis/ui/web/frontend/src/views/settings/settingsSearch.tsnew file mode 100644index 0000000000..a2d0dc3a44--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/settings/settingsSearch.ts@@ -0,0 +1,106 @@+import en from "@/i18n/locales/en.json";+import de from "@/i18n/locales/de.json";+import es from "@/i18n/locales/es.json";+import type { UiLanguage } from "@/i18n";++type LocaleTree = Record<string, unknown>;++const LOCALES: Record<UiLanguage, LocaleTree> = { en, de, es };++/** Each Settings page group owns the copy used to search its controls. */+const SEARCH_GROUPS = [+ { id: "languages", keys: ["language", "languages_group_title"] },+ { id: "app", keys: ["app_settings_group_title", "autostart", "appearance", "jarvis_api"] },+ { id: "permissions", keys: ["nav.permissions"] },+ { id: "screen-context", keys: ["screen_context"] },+ { id: "realtime-voice", keys: ["realtime_voice"] },+ { id: "system-prompt", keys: ["system_prompt"] },+ { id: "wake-word", keys: ["wake_word"] },+ { id: "silence-window", keys: ["silence_window"] },+ { id: "volume", keys: ["volume"] },+ { id: "audio-devices", keys: ["audio_devices"] },+ { id: "music", keys: ["music", "music_group_title"] },+ { id: "keybinds", keys: ["keybinds"] },+ { id: "more", keys: ["rows", "team_proxy", "codex_title", "safety_title"] },+ { id: "overlay-taskbar", keys: ["overlay_style", "bar_size", "overlay_taskbar_group_title"] },+] as const;++const SEARCH_PAGES = [+ { id: "profile", keys: ["profile_view"] },+ { id: "agent-instructions", keys: ["agent_instructions"] },+ { id: "contacts", keys: ["contacts"] },+ { id: "socials", keys: ["socials"] },+ { id: "apikeys", keys: ["apikeys_view", "apikeys_voice", "apikeys_model", "apikeys_cu_model"] },+ { id: "wallpaper", keys: ["home.background_label", "home.background_hint"] },+ { id: "costs", keys: ["costs_view"] },+ { id: "feedback", keys: ["feedback"] },+] as const;++export interface SettingsOptionMatch {+ id: string;+ label: string;+ detail?: string;+}++function normalize(value: string): string {+ return value.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase();+}++function atPath(tree: LocaleTree, path: string): unknown {+ return path.split(".").reduce<unknown>((node, part) =>+ node && typeof node === "object" ? (node as LocaleTree)[part] : undefined, tree);+}++function stringsIn(node: unknown): string[] {+ if (typeof node === "string") return [node];+ if (!node || typeof node !== "object") return [];+ return Object.values(node).flatMap(stringsIn);+}++function matchingCopy(tree: LocaleTree, keys: readonly string[], needle: string): string[] {+ return keys.flatMap((key) => stringsIn(atPath(tree, key)))+ .filter((value) => normalize(value).includes(needle));+}++function shortDetail(matches: string[], label: string): string | undefined {+ const detail = matches.filter((value) => value !== label)+ .sort((a, b) => a.length - b.length)[0];+ return detail && detail.length <= 100 ? detail : undefined;+}++/** Search localized option copy, not just the ten Settings tab names. */+export function searchSettingsOptions(+ language: UiLanguage,+ query: string,+ translate: (key: string) => string,+): SettingsOptionMatch[] {+ const needle = normalize(query.trim());+ if (!needle) return [];+ const settings = atPath(LOCALES[language], "settings_view") as LocaleTree;++ return SEARCH_GROUPS.flatMap(({ id, keys }) => {+ const label = translate(`settings_view.nav.${id.replaceAll("-", "_")}`);+ const matches = matchingCopy(settings, keys, needle);+ if (!normalize(label).includes(needle) && matches.length === 0) return [];+ // Prefer a control label to a long explanation or a saved-state toast.+ return [{ id, label, detail: shortDetail(matches, label) }];+ });+}++/** Search the other Settings pages' localized field copy. */+export function searchSettingsPages(+ language: UiLanguage,+ query: string,+ translate: (key: string) => string,+) {+ const needle = normalize(query.trim());+ if (!needle) return [];+ const locale = LOCALES[language];++ return SEARCH_PAGES.flatMap(({ id, keys }) => {+ const label = translate(`nav.${id === "agent-instructions" ? "agent_instructions" : id}`);+ const matches = matchingCopy(locale, keys, needle);+ if (!normalize(label).includes(needle) && matches.length === 0) return [];+ return [{ id, label, detail: shortDetail(matches, label) }];+ });+}diff --git a/jarvis/ui/web/frontend/src/views/society/SocietyView.test.tsx b/jarvis/ui/web/frontend/src/views/society/SocietyView.test.tsxindex b231fe1333..a75e88e12a 100644--- a/jarvis/ui/web/frontend/src/views/society/SocietyView.test.tsx+++ b/jarvis/ui/web/frontend/src/views/society/SocietyView.test.tsx@@ -1,9 +1,13 @@import { cleanup, fireEvent, render, screen, within } from "@testing-library/react";-import { afterEach, expect, it, vi } from "vitest";+import { afterEach, beforeEach, expect, it, vi } from "vitest";import { setMapFullscreen } from "@/lib/mapFullscreen";import { LAST_AGENT_STORAGE_KEY } from "./lastAgent";import { SocietyView } from "./SocietyView";+const app = vi.hoisted(() => ({ instance: { name: "default", isDev: false } }));+vi.mock("@/hooks/useAppInstance", () => ({ useAppInstance: () => app.instance }));+beforeEach(() => { app.instance = { name: "default", isDev: false }; });+vi.mock("@/lib/mapFullscreen", () => ({ setMapFullscreen: vi.fn(async () => undefined) }));vi.mock("@/i18n", () => ({ useT: () => (key: string) => key, useLocaleChunk: () => true }));vi.mock("@/components/society/chat/useModelMenuData", () => ({ useModelMenuData: () => undefined }));@@ -11,9 +15,10 @@ vi.mock("@/components/society/data", () => ({ useSocietyRoster: () => ({ data: {{ agentId: "lead", name: "Lead", tier: "lead", state: "idle" },{ agentId: "specialist", name: "Specialist", tier: "specialist", state: "idle" },] }, isLoading: false }) }));-vi.mock("@/views/JarvisAgentsView", () => ({ JarvisAgentsView: ({ onSelectAgent, onOpenAgents }: any) => (- <div data-testid="map"><button onClick={() => onSelectAgent("specialist")}>Map specialist</button><button onClick={onOpenAgents}>Map fallback</button></div>+vi.mock("@/views/JarvisAgentsView", () => ({ JarvisAgentsView: ({ onSelectAgent, onOpenAgents, onMarsSelectionChange }: any) => (+ <div data-testid="map"><button onClick={() => onSelectAgent("specialist")}>Map specialist</button><button onClick={onOpenAgents}>Map fallback</button><div data-mars-ui><input aria-label="Mars draft" /></div><div data-mars-mode="player"><button>Player viewport</button></div><div data-mars-mode="follow"><button>Follow viewport</button></div><button onClick={() => onMarsSelectionChange(false)}>Previous world</button><button onClick={() => onMarsSelectionChange(true)}>Mars world</button></div>) }));+vi.mock("@/components/society/mars/MarsStationPanel", () => ({ MarsStationPanel: ({ onClose }: any) => <aside aria-label="Mars station"><button onClick={onClose}>Close station</button></aside> }));vi.mock("@/components/society/card/AgentCardOverlay", () => ({ AgentCardOverlay: ({ agent, embedded, onSelectAgent, onCreate, railHeader }: any) => (<div data-testid="workspace" data-embedded={String(embedded)}>{railHeader}@@ -26,10 +31,8 @@ vi.mock("@/components/society/roster/RosterRail", () => ({ RosterRail: () => <divi.mock("@/components/society/card/BuildingCardOverlay", () => ({ BuildingCardOverlay: () => null }));vi.mock("@/components/society/create/CreateAgentDialog", () => ({ CreateAgentDialog: ({ open, onClose }: any) => open ? <button onClick={onClose}>Close creator</button> : null }));-afterEach(() => {- cleanup();- localStorage.removeItem(LAST_AGENT_STORAGE_KEY);-});+const initialUrl = window.location.href;+afterEach(() => { cleanup(); window.history.replaceState(null, "", initialUrl); localStorage.removeItem(LAST_AGENT_STORAGE_KEY); });it("defaults to the embedded Agents workspace even with a saved legacy ledger preference", () => {localStorage.setItem("jarvis.agents.mode.v2", "ledger");@@ -113,3 +116,61 @@ it("requests fullscreen for Map and leaves it on Escape", async () => {expect(setMapFullscreen).toHaveBeenLastCalledWith(false);expect(screen.queryByTestId("map")).toBeNull();});++it("keeps Mars station controls reachable without mounting a renderer", async () => {+ window.history.replaceState(null, "", "?view=agents&world=mars");+ render(<SocietyView />);+ fireEvent.click(screen.getByRole("button", { name: "society.mars.station_title" }));+ expect(await screen.findByRole("complementary", { name: "Mars station" })).toBeTruthy();+ expect(screen.queryByTestId("map")).toBeNull();+ expect(screen.getByTestId("workspace")).toBeTruthy();+ fireEvent.click(screen.getByText("Close station"));+ expect(screen.queryByRole("complementary", { name: "Mars station" })).toBeNull();+});++it("exposes the Mars station in dev without an opt-in URL", async () => {+ app.instance = { name: "dev", isDev: true };+ window.history.replaceState(null, "", "?view=agents");+ render(<SocietyView />);+ fireEvent.click(screen.getByRole("button", { name: "society.mars.station_title" }));+ expect(await screen.findByRole("complementary", { name: "Mars station" })).toBeTruthy();+ expect(screen.queryByTestId("map")).toBeNull();+});++it("does not discard a Mars form when Escape belongs to its input", async () => {+ render(<SocietyView />);+ fireEvent.click(screen.getByRole("tab", { name: "society.world.mode_map" }));+ const field = await screen.findByLabelText("Mars draft");+ fireEvent.change(field, { target: { value: "Unsent station draft" } });+ fireEvent.keyDown(field, { key: "Escape" });+ expect(screen.getByTestId("map")).toBeTruthy();+ expect((field as HTMLInputElement).value).toBe("Unsent station draft");+ fireEvent.keyDown(document, { key: "Escape" });+ expect(screen.queryByTestId("map")).toBeNull();+});++it.each(["Mars draft", "Player viewport", "Follow viewport"])("preserves focused %s when the browser exits fullscreen without a keydown", async (target) => {+ render(<SocietyView />);+ fireEvent.click(screen.getByRole("tab", { name: "society.world.mode_map" }));+ const field = await screen.findByLabelText("Mars draft");+ fireEvent.change(field, { target: { value: "Unsent station draft" } });+ const focused = target === "Mars draft" ? field : screen.getByText(target);+ focused.focus();+ expect(document.fullscreenElement).toBeFalsy();+ fireEvent(document, new Event("fullscreenchange"));+ expect(screen.getByTestId("map")).toBeTruthy();+ expect(screen.getByLabelText("Mars draft")).toBe(field);+ expect((field as HTMLInputElement).value).toBe("Unsent station draft");+ fireEvent.click(screen.getByRole("tab", { name: "society.roster.title" }));+ expect(screen.queryByTestId("map")).toBeNull();+});++it("still leaves the ordinary map when browser fullscreen exits", async () => {+ render(<SocietyView />);+ fireEvent.click(screen.getByRole("tab", { name: "society.world.mode_map" }));+ await screen.findByTestId("map");+ fireEvent(document, new Event("fullscreenchange"));+ expect(screen.queryByTestId("map")).toBeNull();+});++diff --git a/jarvis/ui/web/frontend/src/views/society/SocietyView.tsx b/jarvis/ui/web/frontend/src/views/society/SocietyView.tsxindex 40da934d99..946bea6877 100644--- a/jarvis/ui/web/frontend/src/views/society/SocietyView.tsx+++ b/jarvis/ui/web/frontend/src/views/society/SocietyView.tsx@@ -1,4 +1,5 @@import { lazy, Suspense, useCallback, useMemo, useState, useEffect } from "react";+import { createPortal } from "react-dom";import { useSocietyShell } from "@/store/societyShell";import { setMapFullscreen } from "@/lib/mapFullscreen";@@ -19,11 +20,18 @@ const JarvisAgentsBoard = lazy(() =>import("@/views/JarvisAgentsView").then((m) => ({ default: m.JarvisAgentsView })),);+const MarsStationPanel = lazy(() => import("@/components/society/mars/MarsStationPanel").then((m) => ({ default: m.MarsStationPanel })));++function isProtectedMarsInteraction(target: EventTarget | null): boolean {+ return target instanceof Element && Boolean(target.closest("[data-mars-ui], [data-mars-mode=\'player\'], [data-mars-mode=\'follow\']"));+}+export function SocietyView() {useModelMenuData();const t = useT();useLocaleChunk("society");const [mode, setMode] = useState<"agents" | "world">("agents");+ const [marsStationOpen, setMarsStationOpen] = useState(false);const roster = useSocietyRoster();const agents = useMemo(() => roster.data?.agents ?? [], [roster.data]);const sample = roster.data?.sample ?? true;@@ -56,7 +64,7 @@ export function SocietyView() {const switchMode = useCallback((next: "agents" | "world") => {setMode(next);setFullscreenError(false);- void setMapFullscreen(next === "world").catch(() => setFullscreenError(true));+ if (inDesktopShell()) void setMapFullscreen(next === "world").catch(() => setFullscreenError(true));}, []);useEffect(() => {@@ -72,10 +80,10 @@ export function SocietyView() {useEffect(() => {const onKey = (event: KeyboardEvent) => {- if (event.key === "Escape" && mode === "world" && !openPlace && !creating) switchMode("agents");+ if (event.key === "Escape" && !event.defaultPrevented && !isProtectedMarsInteraction(event.target) && mode === "world" && !openPlace && !creating) switchMode("agents");};const onFullscreen = () => {- if (!document.fullscreenElement && !inDesktopShell()) setMode("agents");+ if (!document.fullscreenElement && !inDesktopShell() && !isProtectedMarsInteraction(document.activeElement)) setMode("agents");};document.addEventListener("keydown", onKey);document.addEventListener("fullscreenchange", onFullscreen);@@ -111,15 +119,18 @@ export function SocietyView() {);return (- <div className={mode === "world" ? "fixed inset-x-0 bottom-0 top-8 z-30 flex flex-col bg-background" : "flex h-full min-h-0 w-full flex-col"} data-testid="society-view">+ <div className={mode === "world" ? "fixed inset-x-0 bottom-0 top-8 z-30 flex flex-col bg-background" : "relative flex h-full min-h-0 w-full flex-col"} data-testid="society-view"><div className="flex min-h-0 min-w-0 flex-1 flex-col">{/* Map mode takes the native window fullscreen, so the switch cannotlive inside the map HUD: it would shrink into the corner and strandthe user on the island. It rides in the window caption in BOTHmodes — one switch, always centered, always a way back. */}- <div className="pointer-events-none fixed inset-x-0 top-0 z-[130] flex h-8 items-center justify-center" data-testid="mode-switch">- <div className="pointer-events-auto">{modeSwitch}</div>- </div>+ {createPortal(+ <div className="pointer-events-none fixed inset-x-0 top-0 z-[140] flex h-8 items-center justify-center" data-testid="mode-switch">+ <div className="pointer-events-auto flex items-center gap-2">{modeSwitch}{mode === "agents" && <button type="button" onClick={() => setMarsStationOpen(true)} className="rounded border border-border bg-background px-2 py-1 text-xs text-foreground">{t("society.mars.station_title")}</button>}</div>+ </div>,+ document.body,+ )}{fullscreenError && <p role="alert" className="bg-card px-4 py-2 text-sm text-destructive">{t("society.world.fullscreen_failed")}</p>}{mode === "world" ? (<div className="relative flex min-h-0 flex-1">@@ -153,6 +164,7 @@ export function SocietyView() {setCreating(true);}}/>+ {mode === "agents" && marsStationOpen && <div className="absolute right-4 top-14 z-40 max-h-[calc(100%-4rem)] w-[min(26rem,calc(100%-2rem))] overflow-auto" data-mars-ui><Suspense fallback={null}><MarsStationPanel onClose={() => setMarsStationOpen(false)} onOpenAgent={(id) => { selectAgent(id); setMarsStationOpen(false); }} /></Suspense></div>}<CreateAgentDialog open={creating} onClose={() => setCreating(false)} onCreated={onCreated} /></div>);diff --git a/jarvis/ui/web/launcher.py b/jarvis/ui/web/launcher.pyindex e1b5511406..6998676782 100644--- a/jarvis/ui/web/launcher.py+++ b/jarvis/ui/web/launcher.py@@ -1765,6 +1765,9 @@ def _main(argv: list[str] | None = None) -> int:# From here on every desktop launch is written down — see the helper.if not args.headless:+ from jarvis.ui.relauncher import remember_desktop_launch_args # noqa: PLC0415++ remember_desktop_launch_args(port=args.port, dev=args.dev, no_lock=args.no_lock)_install_boot_trace(_raw_argv)# Refuse a window we cannot build, BEFORE paying for the boot. Everythingdiff --git a/jarvis/ui/web/mars_routes.py b/jarvis/ui/web/mars_routes.pynew file mode 100644index 0000000000..c5314bff4b--- /dev/null+++ b/jarvis/ui/web/mars_routes.py@@ -0,0 +1,451 @@+"""Authenticated Mars world definition and durable draft-station control surface."""++from __future__ import annotations++import asyncio+import logging+from collections.abc import Awaitable, Callable+from pathlib import Path+from typing import Any++from fastapi import APIRouter, HTTPException, Query, Request+from fastapi.exceptions import RequestValidationError+from fastapi.responses import JSONResponse+from fastapi.routing import APIRoute+from starlette.responses import Response++from jarvis.society.mars.definition import load_definition+from jarvis.society.mars.models import (+ CommandRecord,+ Identity,+ StationCommand,+ StationError,+ StationEventBatch,+ StationSnapshot,+)+from jarvis.society.mars.navigation_models import (+ NavigationRecord,+ NavigationSnapshot,+ PedestrianMoveCommand,+ RoverActionCommand,+ RoverReserveCommand,+ RoverRideRecord,+ RoverTravelCommand,+)++log = logging.getLogger(__name__)++_INITIALIZATION_TIMEOUT_S = 30.0+_INITIALIZATION_STOP_TIMEOUT_S = 5.0+_NAVIGATION_TICK_S = 0.25+++class _PrivateStationRoute(APIRoute):+ """Keep malformed private drafts out of FastAPI's rejected-input echo.++ A request can fail validation before the station's credential guard runs.+ Even error locations may contain a user-supplied extra field name, so no+ input, location, exception text or context is copied into the response.+ The declared endpoint models still generate the normal OpenAPI schema.+ """++ def get_route_handler(self) -> Callable[[Request], Awaitable[Response]]:+ handler = super().get_route_handler()++ async def private_validation(request: Request) -> Response:+ try:+ return await handler(request)+ except RequestValidationError as exc:+ reason = "invalid_station_request"+ if "/rides" in self.path:+ reason = "invalid_rover_request"+ if "/moves" in self.path or "/navigation/" in self.path:+ reason = "invalid_navigation_request"+ if any(+ error.get("loc") == ("body", "mode")+ and error.get("type") == "literal_error"+ for error in exc.errors()+ ):+ reason = "unsupported_navigation_mode"+ return JSONResponse(+ status_code=422,+ content={"detail": {"reason": reason}},+ headers={"Cache-Control": "no-store"},+ )++ return private_validation+++router = APIRouter(prefix="/api/society/mars", tags=["mars"], route_class=_PrivateStationRoute)+++async def _reconcile_loop(service: Any) -> None:+ """The process owns progress even with zero renderers and zero HTTP clients."""+ while True:+ try:+ await service.reconcile()+ except asyncio.CancelledError:+ raise+ except Exception as exc:+ log.warning("Mars station reconciliation unavailable (%s)", type(exc).__name__)+ await asyncio.sleep(1.0)+++async def _navigation_loop(service: Any) -> None:+ """Travel has its own owner; slow task inspection cannot stall movement."""+ while True:+ try:+ await service.advance()+ except asyncio.CancelledError:+ raise+ except Exception as exc:+ log.warning("Mars navigation advance unavailable (%s)", type(exc).__name__)+ await asyncio.sleep(_NAVIGATION_TICK_S)+++def _station_lock(state: Any) -> asyncio.Lock:+ if getattr(state, "mars_station_lock", None) is None:+ state.mars_station_lock = asyncio.Lock()+ return state.mars_station_lock+++async def _initialize_mars_station(state: Any) -> Any:+ """The application owns initialization even when every HTTP waiter leaves."""+ from jarvis.society.mars.navigation_ordinary import OrdinaryNavigationAuthority+ from jarvis.society.mars.navigation_service import MarsNavigationService+ from jarvis.society.mars.navigation_store import MarsNavigationStore+ from jarvis.society.mars.ordinary import OrdinaryStationExecutor+ from jarvis.society.mars.service import MarsStationService+ from jarvis.society.mars.store import MarsStore++ service = None+ navigation = None+ published = False+ try:+ async with asyncio.timeout(_INITIALIZATION_TIMEOUT_S):+ runtime = getattr(state, "society", None)+ if runtime is None:+ factory = getattr(state, "society_factory", None)+ if factory is None:+ raise HTTPException(503, "mars_station_unavailable")+ runtime = factory()+ state.society = runtime+ await runtime.ensure_started()+ if getattr(state, "mars_station_stopping", False):+ raise HTTPException(503, "mars_station_stopped")+ service = MarsStationService(+ MarsStore(runtime.store.path.parent / "mars" / "ordinary.db"),+ OrdinaryStationExecutor(runtime),+ # Existing chat cancellation waits up to fifteen seconds before forcing stop.+ operation_timeout_s=20.0,+ )+ await service.start()+ navigation_authority = OrdinaryNavigationAuthority(runtime)+ navigation = MarsNavigationService(+ MarsNavigationStore(runtime.store.path.parent / "mars" / "navigation.db"),+ load_definition(),+ authorize=navigation_authority,+ authorize_rover=navigation_authority.rover,+ )+ await navigation.start()+ if getattr(state, "mars_station_stopping", False):+ raise HTTPException(503, "mars_station_stopped")+ # No await separates the stop check and publication. The state lock+ # only protects task creation; it is never held across initialization.+ state.mars_station = service+ state.mars_navigation = navigation+ state.mars_station_task = asyncio.create_task(+ _reconcile_loop(service), name="mars-station-owner"+ )+ state.mars_navigation_task = asyncio.create_task(+ _navigation_loop(navigation), name="mars-navigation-owner"+ )+ published = True+ return service+ except Exception as exc:+ # Exception text may contain private drafts or provider error bodies.+ log.warning("Mars station startup unavailable (%s)", type(exc).__name__)+ raise HTTPException(503, "mars_station_unavailable") from exc+ finally:+ if not published:+ try:+ if navigation is not None:+ await navigation.close()+ finally:+ if service is not None:+ await service.close()+++def _observe_initialization(task: asyncio.Task[Any]) -> None:+ # All waiters may have disconnected. Startup logs a sanitized failure itself;+ # retrieving the exception avoids asyncio logging its private exception chain.+ if not task.cancelled():+ task.exception()+++async def ensure_mars_station(state: Any) -> Any:+ """Share one bounded initialization task between HTTP and deferred recovery."""+ async with _station_lock(state):+ if getattr(state, "mars_station_stopping", False):+ raise HTTPException(503, "mars_station_stopped")+ existing = getattr(state, "mars_station", None)+ if existing is not None:+ return existing+ initialization = getattr(state, "mars_station_initialization_task", None)+ if initialization is None or initialization.done():+ initialization = asyncio.create_task(+ _initialize_mars_station(state), name="mars-station-initialize"+ )+ initialization.add_done_callback(_observe_initialization)+ state.mars_station_initialization_task = initialization+ # A canceled HTTP request must not cancel initialization needed by other+ # callers or the process-owned recovery task. Explicit stop cancels the owner.+ return await asyncio.shield(initialization)+++def schedule_mars_resume(state: Any, data_dir: Path) -> None:+ """Resume an existing journal after boot, without requiring any client.++ Merely scheduling this task does no I/O and calls no runtime factory. A+ normal install that has never used Mars retains its lazy boot behavior.+ """+ if getattr(state, "mars_station_stopping", False):+ return+ previous = getattr(state, "mars_station_startup_task", None)+ if previous is not None and not previous.done():+ return++ async def resume() -> None:+ # Even an eager task factory must not run recovery on the boot chain.+ await asyncio.sleep(0)+ try:+ directory = Path(data_dir) / "mars"++ def has_journal() -> bool:+ return any(+ (directory / name).is_file() for name in ("ordinary.db", "navigation.db")+ )++ if await asyncio.to_thread(has_journal):+ await ensure_mars_station(state)+ except asyncio.CancelledError:+ raise+ except Exception as exc:+ log.warning("Mars station deferred resume unavailable (%s)", type(exc).__name__)++ state.mars_station_startup_task = asyncio.create_task(resume(), name="mars-station-resume")+++async def stop_mars_station(state: Any) -> None:+ """Fence late initialization and join both owners before releasing the store."""+ state.mars_station_stopping = True+ tasks = tuple(+ task+ for name in (+ "mars_station_startup_task",+ "mars_station_initialization_task",+ "mars_station_task",+ "mars_navigation_task",+ )+ if (task := getattr(state, name, None)) is not None+ )+ for task in tasks:+ task.cancel()+ if tasks:+ _done, pending = await asyncio.wait(tasks, timeout=_INITIALIZATION_STOP_TIMEOUT_S)+ if pending:+ # Retain ownership references and the stop latch if a collaborator+ # ignores cancellation. It still cannot publish a station when it+ # eventually returns; its finally block closes any partial service.+ log.warning("Mars station shutdown deadline expired (TimeoutError)")+ raise TimeoutError("mars_station_shutdown_timeout")+ async with _station_lock(state):+ navigation = getattr(state, "mars_navigation", None)+ service = getattr(state, "mars_station", None)+ try:+ if navigation is not None:+ await navigation.close()+ state.mars_navigation = None+ finally:+ # Each service owns an independent journal. A navigation cleanup+ # failure must not leave the task journal open as a side effect.+ if service is not None:+ await service.close()+ state.mars_station = None+ state.mars_station_startup_task = None+ state.mars_station_initialization_task = None+ state.mars_station_task = None+ state.mars_navigation_task = None+++async def _service(request: Request) -> Any:+ return await ensure_mars_station(request.app.state)+++async def ensure_mars_navigation(state: Any) -> Any:+ """Both surfaces share the same initialization task, deadline and stop fence."""+ await ensure_mars_station(state)+ navigation = getattr(state, "mars_navigation", None)+ if navigation is None:+ raise HTTPException(503, "mars_navigation_unavailable")+ return navigation+++def _error(exc: StationError) -> HTTPException:+ return HTTPException(exc.status_code, {"reason": exc.reason})++[email protected]("/definition")+async def get_mars_definition() -> dict[str, Any]:+ """Read the packaged canonical world without starting agents or a renderer."""+ return load_definition()++[email protected]("/snapshot", response_model=StationSnapshot)+async def get_mars_snapshot(request: Request) -> StationSnapshot:+ """Read current durable station state; no private draft text is returned."""+ try:+ return await (await _service(request)).snapshot()+ except StationError as exc:+ raise _error(exc) from exc++[email protected]("/events", response_model=StationEventBatch)+async def get_mars_events(+ request: Request,+ after_seq: int = Query(default=0, ge=0),+ limit: int = Query(default=100, ge=1, le=200),+) -> StationEventBatch:+ """Read a bounded delivered cursor, with an explicit snapshot-resync signal."""+ try:+ return await (await _service(request)).events(after_seq, limit=limit)+ except StationError as exc:+ raise _error(exc) from exc+++ "/agents/{agent_id}/commands",+ response_model=CommandRecord,+ openapi_extra={"x-jarvis-dangerous": True},+)+async def submit_mars_draft(agent_id: str, body: StationCommand, request: Request) -> CommandRecord:+ """Submit one idempotent communication draft through existing agent authority."""+ try:+ return await (await _service(request)).submit(agent_id, body)+ except StationError as exc:+ raise _error(exc) from exc+++ "/agents/{agent_id}/commands/{command_id}/cancel",+ response_model=CommandRecord,+ openapi_extra={"x-jarvis-dangerous": True},+)+async def cancel_mars_command(agent_id: str, command_id: str, request: Request) -> CommandRecord:+ """Request a scoped stop without canceling a newer unrelated conversation."""+ try:+ return await (await _service(request)).cancel(agent_id, command_id)+ except StationError as exc:+ raise _error(exc) from exc++[email protected]("/navigation/snapshot", response_model=NavigationSnapshot)+async def get_mars_navigation_snapshot(request: Request) -> NavigationSnapshot:+ """Read bounded durable visits and physical occupancy independently of tasks."""+ try:+ return await (await ensure_mars_navigation(request.app.state)).snapshot()+ except StationError as exc:+ raise _error(exc) from exc++[email protected]("/agents/{agent_id}/moves", response_model=NavigationRecord)+async def submit_mars_move(+ agent_id: Identity, body: PedestrianMoveCommand, request: Request+) -> NavigationRecord:+ """Visit a named destination on foot without dispatching provider work."""+ try:+ return await (await ensure_mars_navigation(request.app.state)).submit(agent_id, body)+ except StationError as exc:+ raise _error(exc) from exc+++ "/agents/{agent_id}/moves/{command_id}/cancel",+ response_model=NavigationRecord,+ openapi_extra={"x-jarvis-dangerous": True},+)+async def cancel_mars_move(+ agent_id: Identity, command_id: Identity, request: Request+) -> NavigationRecord:+ """Stop only the named visit in place; ordinary tasks remain unchanged."""+ try:+ return await (await ensure_mars_navigation(request.app.state)).cancel(agent_id, command_id)+ except StationError as exc:+ raise _error(exc) from exc++[email protected]("/agents/{agent_id}/rides", response_model=RoverRideRecord)+async def reserve_mars_rover(+ agent_id: Identity, body: RoverReserveCommand, request: Request+) -> RoverRideRecord:+ """Reserve one rover seat and approach it through real agent navigation."""+ try:+ return await (await ensure_mars_navigation(request.app.state)).reserve_ride(agent_id, body)+ except StationError as exc:+ raise _error(exc) from exc++[email protected]("/agents/{agent_id}/rides/{ride_id}/board", response_model=RoverRideRecord)+async def board_mars_rover(+ agent_id: Identity, ride_id: Identity, body: RoverActionCommand, request: Request+) -> RoverRideRecord:+ """Board only after the server confirms arrival at the reserved rover."""+ try:+ return await (await ensure_mars_navigation(request.app.state)).board_ride(+ agent_id, ride_id, body+ )+ except StationError as exc:+ raise _error(exc) from exc++[email protected]("/agents/{agent_id}/rides/{ride_id}/travel", response_model=RoverRideRecord)+async def travel_mars_rover(+ agent_id: Identity, ride_id: Identity, body: RoverTravelCommand, request: Request+) -> RoverRideRecord:+ """Travel to a named supported dock with the existing reserved rider."""+ try:+ return await (await ensure_mars_navigation(request.app.state)).travel_ride(+ agent_id, ride_id, body+ )+ except StationError as exc:+ raise _error(exc) from exc+++ "/agents/{agent_id}/rides/{ride_id}/cancel",+ response_model=RoverRideRecord,+ openapi_extra={"x-jarvis-dangerous": True},+)+async def cancel_mars_rover(+ agent_id: Identity, ride_id: Identity, body: RoverActionCommand, request: Request+) -> RoverRideRecord:+ """Stop the named ride in place while retaining any attached rider safely."""+ try:+ return await (await ensure_mars_navigation(request.app.state)).cancel_ride(+ agent_id, ride_id, body+ )+ except StationError as exc:+ raise _error(exc) from exc++[email protected]("/agents/{agent_id}/rides/{ride_id}/exit", response_model=RoverRideRecord)+async def exit_mars_rover(+ agent_id: Identity, ride_id: Identity, body: RoverActionCommand, request: Request+) -> RoverRideRecord:+ """Exit only onto a supported, unoccupied dock anchor confirmed by the server."""+ try:+ return await (await ensure_mars_navigation(request.app.state)).exit_ride(+ agent_id, ride_id, body+ )+ except StationError as exc:+ raise _error(exc) from excdiff --git a/jarvis/ui/web/provider_routes.py b/jarvis/ui/web/provider_routes.pyindex e90d4ccd46..18a0c83272 100644--- a/jarvis/ui/web/provider_routes.py+++ b/jarvis/ui/web/provider_routes.py@@ -674,6 +674,7 @@ def _spec_to_payload(# Unstable provider protocol: the card explains the fallback before a# user activates it. Presentation only, never a runtime provider gate."experimental": spec.experimental,+ "configuration_surface": spec.configuration_surface,# Dictation-polish cards only: the value ``[dictation].polish_provider``# actually stores. The card id and the polish FAMILY id differ ("groq"# is already the brain card), so a client pinning this tier must senddiff --git a/jarvis/ui/web/provider_spec.py b/jarvis/ui/web/provider_spec.pyindex 230a2be322..1051f0669d 100644--- a/jarvis/ui/web/provider_spec.py+++ b/jarvis/ui/web/provider_spec.py@@ -105,6 +105,8 @@ class ProviderSpec:# shows a clear badge and fallback note, while runtime selection remains# capability-driven. This is presentation only and never gates behavior.experimental: bool = False+ # Settings presentation: continuous voice has one coherent profile form.+ configuration_surface: Literal["provider", "live"] = "provider"# Withdrawn from the public catalog: ``/api/providers`` does not serve the# card, so the settings UI offers no way to select the provider. This is# presentation-gating only (AP-21): all runtime plumbing — config@@ -901,6 +903,7 @@ PROVIDERS: tuple[ProviderSpec, ...] = (id="openai-live",label="OpenAI GPT-Live",tier="realtime",+ configuration_surface="live",auth_mode="api_key",secret_keys=("openai_api_key",),dashboard_url="https://platform.openai.com/api-keys",diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.pyindex 90f3f683af..28cd01bd7a 100644--- a/jarvis/ui/web/server.py+++ b/jarvis/ui/web/server.py@@ -592,6 +592,9 @@ class WebServer:set_society_factory(self._build_society_runtime)app.include_router(society_router)+ from .mars_routes import router as mars_router++ app.include_router(mars_router)app.include_router(society_browser_router)app.include_router(society_figure_router)app.include_router(drop_router)@@ -2839,6 +2842,12 @@ class WebServer:except Exception:logger.debug("Browser preparation deferred after failure", exc_info=True)self._browser_prepare_task = asyncio.create_task(prepare_browser(), name="browser-prepare")+ # Existing Mars work recovers with zero clients. The deferred helper+ # performs its existence probe and runtime composition after boot yields.+ from .mars_routes import schedule_mars_resume++ data_dir = Path(getattr(getattr(self.cfg, "memory", None), "data_dir", None) or "data")+ schedule_mars_resume(self.app.state, data_dir)async def _init_screenshot_retention(self) -> None:"""Auto-delete captured screenshot blobs older than the configured@@ -3670,10 +3679,12 @@ class WebServer:follows the live mission manager, budget tracker, brain tool surfaceand skill registry — whichever of them exists at call time."""- from jarvis.society.runtime import SocietyRuntime+ from jarvis.society.runtime import SocietyRuntime, SocietyRuntimeClosed- data_dir = Path(getattr(getattr(self.cfg, "memory", None), "data_dir", None) or "data")state = self.app.state+ if getattr(state, "society_stopping", False):+ raise SocietyRuntimeClosed("society runtime stopped")+ data_dir = Path(getattr(getattr(self.cfg, "memory", None), "data_dir", None) or "data")if getattr(state, "society", None) is not None:return state.society@@ -3760,13 +3771,35 @@ class WebServer:return AgentChatService(store, assistant_name=_name, bus=lambda: self.bus)async def stop(self) -> None:+ # Fence lazy creation even when no Society owner exists yet. The shared+ # brain factory and HTTP surface can still be called while shutdown awaits.+ self.app.state.society_stopping = True+ from .mars_routes import stop_mars_station++ # Fence station creation before any other shutdown await can interleave+ # with a pending boot recovery or first HTTP request.+ mars_shutdown_failure: str | None = None+ try:+ await stop_mars_station(self.app.state)+ except Exception as exc: # noqa: BLE001 -- independent resources must still shut down+ # The helper retains its stop latch and pending owner references.+ # Keep only the type: cleanup failures can contain private payloads.+ mars_shutdown_failure = type(exc).__name__+ logger.warning("Mars station cleanup incomplete ({})", mars_shutdown_failure)if self._browser_prepare_task is not None:self._browser_prepare_task.cancel()await asyncio.gather(self._browser_prepare_task, return_exceptions=True)self._browser_prepare_task = Nonesociety = getattr(self.app.state, "society", None)+ society_shutdown_failure: str | None = Noneif society is not None:- await society.browser.close()+ try:+ # The runtime owns delivery tasks, subscriptions and SQLite as+ # well as the browser. Leaving its store open prevents exit.+ await asyncio.wait_for(society.close(), timeout=5.0)+ except Exception as exc: # noqa: BLE001 -- finish independent cleanup below+ society_shutdown_failure = type(exc).__name__+ logger.warning("Society runtime cleanup incomplete ({})", society_shutdown_failure)self._mic_level_sessions.clear()self._stop_mic_level_bridge()@@ -4075,6 +4108,13 @@ class WebServer:except Exception as exc: # noqa: BLE001 - shutdown continues best-effortlogger.opt(exception=exc).warning("Codex subscription app-server cleanup failed")+ if mars_shutdown_failure is not None:+ # Report incomplete Mars cleanup only after unrelated browser, chat,+ # plugin, watcher, terminal and server resources have been released.+ raise RuntimeError(f"mars_station_shutdown_incomplete ({mars_shutdown_failure})")+ if society_shutdown_failure is not None:+ raise RuntimeError(f"society_runtime_shutdown_incomplete ({society_shutdown_failure})")+@propertydef running(self) -> bool:return self._server is not None and self._server.starteddiff --git a/jarvis/ui/web/settings_routes.py b/jarvis/ui/web/settings_routes.pyindex 21d1890972..30268b192e 100644--- a/jarvis/ui/web/settings_routes.py+++ b/jarvis/ui/web/settings_routes.py@@ -311,11 +311,12 @@ async def get_voice_mode(request: Request) -> dict[str, object]:# Capability, not a provider id (AP-21): the surface must not call a start# attempt dead while the backend is still inside a budget it declared.handshake_budget_s = await asyncio.to_thread(_realtime_handshake_budget_s, cfg)- transport_offer_ready = await _realtime_transport_offer_ready(- requires_webrtc_offer+ browser_audio = realtime_browser_audio(cfg)+ transport_offer_ready = (+ None if browser_audio else await _realtime_transport_offer_ready(requires_webrtc_offer))transport_offer_detail: str | None = None- if requires_webrtc_offer:+ if requires_webrtc_offer and not browser_audio:transport_offer_detail = str(getattr(request.app.state, "realtime_transport_broker_error", "")or (@@ -356,7 +357,7 @@ async def get_voice_mode(request: Request) -> dict[str, object]:"realtime_available": realtime_available,"realtime_availability_pending": realtime_availability_pending,"requires_webrtc_offer": requires_webrtc_offer,- "browser_audio": realtime_browser_audio(cfg),+ "browser_audio": browser_audio,"handshake_budget_s": handshake_budget_s,"transport_offer_ready": transport_offer_ready,"transport_offer_detail": transport_offer_detail,diff --git a/jarvis/ui/web/society_routes.py b/jarvis/ui/web/society_routes.pyindex de4532a258..6335862315 100644--- a/jarvis/ui/web/society_routes.py+++ b/jarvis/ui/web/society_routes.py@@ -24,7 +24,7 @@ from jarvis.society.failure_reasons import FailureReason, retry_actionfrom jarvis.society.memory import MEMORY_SHARE_CAPABILITY, MemoryRefusedfrom jarvis.society.rooms import RoomErrorfrom jarvis.society.roster import AgentRecord, RosterError-from jarvis.society.runtime import SocietyRuntime+from jarvis.society.runtime import SocietyRuntime, SocietyRuntimeClosedlog = logging.getLogger(__name__)@@ -36,6 +36,8 @@ router = APIRouter(prefix="/api/society", tags=["society"])async def _runtime(request: HTTPConnection) -> SocietyRuntime:state = request.app.state+ if getattr(state, "society_stopping", False):+ raise HTTPException(503, "society runtime stopped")runtime = getattr(state, "society", None)if runtime is None:factory = getattr(state, "society_factory", None)@@ -43,11 +45,16 @@ async def _runtime(request: HTTPConnection) -> SocietyRuntime:raise HTTPException(503, "society runtime not configured")try:runtime = factory()+ except SocietyRuntimeClosed as exc:+ raise HTTPException(503, "society runtime stopped") from excexcept Exception as exc: # noqa: BLE001 — surfaces as 503 with the reason in the loglog.warning("society: runtime could not be built: %s", exc)raise HTTPException(503, "society runtime unavailable") from excstate.society = runtime- await runtime.ensure_started()+ try:+ await runtime.ensure_started()+ except SocietyRuntimeClosed as exc:+ raise HTTPException(503, "society runtime stopped") from excreturn runtimediff --git a/jarvis/ui/window_command.py b/jarvis/ui/window_command.pynew file mode 100644index 0000000000..f5ec44f05b--- /dev/null+++ b/jarvis/ui/window_command.py@@ -0,0 +1,71 @@+"""Minimize, maximize and close for the desktop window, from the page.++The page draws those buttons itself once the native title bar is gone+(``frameless``). The methods are the same ones the operating system would+call, so closing still runs the window's normal close path.++Headless hosts have no window. Callers get ``ok: false`` and do not pretend+a button was pressed.+"""++from __future__ import annotations++import sys+from typing import Any++_ACTIONS = frozenset({"minimize", "maximize", "close"})+++def window_chrome(platform: str | None = None) -> dict[str, Any]:+ """Where the page should put the window buttons.++ macOS keeps them on the left, like the traffic lights they replace.+ Windows and Linux keep them on the right. ``frameless`` is filled in by+ the desktop shell from the live window — this helper only names the side.+ """+ plat = platform if platform is not None else sys.platform+ if plat == "darwin":+ name, controls = "darwin", "leading"+ elif plat == "win32":+ name, controls = "windows", "trailing"+ else:+ name, controls = "linux", "trailing"+ return {"ok": True, "frameless": False, "platform": name, "controls": controls}+++def run_window_command(+ window: Any,+ action: str,+ *,+ maximized: bool | None = None,+) -> dict[str, Any]:+ """Run one caption action on ``window``.++ ``maximized`` is the operating system's answer when the caller has one+ (Windows ``IsZoomed``). Without it, the last action this process took is+ the answer — enough for macOS and Linux, where only these buttons change+ that state.+ """+ if window is None:+ return {"ok": False, "reason": "no_window"}+ if action not in _ACTIONS:+ return {"ok": False, "reason": "unknown_action"}+ if action == "minimize":+ window.minimize()+ window._jarvis_maximized = False+ return {"ok": True, "maximized": False}+ if action == "close":+ window.destroy()+ return {"ok": True, "maximized": False}+ is_max = (+ maximized+ if maximized is not None+ else bool(getattr(window, "_jarvis_maximized", False))+ )+ if is_max:+ window.restore()+ window._jarvis_maximized = False+ return {"ok": True, "maximized": False}+ window.maximize()+ window._jarvis_maximized = True+ return {"ok": True, "maximized": True}diff --git a/jarvis/workspace/launch_picks.py b/jarvis/workspace/launch_picks.pyindex 789670f2b6..e48ee11c73 100644--- a/jarvis/workspace/launch_picks.py+++ b/jarvis/workspace/launch_picks.py@@ -257,8 +257,7 @@ async def live_models() -> dict[str, list[dict[str, Any]]]:except Exception as exc: # noqa: BLE001 — the fallback list stands in_log.debug("launch picks: codex model list unavailable: %s", exc)rows = None- if rows:- out["codex-cli"] = rows+ out["codex-cli"] = rows or []if _installed("grok-cli"):try:rows = await asyncio.to_thread(read_grok_models)@@ -274,8 +273,7 @@ async def live_models() -> dict[str, list[dict[str, Any]]]:except Exception as exc: # noqa: BLE001 — no list is an empty picker, not an error_log.debug("launch picks: opencode model list unavailable: %s", exc)rows = []- if rows:- out["opencode-cli"] = rows+ out["opencode-cli"] = rowsreturn out@@ -316,8 +314,8 @@ def offered_models(if row is None:return []# What THIS account can actually pick, when the CLI was asked and answered.- if live and (published := live.get(row.runner)):- return list(published)+ if live is not None and row.runner in live:+ return list(live[row.runner])# Claude Code takes its own ids and aliases rather than the Anthropic# API's catalog — the same exception the chat catalog route makes.if picks.provider == "claude-api":diff --git a/pyproject.toml b/pyproject.tomlindex e15983c2db..f55dfe7a40 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -816,6 +816,11 @@ call-contact = "jarvis.plugins.tool.call_contact:CallContactTool"[tool.setuptools.packages.find]where = ["."]include = ["jarvis*"]+exclude = ["*.__pycache__", "*.__pycache__.*"]++[tool.setuptools.exclude-package-data]+# Resource globs must never distribute interpreter caches or their build paths.+"*" = ["*.pyc", "*.pyo", "**/__pycache__/*"][tool.setuptools.package-data]jarvis = [@@ -844,6 +849,7 @@ jarvis = ["brain/JARVIS_PERSONA.md","skills/safe_imports.txt","core/review/verdict_schema.json",+ "society/mars/definition.json",# Seed catalogs (CLI tools / skills / marketplace plugins) — named# explicitly rather than a repo-wide "**/*.json" glob, which would also# sweep in jarvis/ui/web/frontend's SOURCE config (package.json,diff --git a/scripts/art/build_agent_companions.py b/scripts/art/build_agent_companions.pynew file mode 100644index 0000000000..0bd90f5b75--- /dev/null+++ b/scripts/art/build_agent_companions.py@@ -0,0 +1,100 @@+"""Author the approved flat bot silhouettes as small bevelled Blender figures.++Input: source/outlines.json sampled from the actual AgentSymbol SVG geometry.+Run inside Blender with --background --factory-startup --python this_file.+The .blend remains editable; GLB uses ordinary meshes and PBR materials only.+"""++import json+from pathlib import Path++import bmesh+import bpy++ROOT = Path(__file__).resolve().parents[2]+STUDY = ROOT / "art/studies/agent-symbol-companions"+++def material(name, color):+ mat = bpy.data.materials.new(name)+ mat.diffuse_color = (*color, 1)+ mat.use_nodes = True+ bsdf = mat.node_tree.nodes.get("Principled BSDF")+ bsdf.inputs["Base Color"].default_value = (*color, 1)+ bsdf.inputs["Roughness"].default_value = 0.78+ return mat+++def main():+ bpy.ops.object.select_all(action="SELECT")+ bpy.ops.object.delete(use_global=False)+ outlines = json.loads((STUDY / "source/outlines.json").read_text(encoding="utf-8"))+ body_mat = material("Companion.Body", (0.62, 0.40, 0.93))+ eye_mat = material("Companion.Eyes", (0.01, 0.009, 0.015))+ shine_mat = material("Companion.Highlight", (1, 1, 1))+ for name, points in outlines.items():+ parent = bpy.data.objects.new(name, None)+ bpy.context.collection.objects.link(parent)+ low = min(y for _, y in points)+ high = max(y for _, y in points)+ scale = 1 / (high - low)+ contour = [((x - 20) * scale, (high - y) * scale) for x, y in points]+ count = len(contour)+ vertices = [(x, depth, z) for depth in (-0.25, 0.25) for x, z in contour]+ faces = [tuple(range(count)), tuple(range(count, count * 2))]+ faces += [(i, (i + 1) % count, (i + 1) % count + count, i + count) for i in range(count)]+ mesh = bpy.data.meshes.new(f"{name}.Body")+ mesh.from_pydata(vertices, [], faces)+ bm = bmesh.new()+ bm.from_mesh(mesh)+ bmesh.ops.recalc_face_normals(bm, faces=bm.faces)+ bm.to_mesh(mesh)+ bm.free()+ obj = bpy.data.objects.new(f"{name}.Body", mesh)+ bpy.context.collection.objects.link(obj)+ obj.parent = parent+ obj.data.materials.append(body_mat)+ bevel = obj.modifiers.new("Soft edge", "BEVEL")+ bevel.width = 0.065+ bevel.segments = 4+ obj.modifiers.new("Surface normals", "WEIGHTED_NORMAL")+ eye_y = 23 if name in ("cloud", "triangle") else 25 if name == "drop" else 17.2+ for style in ("Dots", "Lines"):+ for side, x in enumerate((15.4, 24.6)):+ bpy.ops.mesh.primitive_uv_sphere_add(+ segments=16,+ ring_count=8,+ location=((x - 20) * scale, -0.259, (high - eye_y) * scale),+ )+ eye = bpy.context.object+ eye.name = f"{name}.{style}.{side}"+ eye.parent = parent+ eye.scale = (+ (2.2 if style == "Dots" else 1.3) * scale,+ 0.023,+ (2.3 if style == "Dots" else 3.2) * scale,+ )+ eye.data.materials.append(eye_mat)+ if style == "Dots":+ bpy.ops.mesh.primitive_uv_sphere_add(+ segments=12,+ ring_count=6,+ radius=0.65 * scale,+ location=((x - 20 - 0.6) * scale, -0.283, (high - eye_y + 0.7) * scale),+ )+ shine = bpy.context.object+ shine.name = f"{name}.Highlight.{side}"+ shine.parent = parent+ shine.data.materials.append(shine_mat)+ bpy.context.preferences.filepaths.save_version = 0+ bpy.ops.wm.save_as_mainfile(+ filepath=str(STUDY / "source/companions.blend"), check_existing=False+ )+ bpy.ops.export_scene.gltf(+ filepath=str(STUDY / "exports/companions.glb"), export_format="GLB", export_animations=False+ )+ print("COMPANION_GEOMETRY_EXPORTED", (STUDY / "exports/companions.glb").stat().st_size)+++if __name__ == "__main__":+ main()diff --git a/scripts/art/build_gigi_companion.py b/scripts/art/build_gigi_companion.pynew file mode 100644index 0000000000..34e3585b66--- /dev/null+++ b/scripts/art/build_gigi_companion.py@@ -0,0 +1,353 @@+"""Author the editable Gigi reference; exports remain inside the isolated study.++Run in Blender with --background --factory-startup --disable-autoexec --python.+The companion uses metres, Blender Z-up and -Y forward (glTF +Z forward).+No body emblem is authored, including the inconsistent emblems in the concept.+"""++from __future__ import annotations++import json+import math+import sys+from pathlib import Path++import bpy+from mathutils import Vector++sys.path.insert(0, str(Path(__file__).resolve().parent))+from gigi_source_metadata import ( # noqa: E402+ sanitize_source_metadata,+ source_path_records,+ validate_saved_source,+ validate_source_path_records,+)++ROOT = Path(__file__).resolve().parents[2]+STUDY = ROOT / "art/studies/gigi-hover-companion"+TAU = 2 * math.pi+++def material(name, color, metallic=0.0, roughness=0.4, emission=0.0):+ mat = bpy.data.materials.new(name)+ mat.diffuse_color = (*color, 1)+ mat.use_nodes = True+ shader = mat.node_tree.nodes.get("Principled BSDF")+ shader.inputs["Base Color"].default_value = (*color, 1)+ shader.inputs["Metallic"].default_value = metallic+ shader.inputs["Roughness"].default_value = roughness+ shader.inputs["Emission Color"].default_value = (*color, 1)+ shader.inputs["Emission Strength"].default_value = emission+ return mat+++def attach(obj, name, mat, parent):+ obj.name = name+ if mat:+ obj.data.materials.append(mat)+ obj.parent = parent+ for face in getattr(obj.data, "polygons", []):+ face.use_smooth = True+ return obj+++def ellipsoid(name, position, size, mat, parent, segments=32):+ bpy.ops.mesh.primitive_uv_sphere_add(segments=segments, ring_count=16, location=position)+ obj = bpy.context.object+ obj.scale = size+ bpy.ops.object.transform_apply(location=False, rotation=False, scale=True)+ return attach(obj, name, mat, parent)+++def tube(name, points, radius, mat, parent, closed=False):+ curve = bpy.data.curves.new(name, "CURVE")+ curve.dimensions = "3D"+ curve.bevel_depth = radius+ curve.bevel_resolution = 3+ spline = curve.splines.new("POLY")+ spline.points.add(len(points) - 1)+ for point, position in zip(spline.points, points, strict=True):+ point.co = (*position, 1)+ spline.use_cyclic_u = closed+ obj = bpy.data.objects.new(name, curve)+ bpy.context.collection.objects.link(obj)+ attach(obj, name, mat, parent)+ bpy.context.view_layer.objects.active = obj+ obj.select_set(True)+ bpy.ops.object.convert(target="MESH")+ obj.select_set(False)+ return obj+++def rounded_box(name, position, size, radius, mat, parent):+ bpy.ops.mesh.primitive_cube_add(size=1, location=position)+ obj = bpy.context.object+ obj.dimensions = size+ bpy.ops.object.transform_apply(location=False, rotation=False, scale=True)+ bevel = obj.modifiers.new("Machined edge radius", "BEVEL")+ bevel.width = radius+ bevel.segments = 3+ bpy.ops.object.modifier_apply(modifier=bevel.name)+ return attach(obj, name, mat, parent)+++def hem_height(angle):+ # Three teeth across both face and rear, joined around the side surfaces.+ across = (math.cos(angle) + 1) * 1.5+ triangle = abs(2 * (across % 1) - 1)+ return 0.014 + 0.034 * triangle+++def make_shell(parent, mat):+ count = 96+ rings = []+ for height in (None, 0.065, 0.12, 0.20, 0.275):+ rings.append(+ [+ (+ 0.143 * math.cos(i * TAU / count),+ 0.095 * math.sin(i * TAU / count),+ hem_height(i * TAU / count) if height is None else height,+ )+ for i in range(count)+ ]+ )+ for step in range(1, 13):+ angle = step * math.pi / 26+ rings.append(+ [+ (+ 0.143 * math.cos(angle) * math.cos(i * TAU / count),+ 0.095 * math.cos(angle) * math.sin(i * TAU / count),+ 0.275 + 0.125 * math.sin(angle),+ )+ for i in range(count)+ ]+ )+ vertices = [point for ring in rings for point in ring]+ faces = []+ for ring in range(len(rings) - 1):+ for index in range(count):+ a = ring * count + index+ b = ring * count + (index + 1) % count+ faces.append((a, b, b + count, a + count))+ vertices.extend([(0, 0, 0.02), (0, 0, 0.4)])+ for index in range(count):+ nxt = (index + 1) % count+ faces.append((len(vertices) - 2, nxt, index))+ offset = (len(rings) - 1) * count+ faces.append((len(vertices) - 1, offset + index, offset + nxt))+ mesh = bpy.data.meshes.new("Gigi continuous closed shell")+ mesh.from_pydata(vertices, [], faces)+ mesh.update()+ obj = bpy.data.objects.new("Gigi.Housing", mesh)+ bpy.context.collection.objects.link(obj)+ return attach(obj, obj.name, mat, parent)+++def empty(name, parent=None):+ obj = bpy.data.objects.new(name, None)+ bpy.context.collection.objects.link(obj)+ obj.parent = parent+ return obj+++def main():+ bpy.ops.object.select_all(action="SELECT")+ bpy.ops.object.delete(use_global=False)+ scene = bpy.context.scene+ scene.unit_settings.system = "METRIC"+ scene.unit_settings.scale_length = 1+ collection = bpy.data.collections.new("GigiExport")+ scene.collection.children.link(collection)+ layer = bpy.context.view_layer.layer_collection.children[collection.name]+ bpy.context.view_layer.active_layer_collection = layer+ root = empty("Gigi.Root")+ root["body_height_m"] = 0.4+ root["role"] = "optional assistant companion, never worker identity"+ root["forward"] = "Blender -Y; glTF +Z"+ root["body_emblem"] = "none"+ shell = material("Gigi.Graphite", (0.045, 0.050, 0.057), 0.3, 0.46)+ face = material("Gigi.FaceGlass", (0.004, 0.006, 0.009), 0.15, 0.23)+ metal = material("Gigi.AnodizedRim", (0.11, 0.10, 0.075), 0.85, 0.29)+ yellow = material("Gigi.SignalYellow", (1.0, 0.59, 0.025), 0.25, 0.26, 1.2)+ pupil = material("Gigi.Pupil", (0.001, 0.002, 0.003), 0.0, 0.23)+ highlight = material("Gigi.EyeHighlight", (0.95, 0.95, 0.88), 0.0, 0.2, 0.35)+ make_shell(root, shell)+ # The face is a fitted curved lens rather than a flat billboard.+ ellipsoid("Gigi.Face", (0, -0.037, 0.275), (0.137, 0.064, 0.116), face, root)+ ring = [+ (0.144 * math.cos(i * TAU / 144), 0.096 * math.sin(i * TAU / 144), 0.207)+ for i in range(144)+ ]+ tube("Gigi.EquatorSeam", ring, 0.0015, metal, root, True)+ tube(+ "Gigi.EquatorLight",+ [(x, y - 0.0008, z + 0.002) for x, y, z in ring[72:]],+ 0.0008,+ yellow,+ root,+ )+ hem = [+ (+ 0.144 * math.cos(i * TAU / 192),+ 0.096 * math.sin(i * TAU / 192),+ hem_height(i * TAU / 192) + 0.004,+ )+ for i in range(192)+ ]+ tube("Gigi.HemLight", hem, 0.0025, yellow, root, True)+ arch = [+ (0.137 * math.cos(i * math.pi / 64), -0.035, 0.275 + 0.121 * math.sin(i * math.pi / 64))+ for i in range(65)+ ]+ tube("Gigi.CrownLight", arch, 0.0022, yellow, root)+ for side, x in (("L", -0.055), ("R", 0.055)):+ eye = empty(f"Gigi.Eye.{side}", root)+ eye.location = (x, -0.100, 0.268)+ ellipsoid(f"Gigi.Iris.{side}", (0, 0, 0), (0.027, 0.007, 0.037), yellow, eye)+ ellipsoid(f"Gigi.Pupil.{side}", (0.002, -0.006, -0.004), (0.0115, 0.003, 0.023), pupil, eye)+ ellipsoid(+ f"Gigi.Glint.{side}", (0.008, -0.009, 0.016), (0.004, 0.002, 0.005), highlight, eye, 16+ )+ eye.scale = (1, 1, 1)+ eye.keyframe_insert(data_path="scale", frame=1)+ eye.keyframe_insert(data_path="scale", frame=90)+ eye.scale.z = 0.12+ eye.keyframe_insert(data_path="scale", frame=94)+ eye.scale.z = 1+ eye.keyframe_insert(data_path="scale", frame=98)+ eye.keyframe_insert(data_path="scale", frame=180)+ eye.animation_data.action.name = f"Gigi.Blink.{side}"+ mouth = [+ (0.012 * math.cos(i * TAU / 48), -0.0975, 0.178 + 0.019 * math.sin(i * TAU / 48))+ for i in range(48)+ ]+ tube("Gigi.Mouth", mouth, 0.0025, yellow, root, True)+ for sign, side in ((-1, "L"), (1, "R")):+ ellipsoid(+ f"Gigi.SensorRim.{side}", (sign * 0.143, 0, 0.254), (0.023, 0.049, 0.050), metal, root+ )+ ellipsoid(+ f"Gigi.Sensor.{side}", (sign * 0.161, 0, 0.254), (0.01, 0.039, 0.040), shell, root+ )+ rounded_box(+ f"Gigi.SensorLight.{side}",+ (sign * 0.170, -0.005, 0.254),+ (0.003, 0.007, 0.045),+ 0.002,+ yellow,+ root,+ )+ arm = empty(f"Gigi.Arm.{side}", root)+ arm.location = (sign * 0.136, 0, 0.170)+ ellipsoid(+ f"Gigi.ArmShell.{side}",+ (sign * 0.020, -0.002, -0.034),+ (0.021, 0.028, 0.056),+ shell,+ arm,+ )+ ellipsoid(+ f"Gigi.ArmLight.{side}",+ (sign * 0.028, -0.026, -0.040),+ (0.014, 0.004, 0.036),+ yellow,+ arm,+ )+ arm.rotation_euler.y = sign * -0.15+ rounded_box("Gigi.RearPanel", (0, 0.094, 0.142), (0.18, 0.014, 0.14), 0.011, shell, root)+ for z in (0.165, 0.176):+ rounded_box(+ f"Gigi.RearStatus.{z}", (0, 0.104, z), (0.027, 0.003, 0.002), 0.001, yellow, root+ )+ for x in (-0.072, 0.072):+ for z in (0.092, 0.196):+ ellipsoid(+ f"Gigi.RearFastener.{x}.{z}", (x, 0.103, z), (0.002, 0.001, 0.002), metal, root, 12+ )+ ellipsoid("Gigi.HoverHousing", (0, 0, 0.026), (0.062, 0.057, 0.012), metal, root)+ tube(+ "Gigi.HoverEmitter",+ [+ (0.045 * math.cos(i * TAU / 64), 0.043 * math.sin(i * TAU / 64), 0.014)+ for i in range(64)+ ],+ 0.003,+ yellow,+ root,+ True,+ )+ scene.frame_start, scene.frame_end, scene.render.fps = 1, 180, 30+ scene.frame_set(1)+ scene["production_recipe"] = "scripts/art/build_gigi_companion.py"+ scene["reference_status"] = "pending actual-runtime visual review"+ # Review lighting/camera is outside the export collection.+ bpy.context.view_layer.active_layer_collection = bpy.context.view_layer.layer_collection+ world = bpy.data.worlds.new("Gigi neutral studio")+ world.use_nodes = True+ world.node_tree.nodes["Background"].inputs[0].default_value = (0.18, 0.18, 0.18, 1)+ world.node_tree.nodes["Background"].inputs[1].default_value = 0.5+ scene.world = world+ for name, location, energy, size in (+ ("Key", (-0.6, -0.6, 0.9), 45, 0.7),+ ("Fill", (0.7, -0.3, 0.5), 25, 0.6),+ ("Rim", (0, 0.6, 0.7), 40, 0.5),+ ):+ bpy.ops.object.light_add(type="AREA", location=location)+ light = bpy.context.object+ light.name, light.data.energy, light.data.shape, light.data.size = (+ name,+ energy,+ "DISK",+ size,+ )+ light.rotation_euler = (+ (Vector((0, 0, 0.2)) - light.location).to_track_quat("-Z", "Y").to_euler()+ )+ bpy.ops.object.camera_add(location=(0.65, -1.1, 0.58))+ camera = bpy.context.object+ camera.rotation_euler = (+ (Vector((0, 0, 0.20)) - camera.location).to_track_quat("-Z", "Y").to_euler()+ )+ camera.data.type, camera.data.ortho_scale = "ORTHO", 0.58+ scene.camera = camera+ scene.render.engine = "CYCLES"+ scene.cycles.samples = 24+ scene.render.resolution_x = scene.render.resolution_y = 768+ scene.render.resolution_percentage = 100+ scene.render.film_transparent = True+ scene.view_settings.view_transform = "AgX"+ source = STUDY / "source/gigi.blend"+ bpy.context.preferences.filepaths.save_version = 0+ metadata = sanitize_source_metadata(bpy)+ bpy.ops.wm.save_as_mainfile(+ filepath=str(source), check_existing=False, relative_remap=False, compress=False+ )+ saved_validation = validate_saved_source(source.read_bytes())+ # Reopen with UI data so file-browser path fields are checked after serialization.+ bpy.ops.wm.open_mainfile(filepath=str(source), load_ui=True, use_scripts=False)+ reopened = validate_source_path_records(source_path_records(bpy))+ report = {+ "blender": bpy.app.version_string,+ "body_height_m": 0.4,+ "forward": "glTF +Z",+ "pivot": "body bottom center",+ "objects": len(bpy.data.collections["GigiExport"].all_objects),+ "textures": "none; glTF PBR constants",+ "approval": "pending",+ "body_emblem": "none",+ "source_metadata": {+ **metadata,+ **saved_validation,+ "reopened_fields": reopened["validated_fields"],+ },+ }+ (STUDY / "source/build-report.json").write_text(+ json.dumps(report, indent=2) + "\n", encoding="utf-8"+ )+ print(json.dumps(report))+++if __name__ == "__main__":+ main()diff --git a/scripts/art/build_outpost_reference.py b/scripts/art/build_outpost_reference.pynew file mode 100644index 0000000000..95fab19243--- /dev/null+++ b/scripts/art/build_outpost_reference.py@@ -0,0 +1,2377 @@+"""Author the isolated Communications Outpost; never approve or publish it.++Run with Blender --background --factory-startup --disable-autoexec --python+scripts/art/build_outpost_reference.py. Geometry uses canonical runtime metres;+conversion to Blender Z-up occurs only at the authoring boundary.+"""++from __future__ import annotations++import argparse+import hashlib+import json+import math+import random+import re+import struct+import sys+from array import array+from collections import Counter, defaultdict+from pathlib import Path++ROOT = Path(__file__).resolve().parents[2]+STUDY = ROOT / "art/studies/mars-outpost-reference"+ASSET_ID = "communications-outpost-reference"+TRIANGLE_TARGET = 300_000+++def blender_point(point):+ """Convert runtime X-east/Y-up/Z-south coordinates into Blender axes."""+ return (point[0], -point[2], point[1])+++def add(a, b):+ return tuple(a[i] + b[i] for i in range(3))+++def scale(a, factor):+ return tuple(value * factor for value in a)+++def lerp(a, b, fraction):+ return add(scale(a, 1 - fraction), scale(b, fraction))+++def length(a):+ return math.sqrt(sum(value * value for value in a))+++def normalized(a):+ magnitude = length(a)+ if magnitude < 1e-9:+ raise ValueError("a direction must have nonzero length")+ return scale(a, 1 / magnitude)+++def cross(a, b):+ return (+ a[1] * b[2] - a[2] * b[1],+ a[2] * b[0] - a[0] * b[2],+ a[0] * b[1] - a[1] * b[0],+ )+++def canonical_layout(path: Path):+ """Read shared placements; fail rather than exporting a competing layout."""+ definition = json.loads(path.read_text(encoding="utf-8"))+ if definition["units"] != "metres" or definition["axes"] != {+ "up": "+Y",+ "east": "+X",+ "north": "-Z",+ }:+ raise ValueError("the Outpost recipe requires the declared metre/Y-up axes")+ district = next(+ item for item in definition["districts"] if item["id"] == "communications-outpost"+ )+ origin = district["center"]+ buildings = {}+ for building in definition["buildings"]:+ if building["district_id"] == district["id"]:+ buildings[building["id"]] = {+ **building,+ "local": tuple(building["position"][i] - origin[i] for i in range(3)),+ }+ nodes = {+ node["id"]: tuple(node["position"][i] - origin[i] for i in range(3))+ for node in definition["navigation"]["nodes"]+ }+ return {+ "origin": origin,+ "size": district["size"],+ "seed": definition["seed"],+ "layout_version": definition["layout_version"],+ "definition_sha256": hashlib.sha256(path.read_bytes()).hexdigest(),+ "buildings": buildings,+ "nodes": nodes,+ }+++def plateau_mesh(seed=6901, segments=128):+ """A closed, layered rock volume; no open rear, bottom or edge seams."""+ rng = random.Random(seed) # noqa: S311 - reproducible terrain, not security.+ heights = [-0.12, -1.7, -5.5, -11, -18, -27, -37, -46, -55, -62]+ factors = [1.0, 1.015, 0.97, 1.02, 0.96, 1.015, 0.95, 0.90, 0.79, 0.63]+ wobble = [rng.uniform(-0.024, 0.024) for _ in range(segments)]+ vertices = []+ for level, (height, factor) in enumerate(zip(heights, factors, strict=True)):+ for index in range(segments):+ angle = math.tau * index / segments+ cosine, sine = math.cos(angle), math.sin(angle)+ x = math.copysign(abs(cosine) ** 0.58, cosine) * 60+ z = math.copysign(abs(sine) ** 0.58, sine) * 47.5+ fold = 1 + wobble[index] + 0.02 * math.sin(angle * 11 + level * 0.55)+ y = height if level == 0 else height + rng.uniform(-1.2, 1.2)+ vertices.append((x * factor * fold, y, z * factor * fold))+ faces = []+ for level in range(len(heights) - 1):+ for index in range(segments):+ following = (index + 1) % segments+ a, b = level * segments + index, level * segments + following+ faces.append((a, b, b + segments, a + segments))+ # Runtime coordinates form a right-handed basis; reverse top ring for +Y.+ faces.append(tuple(reversed(range(segments))))+ start = (len(heights) - 1) * segments+ faces.append(tuple(start + index for index in range(segments)))+ return vertices, faces+++def deck_mesh(start, end, width=10, thickness=0.65):+ """Deck top endpoints match the navigation graph, including bridge grade."""+ tangent = normalized((end[0] - start[0], 0, end[2] - start[2]))+ side = (-tangent[2] * width / 2, 0, tangent[0] * width / 2)+ top = [add(start, side), add(end, side), add(end, scale(side, -1)), add(start, scale(side, -1))]+ vertices = top + [add(point, (0, -thickness, 0)) for point in top]+ faces = [(0, 1, 2, 3), (7, 6, 5, 4)]+ faces.extend((i, i + 4, (i + 1) % 4 + 4, (i + 1) % 4) for i in range(4))+ return vertices, faces+++def dish_mesh(radius, depth, rings=20, segments=72, thickness=0.10):+ """Closed parabolic reflector shell, with a real back and rim."""+ vertices = [(0, 0, 0), (0, -thickness, 0)]+ for surface in (0, 1):+ for ring in range(1, rings + 1):+ r = radius * ring / rings+ for index in range(segments):+ angle = math.tau * index / segments+ vertices.append(+ (+ r * math.cos(angle),+ depth * (r / radius) ** 2 - surface * thickness,+ r * math.sin(angle),+ )+ )+ front, back = 2, 2 + rings * segments+ faces = []+ for index in range(segments):+ following = (index + 1) % segments+ faces.extend(((0, front + following, front + index), (1, back + index, back + following)))+ for ring in range(rings - 1):+ for index in range(segments):+ following = (index + 1) % segments+ a, b = front + ring * segments + index, front + ring * segments + following+ c, d = back + ring * segments + index, back + ring * segments + following+ faces.extend(((a, b, b + segments, a + segments), (c + segments, d + segments, d, c)))+ for index in range(segments):+ following = (index + 1) % segments+ a = front + (rings - 1) * segments+ b = back + (rings - 1) * segments+ faces.append((a + index, a + following, b + following, b + index))+ return vertices, faces+++def operations_walls(center=(-26, 0, 14), size=(20, 8, 14)):+ """Collision solids leave a genuine south door and open station approach."""+ x, y, z = center+ width, height, depth = size+ thickness, gap = 0.38, 3.0+ shoulder = (width - gap) / 2+ return [+ ("west", (x - width / 2 + thickness / 2, y + height / 2, z), (thickness, height, depth)),+ ("east", (x + width / 2 - thickness / 2, y + height / 2, z), (thickness, height, depth)),+ ("north", (x, y + height / 2, z - depth / 2 + thickness / 2), (width, height, thickness)),+ (+ "south-west",+ (x - gap / 2 - shoulder / 2, y + height / 2, z + depth / 2 - thickness / 2),+ (shoulder, height, thickness),+ ),+ (+ "south-east",+ (x + gap / 2 + shoulder / 2, y + height / 2, z + depth / 2 - thickness / 2),+ (shoulder, height, thickness),+ ),+ ("lintel", (x, y + 5.5, z + depth / 2 - thickness / 2), (gap, 5, thickness)),+ ("jamb-west", (x - 1.35, y + 1.5, z + depth / 2), (0.3, 3, 0.6)),+ ("jamb-east", (x + 1.35, y + 1.5, z + depth / 2), (0.3, 3, 0.6)),+ ]+++def closed_edges(faces):+ counts = Counter()+ for face in faces:+ for index, a in enumerate(face):+ counts[tuple(sorted((a, face[(index + 1) % len(face)])))] += 1+ return all(count == 2 for count in counts.values())+++def tower_sections():+ """Constant-width equipment decks replace the rejected continuous cone."""+ return [+ {"bottom": 5.8, "top": 20.5, "width": 7.8, "depth": 7.2},+ {"bottom": 20.5, "top": 35.0, "width": 5.6, "depth": 5.0},+ {"bottom": 35.0, "top": 47.0, "width": 3.5, "depth": 3.0},+ ]+++SURFACE_PROFILES = {+ "paint": {"seed": 41, "tile_metres": 0.24, "relief_metres": 0.00012, "roughness_span": 0.025},+ "metal": {"seed": 87, "tile_metres": 0.20, "relief_metres": 0.00006, "roughness_span": 0.04},+ "mineral": {"seed": 129, "tile_metres": 1.8, "relief_metres": 0.018, "roughness_span": 0.10},+ "concrete": {"seed": 173, "tile_metres": 0.8, "relief_metres": 0.0012, "roughness_span": 0.05},+ "paving": {"seed": 191, "tile_metres": 0.65, "relief_metres": 0.0006, "roughness_span": 0.04},+ "road": {"seed": 219, "tile_metres": 0.6, "relief_metres": 0.001, "roughness_span": 0.06},+}+++def surface_grain(family, resolution=256):+ """Periodic stochastic microrelief with slopes derived from physical metres.++ Relief is a material property, not silhouette displacement. Paint must not+ inherit centimetre-scale rock grain, and polished aggregate is distinct from+ cliff stone. Independent lattice samples avoid diagonal hash correlations;+ no sinusoidal banding is painted across unrelated manufactured surfaces.+ """+ profile = SURFACE_PROFILES[family]+ grids = (8, 31, 71)+ lattices = {}+ for grid in grids:+ rng = random.Random(profile["seed"] + grid * 1009) # noqa: S311 - repeatable material.+ lattices[grid] = [rng.random() for _ in range(grid * grid)]++ def noise(x, y, grid):+ x, y = x * grid / resolution, y * grid / resolution+ ix, iy = math.floor(x), math.floor(y)+ fx, fy = x - ix, y - iy+ fx, fy = fx * fx * (3 - 2 * fx), fy * fy * (3 - 2 * fy)++ def sample(dx, dy):+ return lattices[grid][((iy + dy) % grid) * grid + (ix + dx) % grid]++ a, b, c, d = sample(0, 0), sample(1, 0), sample(0, 1), sample(1, 1)+ return (a * (1 - fx) + b * fx) * (1 - fy) + (c * (1 - fx) + d * fx) * fy++ values = []+ for y in range(resolution):+ for x in range(resolution):+ coarse, middle, fine = (noise(x, y, grid) for grid in grids)+ values.append(0.20 * coarse + 0.35 * middle + 0.45 * fine)+ strength = profile["relief_metres"] * resolution / (2 * profile["tile_metres"])+ normals = []+ for y in range(resolution):+ for x in range(resolution):+ dx = (+ values[y * resolution + (x + 1) % resolution]+ - values[y * resolution + (x - 1) % resolution]+ )+ dy = (+ values[((y + 1) % resolution) * resolution + x]+ - values[((y - 1) % resolution) * resolution + x]+ )+ normal = normalized((-dx * strength, -dy * strength, 1))+ normals.extend((normal[0] * 0.5 + 0.5, normal[1] * 0.5 + 0.5, normal[2] * 0.5 + 0.5, 1))+ return values, normals+++def polygon_area(points):+ """Signed area in the runtime X/Z ground plane."""+ return (+ sum(+ a[0] * b[1] - b[0] * a[1] for a, b in zip(points, [*points[1:], points[0]], strict=True)+ )+ / 2+ if points+ else 0+ )+++def subtract_convex_polygon(subject, cutter):+ """Partition a convex surface around another, without coplanar overlap.++ Each emitted piece lies outside one cutter half-plane. The portion inside+ that plane continues to the next edge; consequently emitted pieces cannot+ overlap one another. Coordinates and the retained surface elevation stay+ unchanged, unlike polygon-offset or small height-shift workarounds.+ """+ # Most route pairs are far apart. Avoid splitting an unrelated surface on+ # the infinite extension of cutter edges, which adds needless tessellation.+ if any(+ max(point[axis] for point in subject) <= min(point[axis] for point in cutter)+ or max(point[axis] for point in cutter) <= min(point[axis] for point in subject)+ for axis in (0, 1)+ ):+ return [subject]+ if polygon_area(cutter) < 0:+ cutter = list(reversed(cutter))+ remaining, result = list(subject), []+ for start, end in zip(cutter, [*cutter[1:], cutter[0]], strict=True):+ if not remaining:+ break++ def distance(point, start=start, end=end):+ return (end[0] - start[0]) * (point[1] - start[1]) - (end[1] - start[1]) * (+ point[0] - start[0]+ )++ inside, outside = [], []+ for a, b in zip(remaining, [*remaining[1:], remaining[0]], strict=True):+ da, db = distance(a), distance(b)+ (inside if da >= 0 else outside).append(a)+ if (da > 0 and db < 0) or (da < 0 and db > 0):+ t = da / (da - db)+ intersection = (a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t)+ inside.append(intersection)+ outside.append(intersection)+ elif da == 0:+ outside.append(a)+ if abs(polygon_area(outside)) > 1e-8:+ result.append(outside)+ remaining = inside if abs(polygon_area(inside)) > 1e-8 else []+ return result+++def road_surface_pieces(routes):+ """Yield nonoverlapping convex top surfaces; earlier routes own junctions."""+ occupied = []+ for label, polygon, material in routes:+ pieces = [polygon]+ for cutter in occupied:+ pieces = [part for piece in pieces for part in subtract_convex_polygon(piece, cutter)]+ if not pieces:+ break+ for index, piece in enumerate(pieces):+ yield f"{label} surface {index:02d}", piece, material+ occupied.append(polygon)+++def road_piece_mesh(polygon, height=0.006, thickness=0.24):+ """Closed supporting road volume with one nonoverlapping top polygon."""+ vertices = [(x, height, z) for x, z in polygon]+ vertices.extend((x, height - thickness, z) for x, z in polygon)+ count = len(polygon)+ top = list(range(count))+ if polygon_area(polygon) > 0:+ top.reverse()+ faces = [tuple(top), tuple(index + count for index in reversed(top))]+ faces.extend((b, a, a + count, b + count) for a, b in zip(top, [*top[1:], top[0]], strict=True))+ return vertices, faces+++def fracture_center_y(center_y, vertical_radius):+ """Decorative cliff fragments never pierce the paved terrace above them."""+ return min(center_y, -0.20 - vertical_radius)+++def glb_attribute_values(document, binary, index):+ """Read actual accessor bytes, respecting both offsets and padded strides."""+ accessor = document["accessors"][index]+ view = document["bufferViews"][accessor["bufferView"]]+ if view.get("buffer", 0) != 0 or "sparse" in accessor:+ raise ValueError("reference attribute must use its embedded nonsparse buffer")+ formats = {5121: "B", 5123: "H", 5125: "I", 5126: "f"}+ components = {"SCALAR": 1, "VEC2": 2, "VEC3": 3, "VEC4": 4}+ kind, component_type = accessor["type"], accessor["componentType"]+ if kind not in components or component_type not in formats:+ raise ValueError("unsupported reference accessor representation")+ unpack = "<" + formats[component_type] * components[kind]+ size = struct.calcsize(unpack)+ stride = view.get("byteStride", size)+ relative = accessor.get("byteOffset", 0)+ view_start = view.get("byteOffset", 0)+ count = accessor["count"]+ if count < 1 or stride < size or relative < 0 or view_start < 0:+ raise ValueError("invalid reference accessor bounds or stride")+ end = relative + (count - 1) * stride + size+ if end > view["byteLength"] or view_start + view["byteLength"] > len(binary):+ raise ValueError("reference accessor extends beyond its buffer view")+ divisor = {5121: 255, 5123: 65535}.get(component_type, 1)+ if not accessor.get("normalized", False):+ divisor = 1+ for position in range(count):+ values = struct.unpack_from(unpack, binary, view_start + relative + position * stride)+ yield tuple(value / divisor for value in values)+++def validate_glb_material_attributes(raw):+ """Reject numeric corruption that a syntactically valid GLB can conceal."""+ if len(raw) < 20 or struct.unpack_from("<III", raw) != (0x46546C67, 2, len(raw)):+ raise ValueError("invalid reference GLB header")+ offset, document, binary = 12, None, None+ while offset < len(raw):+ if offset + 8 > len(raw):+ raise ValueError("truncated reference GLB chunk")+ size, kind = struct.unpack_from("<II", raw, offset)+ offset += 8+ if offset + size > len(raw):+ raise ValueError("truncated reference GLB chunk data")+ if kind == 0x4E4F534A:+ document = json.loads(raw[offset : offset + size])+ elif kind == 0x004E4942:+ binary = raw[offset : offset + size]+ offset += size+ if document is None or binary is None:+ raise ValueError("reference GLB needs embedded JSON and binary data")+ color_min, color_max, uv_max, colored = 1.0, 0.0, 0.0, 0+ for mesh in document.get("meshes", []):+ for primitive in mesh["primitives"]:+ attributes = primitive["attributes"]+ expected_count = document["accessors"][attributes["POSITION"]]["count"]+ for semantic in ("COLOR_0", "TEXCOORD_0", "NORMAL", "TANGENT"):+ if semantic not in attributes:+ continue+ index = attributes[semantic]+ accessor = document["accessors"][index]+ if accessor["count"] != expected_count:+ raise ValueError(f"{semantic} count does not match positions")+ if semantic == "COLOR_0":+ colored += 1+ if accessor["type"] not in {"VEC3", "VEC4"}:+ raise ValueError("COLOR_0 requires RGB or RGBA values")+ if accessor["componentType"] != 5126 and not accessor.get("normalized"):+ raise ValueError("integer COLOR_0 data must be normalized")+ for values in glb_attribute_values(document, binary, index):+ if not all(math.isfinite(value) for value in values):+ raise ValueError(f"{semantic} contains nonfinite data")+ if semantic == "COLOR_0":+ if min(values) < 0 or max(values) > 1:+ raise ValueError(+ f"COLOR_0 outside linear [0, 1] in {mesh.get('name', 'mesh')}"+ )+ color_min, color_max = min(color_min, *values), max(color_max, *values)+ elif semantic == "TEXCOORD_0":+ uv_max = max(uv_max, *(abs(value) for value in values))+ elif not 0.98 <= sum(value * value for value in values[:3]) <= 1.02:+ raise ValueError(f"{semantic} is not a unit direction")+ return {+ "colored_primitives": colored,+ "linear_color_range": [color_min, color_max],+ "uv_abs_max": uv_max,+ }+++def validate_source_path_records(records):+ """Validate field classes without including a rejected path in diagnostics."""+ for field, value in records:+ if isinstance(value, bytes):+ value = value.decode("utf-8")+ # Blender restores native separators after the unchanged // relative prefix.+ portable = value.replace("\\", "/") if value.startswith("//") else value+ if field in {"Image.filepath", "ImagePackedFile.filepath"}:+ valid = re.fullmatch(r"//materials/[a-z]+(?:-[a-z]+)*\.png", portable)+ elif field == "FileSelectParams.dir":+ valid = value == "//"+ elif field == "RenderData.pic":+ valid = portable == "//renders/"+ else:+ raise ValueError("unknown authoring path field class")+ if not valid:+ raise ValueError(f"{field} is not a portable authoring path")+ return {"validated_fields": len(records)}+++def source_path_records(bpy_module):+ records = []+ for image in bpy_module.data.images:+ if not image.filepath:+ continue+ if not image.packed_files:+ raise ValueError("a file-backed authoring image is not packed")+ records.append(("Image.filepath", image.filepath))+ records.extend(+ ("ImagePackedFile.filepath", packed.filepath) for packed in image.packed_files+ )+ for screen in bpy_module.data.screens:+ for area in screen.areas:+ for space in area.spaces:+ if space.type == "FILE_BROWSER" and space.params is not None:+ records.append(("FileSelectParams.dir", space.params.directory))+ records.extend(("RenderData.pic", scene.render.filepath) for scene in bpy_module.data.scenes)+ return records+++def sanitize_source_metadata(bpy_module):+ """Clear packed-image snapshots and file-browser defaults, preserving pixels."""++ def replace_field(owner, field, value):+ maximum = owner.bl_rna.properties[field].length_max+ # RNA can retain the tail of a fixed-size serialized char array. Replace+ # the entire capacity with neutral bytes before assigning the short path.+ neutral = "_" * (maximum - 1)+ if isinstance(value, bytes):+ neutral = neutral.encode("ascii")+ setattr(owner, field, neutral)+ setattr(owner, field, value)++ packed_count = 0+ for image in bpy_module.data.images:+ if not image.filepath:+ continue+ if not image.packed_files:+ raise ValueError("cannot sanitize an unpacked authoring image")+ filename = image.filepath.replace("\\", "/").rsplit("/", 1)[-1]+ portable = "//materials/" + filename+ validate_source_path_records([("Image.filepath", portable)])+ # filepath_raw writes the same serialized buffer without asking Blender+ # to reload each temporary neutral path during fixed-size tail clearing.+ replace_field(image, "filepath_raw", portable)+ for packed in image.packed_files:+ replace_field(packed, "filepath", portable)+ packed_count += 1+ browser_count = 0+ for screen in bpy_module.data.screens:+ for area in screen.areas:+ for space in area.spaces:+ if space.type == "FILE_BROWSER" and space.params is not None:+ replace_field(space.params, "directory", b"//")+ replace_field(space.params, "filename", "")+ browser_count += 1+ for scene in bpy_module.data.scenes:+ replace_field(scene.render, "filepath", "//renders/")+ result = validate_source_path_records(source_path_records(bpy_module))+ return {**result, "packed_image_files": packed_count, "file_browser_defaults": browser_count}+++class Author:+ """Source objects stay editable; evaluated exports are batched by material."""++ def __init__(self, layout, study=STUDY):+ import bpy+ from mathutils import Vector++ self.bpy, self.Vector = bpy, Vector+ self.layout = layout+ self.study = study+ self.rng = random.Random(layout["seed"]) # noqa: S311 - authored geometry seed.+ bpy.ops.object.select_all(action="SELECT")+ bpy.ops.object.delete(use_global=False)+ self.source = bpy.data.collections.new("Editable architecture")+ self.export = bpy.data.collections.new("Export")+ bpy.context.scene.collection.children.link(self.source)+ bpy.context.scene.collection.children.link(self.export)+ self.groups, self.materials = {}, {}+ self.colliders, self.anchors = [], []+ self.current = "terrain"+ self.palette()+ self.material_surface_maps()++ def palette(self):+ settings = {+ "cliff": ((0.29, 0.092, 0.034), 0.0, 0.96),+ "rock-highlight": ((0.42, 0.18, 0.077), 0.0, 0.9),+ "rock-shadow": ((0.19, 0.059, 0.027), 0.0, 0.98),+ "paving": ((0.24, 0.25, 0.24), 0.0, 0.78),+ "road": ((0.082, 0.096, 0.11), 0.0, 0.88),+ "concrete": ((0.39, 0.35, 0.29), 0.0, 0.84),+ "ceramic": ((0.73, 0.73, 0.67), 0.0, 0.34),+ "ceramic-warm": ((0.61, 0.61, 0.56), 0.0, 0.43),+ "structure": ((0.075, 0.095, 0.12), 0.74, 0.37),+ "metal": ((0.40, 0.46, 0.49), 0.82, 0.3),+ "gold": ((0.34, 0.23, 0.11), 0.8, 0.34),+ "rubber": ((0.025, 0.033, 0.041), 0.0, 0.75),+ "glass": ((0.04, 0.14, 0.2), 0.15, 0.2),+ "screen": ((0.024, 0.059, 0.084), 0.15, 0.25),+ "marking": ((0.67, 0.70, 0.66), 0.0, 0.8),+ "ochre": ((0.48, 0.29, 0.075), 0.1, 0.62),+ "blue": ((0.012, 0.30, 0.75), 0.2, 0.24),+ "warm-light": ((0.95, 0.64, 0.24), 0.0, 0.35),+ "painted-alloy": ((0.34, 0.39, 0.41), 0.0, 0.50),+ "roof-alloy": ((0.40, 0.42, 0.40), 0.35, 0.65),+ "dust-coated": ((0.34, 0.25, 0.17), 0.12, 0.86),+ }+ for name, (color, metallic, roughness) in settings.items():+ material = self.bpy.data.materials.new(name)+ material.diffuse_color = (*color, 1)+ material.use_nodes = True+ shader = material.node_tree.nodes.get("Principled BSDF")+ shader.inputs["Base Color"].default_value = (*color, 1)+ shader.inputs["Metallic"].default_value = metallic+ shader.inputs["Roughness"].default_value = roughness+ if name in {"blue", "warm-light"}:+ shader.inputs["Emission Color"].default_value = (*color, 1)+ shader.inputs["Emission Strength"].default_value = 3.0 if name == "blue" else 1.8+ if name == "glass":+ shader.inputs["Transmission Weight"].default_value = 0.62+ shader.inputs["IOR"].default_value = 1.45+ self.materials[name] = material++ def material_surface_maps(self):+ """Embed authored roughness/normal maps and material-aware color tinting."""+ folder = self.study / "source/materials"+ folder.mkdir(parents=True, exist_ok=True)+ resolution = 256+ grains = {family: surface_grain(family, resolution) for family in SURFACE_PROFILES}+ families = {+ "cliff": "mineral",+ "rock-highlight": "mineral",+ "rock-shadow": "mineral",+ "concrete": "concrete",+ "paving": "paving",+ "road": "road",+ "ceramic": "paint",+ "ceramic-warm": "paint",+ "painted-alloy": "paint",+ "roof-alloy": "metal",+ "structure": "metal",+ "metal": "metal",+ "gold": "metal",+ "dust-coated": "concrete",+ }+ normal_images = {}+ self.material_families = families+ for family, (_, pixels) in grains.items():+ image = self.bpy.data.images.new(f"Authored {family} relief", resolution, resolution)+ image.colorspace_settings.name = "Non-Color"+ image.pixels.foreach_set(array("f", pixels))+ image.filepath_raw = str(folder / f"{family}-normal.png")+ image.file_format = "PNG"+ image.save()+ packed_data = (folder / f"{family}-normal.png").read_bytes()+ image.filepath_raw = f"//materials/{family}-normal.png"+ # Explicit bytes work before a new .blend has a relative base path.+ image.pack(data=packed_data, data_len=len(packed_data))+ normal_images[family] = image+ for name, family in families.items():+ material = self.materials[name]+ shader = material.node_tree.nodes.get("Principled BSDF")+ roughness = shader.inputs["Roughness"].default_value+ pixels = array("f")+ for grain in grains[family][0]:+ variation = (grain - 0.5) * SURFACE_PROFILES[family]["roughness_span"]+ value = min(0.99, max(0.08, roughness + variation))+ pixels.extend((value, value, value, 1))+ image = self.bpy.data.images.new(f"Authored {name} roughness", resolution, resolution)+ image.colorspace_settings.name = "Non-Color"+ image.pixels.foreach_set(pixels)+ image.filepath_raw = str(folder / f"{name}-roughness.png")+ image.file_format = "PNG"+ image.save()+ packed_data = (folder / f"{name}-roughness.png").read_bytes()+ image.filepath_raw = f"//materials/{name}-roughness.png"+ image.pack(data=packed_data, data_len=len(packed_data))+ nodes, links = material.node_tree.nodes, material.node_tree.links+ roughness_map = nodes.new("ShaderNodeTexImage")+ roughness_map.image = image+ links.new(roughness_map.outputs["Color"], shader.inputs["Roughness"])+ texture = nodes.new("ShaderNodeTexImage")+ texture.image = normal_images[family]+ normal = nodes.new("ShaderNodeNormalMap")+ normal.inputs["Strength"].default_value = 1+ links.new(texture.outputs["Color"], normal.inputs["Color"])+ links.new(normal.outputs["Normal"], shader.inputs["Normal"])+ color = nodes.new("ShaderNodeVertexColor")+ color.layer_name = "Surface tint"+ links.new(color.outputs["Color"], shader.inputs["Base Color"])++ def group(self, name):+ self.current = name+ if name not in self.groups:+ collection = self.bpy.data.collections.new(name)+ self.source.children.link(collection)+ self.groups[name] = collection++ def adopt(self, obj, name, material, smooth=False, bevel=0):+ obj.name = name+ for collection in list(obj.users_collection):+ collection.objects.unlink(obj)+ if self.current not in self.groups:+ self.group(self.current)+ self.groups[self.current].objects.link(obj)+ obj.data.materials.append(self.materials[material])+ if smooth:+ for polygon in obj.data.polygons:+ polygon.use_smooth = True+ if bevel:+ modifier = obj.modifiers.new("Manufactured edge radius", "BEVEL")+ modifier.width, modifier.segments = bevel, 3+ modifier.limit_method = "ANGLE"+ modifier = obj.modifiers.new("Weighted corner normals", "WEIGHTED_NORMAL")+ modifier.keep_sharp = True+ return obj++ def mesh(self, name, vertices, faces, material, smooth=False):+ mesh = self.bpy.data.meshes.new(name)+ mesh.from_pydata([blender_point(vertex) for vertex in vertices], [], faces)+ mesh.update()+ obj = self.bpy.data.objects.new(name, mesh)+ self.groups[self.current].objects.link(obj)+ return self.adopt(obj, name, material, smooth)++ def box(self, name, center, size, material, bevel=0.06, yaw=0):+ self.bpy.ops.mesh.primitive_cube_add(size=1, location=blender_point(center))+ obj = self.bpy.context.object+ obj.dimensions = (size[0], size[2], size[1])+ self.bpy.ops.object.transform_apply(location=False, rotation=False, scale=True)+ obj.rotation_euler.z = -yaw+ return self.adopt(obj, name, material, bevel=bevel)++ def cylinder(self, name, center, radius, height, material, top=None, vertices=48):+ self.bpy.ops.mesh.primitive_cone_add(+ vertices=vertices,+ radius1=radius,+ radius2=radius if top is None else top,+ depth=height,+ location=blender_point(center),+ )+ return self.adopt(self.bpy.context.object, name, material, smooth=True, bevel=0.035)++ def beam(self, name, start, end, radius, material, vertices=10):+ direction = self.Vector(blender_point(tuple(end[i] - start[i] for i in range(3))))+ self.bpy.ops.mesh.primitive_cylinder_add(+ vertices=vertices,+ radius=radius,+ depth=direction.length,+ location=blender_point(lerp(start, end, 0.5)),+ )+ obj = self.bpy.context.object+ obj.rotation_euler = direction.to_track_quat("Z", "Y").to_euler()+ return self.adopt(obj, name, material, smooth=True)++ def tube(self, name, points, radius, material, closed=False, resolution=2):+ curve = self.bpy.data.curves.new(name, "CURVE")+ curve.dimensions, curve.resolution_u = "3D", 1+ curve.bevel_depth, curve.bevel_resolution = radius, resolution+ curve.resolution_u = 1+ spline = curve.splines.new("POLY")+ spline.points.add(len(points) - 1)+ for vertex, point in zip(spline.points, points, strict=True):+ vertex.co = (*blender_point(point), 1)+ spline.use_cyclic_u = closed+ obj = self.bpy.data.objects.new(name, curve)+ self.groups[self.current].objects.link(obj)+ curve.materials.append(self.materials[material])+ return obj++ def ring(self, name, center, radius, thickness, material, segments=64):+ return self.tube(+ name,+ [+ add(+ center,+ (+ radius * math.cos(math.tau * i / segments),+ 0,+ radius * math.sin(math.tau * i / segments),+ ),+ )+ for i in range(segments)+ ],+ thickness,+ material,+ True,+ )++ def text(self, name, body, center, size, material, yaw=0):+ curve = self.bpy.data.curves.new(name, "FONT")+ curve.body, curve.size, curve.align_x, curve.align_y = body, size, "CENTER", "CENTER"+ curve.extrude, curve.resolution_u = 0.002, 2+ obj = self.bpy.data.objects.new(name, curve)+ self.groups[self.current].objects.link(obj)+ obj.location = blender_point(center)+ # Face runtime +Z (south); local text Y becomes runtime up.+ obj.rotation_euler = (math.pi / 2, 0, -yaw)+ curve.materials.append(self.materials[material])+ return obj++ def collider(self, identifier, center, size, **extras):+ self.colliders.append(+ {"id": identifier, "shape": "box", "center": list(center), "size": list(size), **extras}+ )++ def anchor(self, identifier, position, **extras):+ record = {"id": identifier, "position": list(position), **extras}+ previous = next((item for item in self.anchors if item["id"] == identifier), None)+ if previous is not None:+ if previous != record:+ raise ValueError(f"anchor identity has conflicting definitions: {identifier}")+ return+ self.anchors.append(record)++ def terrain(self):+ self.group("01 Rock strata and foundations")+ vertices, faces = plateau_mesh(self.layout["seed"])+ cliff = self.mesh("Layered closed Outpost plateau", vertices, faces, "cliff")+ # Color variation follows stone layers rather than random decoration.+ cliff.data.materials.append(self.materials["rock-highlight"])+ cliff.data.materials.append(self.materials["rock-shadow"])+ for polygon in cliff.data.polygons:+ height = polygon.center.z+ polygon.material_index = (+ 1 if -19 < height < -15 or -39 < height < -35 else (2 if -31 < height < -27 else 0)+ )+ self.colliders.append(+ {+ "id": "plateau-surface",+ "shape": "plateau",+ "top_y": -0.12,+ "footprint": [[point[0], point[2]] for point in vertices[:128]],+ "bottom_y": min(point[1] for point in vertices),+ "walkable": True,+ }+ )+ for index in range(68):+ angle = math.tau * index / 68+ x = math.copysign(abs(math.cos(angle)) ** 0.58, math.cos(angle)) * 59+ z = math.copysign(abs(math.sin(angle)) ** 0.58, math.sin(angle)) * 46+ self.bpy.ops.mesh.primitive_ico_sphere_add(+ subdivisions=1, radius=1, location=blender_point((x, self.rng.uniform(-25, -3), z))+ )+ rock = self.bpy.context.object+ rock.scale = (+ self.rng.uniform(1.6, 3.8),+ self.rng.uniform(1.4, 3.1),+ self.rng.uniform(3, 8),+ )+ rock.location.z = fracture_center_y(rock.location.z, rock.scale.z)+ self.adopt(+ rock,+ f"Exposed vertical fracture {index:02d}",+ "rock-highlight" if index % 4 == 0 else "cliff",+ )+ # Landing footings account for the west route extending beyond the rock lip.+ for center, size in [((-58, -2.1, 10), (20, 4, 27)), ((4, -2.1, 43), (21, 4, 16))]:+ self.box("Cantilever arrival abutment", center, size, "concrete", 0.2)+ self.anchor(+ "outpost-origin",+ (0, 0, 0),+ kind="district",+ layout_version=self.layout["layout_version"],+ )++ def rounded_perimeter(self, y=0):+ points = []+ for cx, cz, start in [(41, 28, 0), (-41, 28, 90), (-41, -28, 180), (41, -28, 270)]:+ for step in range(13):+ angle = math.radians(start + step * 90 / 12)+ points.append((cx + 14 * math.cos(angle), y, cz + 14 * math.sin(angle)))+ return points++ def paths(self):+ self.group("02 Paving and protected routes")+ outer = self.rounded_perimeter(-0.03)+ self.mesh(+ "Continuous engineered terrace",+ [(0, -0.03, 0), *outer],+ [(0, 1 + (i + 1) % len(outer), i + 1) for i in range(len(outer))],+ "paving",+ )+ self.tube(+ "Inner perimeter lane marking",+ [(p[0] * 0.943, 0.035, p[2] * 0.936) for p in outer],+ 0.035,+ "marking",+ True,+ 1,+ )+ nodes = self.layout["nodes"]+ routes = []+ for label, first, last, width in [+ ("Arrival road", "outpost-west", "outpost-arrival", 10),+ ("Operations footpath", "outpost-arrival", "console-approach", 4),+ ("South transport link", "outpost-arrival", "outpost-south", 10),+ ]:+ start, end = nodes[first], nodes[last]+ vertices, _ = deck_mesh(start, end, width)+ routes.append(+ (label, [(x, z) for x, _, z in vertices[:4]], "paving" if width == 4 else "road")+ )+ self.anchor(first, start, kind="navigation")+ self.anchor(last, end, kind="navigation")+ for index, start in enumerate(outer):+ end = outer[(index + 1) % len(outer)]+ vertices, _ = deck_mesh(start, end, 5.8)+ routes.append(+ (+ f"Perimeter road segment {index:02d}",+ [(x, z) for x, _, z in vertices[:4]],+ "road",+ )+ )+ # Top faces form a planar subdivision. No intersecting road rectangles+ # compete for depth at the arrival plaza or the curved perimeter joins.+ # Each piece retains a closed supporting slab under its top polygon.+ for label, polygon, material in road_surface_pieces(routes):+ vertices, faces = road_piece_mesh(polygon)+ self.mesh(label, vertices, faces, material)+ # Seams are organized in service plazas, away from travel corridors.+ for z in (-17, -13, -9, 26, 30):+ self.tube(+ "Terrace expansion joint",+ [(-12, 0.003, z), (21, 0.003, z)],+ 0.018,+ "rubber",+ resolution=1,+ )+ for index, point in enumerate(outer):+ if index % 3:+ continue+ x, _, z = point+ if x < -50 and -8 < z < 25 or z > 38 and -6 < x < 15:+ continue+ outward = normalized((x / 55, 0, z / 42))+ base = add(point, scale(outward, 3.3))+ self.lamp(f"Perimeter luminaire {index:02d}", base, 3.3)+ # A low retaining curb leaves the actual arrival/south junctions open.+ for index, start in enumerate(outer):+ end = outer[(index + 1) % len(outer)]+ mid = lerp(start, end, 0.5)+ if mid[0] < -50 and -8 < mid[2] < 25 or mid[2] > 38 and -8 < mid[0] < 18:+ continue+ raised = [(p[0] * 1.059, 0.45, p[2] * 1.076) for p in (start, end)]+ self.beam("Terrace edge guardrail", raised[0], raised[1], 0.07, "metal")+ self.beam(+ "Terrace edge post",+ (raised[0][0], 0, raised[0][2]),+ add(raised[0], (0, 0.65, 0)),+ 0.065,+ "structure",+ )++ def lamp(self, name, base, height):+ self.box(name + " foot", add(base, (0, 0.08, 0)), (0.42, 0.16, 0.42), "structure", 0.04)+ self.box(+ name + " mast", add(base, (0, height / 2, 0)), (0.10, height, 0.16), "metal", 0.015+ )+ self.box(+ name + " housing", add(base, (0, height, 0)), (0.65, 0.15, 0.42), "structure", 0.04+ )+ self.box(+ name + " diffuser",+ add(base, (0, height - 0.081, 0)),+ (0.51, 0.025, 0.31),+ "warm-light",+ 0.01,+ )++ def roof_plant(self, name, center, width, depth, roof_y):+ """Mounted roof plant stays within the building's existing footprint."""+ x, _, z = center+ for sign in (-1, 1):+ self.box(+ name + " parapet long side",+ (x, roof_y + 0.20, z + sign * (depth / 2 - 0.20)),+ (width - 0.1, 0.4, 0.26),+ "ceramic-warm",+ 0.05,+ )+ self.box(+ name + " parapet return",+ (x + sign * (width / 2 - 0.2), roof_y + 0.20, z),+ (0.26, 0.4, depth - 0.2),+ "ceramic-warm",+ 0.05,+ )+ self.box(+ name + " rooftop mechanical skid",+ (x + 0.5, roof_y + 0.32, z - 0.4),+ (width * 0.48, 0.52, depth * 0.44),+ "painted-alloy",+ 0.12,+ )+ fan_radius = min(width, depth) * 0.13+ for sign in (-1, 1):+ fan = (x + 0.5 + sign * width * 0.14, roof_y + 0.64, z - 0.4)+ self.cylinder(+ name + " ventilation fan shroud", fan, fan_radius, 0.22, "metal", vertices=40+ )+ self.cylinder(+ name + " recessed fan opening",+ add(fan, (0, 0.11, 0)),+ fan_radius * 0.82,+ 0.04,+ "structure",+ vertices=40,+ )+ for fraction in (0.25, 0.52, 0.78):+ self.ring(+ name + " fan protection ring",+ add(fan, (0, 0.15, 0)),+ fan_radius * fraction,+ 0.022,+ "metal",+ 40,+ )+ for angle in (0, math.pi / 2):+ direction = (math.cos(angle), 0, math.sin(angle))+ self.beam(+ name + " fan cross brace",+ add(fan, add(scale(direction, -fan_radius * 0.82), (0, 0.16, 0))),+ add(fan, add(scale(direction, fan_radius * 0.82), (0, 0.16, 0))),+ 0.024,+ "metal",+ 8,+ )+ self.tube(+ name + " roof duct return",+ [+ (x - width * 0.30, roof_y + 0.24, z + 0.7),+ (x - width * 0.30, roof_y + 0.68, z + 0.7),+ (x - width * 0.10, roof_y + 0.68, z + 0.7),+ ],+ 0.23,+ "metal",+ resolution=3,+ )+ for sign in (-1, 1):+ self.box(+ name + " equipment mounting saddle",+ (x + sign * width * 0.22, roof_y + 0.10, z - 0.4),+ (0.2, 0.20, depth * 0.54),+ "structure",+ 0.04,+ )++ def bridge(self):+ self.group("03 Colony bridge and pier structure")+ start, end = self.layout["nodes"]["hub-east"], self.layout["nodes"]["outpost-west"]+ vertices, faces = deck_mesh(start, end)+ self.mesh("Graded 10 metre bridge deck", vertices, faces, "road")+ direction = normalized((end[0] - start[0], 0, end[2] - start[2]))+ side = (-direction[2], 0, direction[0])+ for sign in (-1, 1):+ offset = scale(side, sign * 4.8)+ for height, radius, material in [+ (1.20, 0.075, "metal"),+ (0.58, 0.055, "metal"),+ (0.1, 0.08, "concrete"),+ ]:+ self.beam(+ "Continuous bridge railing",+ add(start, add(offset, (0, height, 0))),+ add(end, add(offset, (0, height, 0))),+ radius,+ material,+ 12,+ )+ for index in range(28):+ center = add(lerp(start, end, index / 27), offset)+ self.beam(+ "Bridge railing upright", center, add(center, (0, 1.23, 0)), 0.055, "structure"+ )+ if index % 4 == 0:+ self.box(+ "Bridge pedestrian light",+ add(center, (0, 0.8, 0)),+ (0.14, 0.35, 0.14),+ "warm-light",+ 0.015,+ )+ girder_start = add(start, add(scale(side, sign * 3.8), (0, -1.1, 0)))+ girder_end = add(end, add(scale(side, sign * 3.8), (0, -1.1, 0)))+ self.beam(+ "Longitudinal bridge box girder", girder_start, girder_end, 0.43, "structure", 4+ )+ self.beam(+ "Sidewalk segregation strip",+ add(start, scale(side, sign * 3.5)),+ add(end, scale(side, sign * 3.5)),+ 0.05,+ "marking",+ 6,+ )+ for index in range(1, 7):+ point = lerp(start, end, index / 7)+ bottom = -58+ self.box(+ f"Pier {index} spread footing",+ (point[0], bottom + 0.8, point[2]),+ (7.2, 1.6, 11),+ "concrete",+ 0.2,+ )+ for sign in (-1, 1):+ offset = scale(side, sign * 3.0)+ lower = (point[0] + offset[0], bottom + 1.6, point[2] + offset[2])+ upper = add(point, add(offset, (0, -1.1, 0)))+ self.beam(f"Pier {index} reinforced column", lower, upper, 0.95, "concrete", 8)+ self.beam(+ f"Pier {index} transverse cap",+ add(point, add(scale(side, -5), (0, -1.4, 0))),+ add(point, add(scale(side, 5), (0, -1.4, 0))),+ 0.7,+ "concrete",+ 4,+ )+ for index in range(1, 27):+ point = lerp(start, end, index / 27)+ self.beam(+ "Deck transverse rib",+ add(point, add(scale(side, -4.7), (0, -0.8, 0))),+ add(point, add(scale(side, 4.7), (0, -0.8, 0))),+ 0.15,+ "metal",+ 4,+ )+ if index % 2:+ tangent = scale(direction, 1.8)+ self.beam(+ "Bridge centre dash",+ add(point, scale(tangent, -0.5)),+ add(point, scale(tangent, 0.5)),+ 0.045,+ "marking",+ 6,+ )+ self.colliders.append(+ {+ "id": "bridge-deck",+ "shape": "graded-deck",+ "start": list(start),+ "end": list(end),+ "width": 10,+ "thickness": 0.65,+ "walkable": True,+ }+ )+ self.anchor("bridge-colony-end", start, kind="navigation")+ self.anchor("bridge-outpost-end", end, kind="navigation")++ def tower(self):+ self.group("04 Stepped communications mast")+ center = self.layout["buildings"]["communications-mast"]["local"]+ self.cylinder(+ "Tower spread foundation", add(center, (0, 0.18, 0)), 9.2, 0.36, "concrete", vertices=80+ )+ self.cylinder(+ "Equipment base weather skirt",+ add(center, (0, 0.55, 0)),+ 7,+ 1.1,+ "dust-coated",+ vertices=12,+ )+ self.cylinder(+ "Substantial communications service drum",+ add(center, (0, 3.2, 0)),+ 6.8,+ 5.5,+ "painted-alloy",+ vertices=12,+ )+ self.cylinder(+ "Service drum roof shoulder", add(center, (0, 6, 0)), 7, 0.4, "roof-alloy", vertices=12+ )+ for index in range(12):+ angle = math.tau * index / 12+ normal = (math.sin(angle), 0, math.cos(angle))+ tangent = (math.cos(angle), 0, -math.sin(angle))+ side = add(center, scale(normal, 6.58))+ self.box(+ "Drum recessed equipment bay",+ add(side, (0, 3, 0)),+ (2.7, 3.9, 0.22),+ "structure",+ 0.12,+ angle,+ )+ self.box(+ "Drum ceramic access hatch",+ add(side, add(scale(normal, 0.13), (0, 3.05, 0))),+ (2.35, 3.45, 0.16),+ "ceramic-warm" if index % 3 else "ceramic",+ 0.10,+ angle,+ )+ for sign in (-1, 1):+ self.box(+ "Drum hatch vertical lock rail",+ add(+ side,+ add(scale(tangent, sign * 1.01), add(scale(normal, 0.23), (0, 2.9, 0))),+ ),+ (0.11, 2.7, 0.09),+ "metal",+ 0.02,+ angle,+ )+ self.box(+ "Drum hatch inspection window",+ add(side, add(scale(normal, 0.23), (0, 3.8, 0))),+ (1.45, 0.48, 0.06),+ "glass",+ 0.045,+ angle,+ )+ self.box(+ "Drum illuminated bay header",+ add(side, add(scale(normal, 0.22), (0, 5.2, 0))),+ (1.7, 0.12, 0.1),+ "warm-light",+ 0.025,+ angle,+ )+ for level, section in enumerate(tower_sections()):+ bottom, top = section["bottom"], section["top"]+ width, depth = section["width"], section["depth"]+ middle = (bottom + top) / 2+ self.box(+ f"Core equipment section {level}",+ add(center, (0, middle, 0)),+ (width, top - bottom, depth),+ "painted-alloy",+ 0.28,+ )+ self.box(+ f"Core recessed level collar {level}",+ add(center, (0, bottom + 0.3, 0)),+ (width + 0.32, 0.6, depth + 0.32),+ "structure",+ 0.14,+ )+ self.box(+ f"Core overhanging weather cap {level}",+ add(center, (0, top - 0.18, 0)),+ (width + 0.48, 0.36, depth + 0.48),+ "roof-alloy",+ 0.14,+ )+ for sign in (-1, 1):+ for panel_index in range(3):+ panel_y = bottom + 2.7 + panel_index * (top - bottom - 2) / 3+ panel_height = (top - bottom - 2.5) / 3+ self.box(+ f"South-north removable tower bay {level}-{panel_index}",+ add(center, (0, panel_y, sign * (depth / 2 + 0.075))),+ (width * 0.72, panel_height, 0.14),+ "ceramic-warm" if panel_index % 2 else "ceramic",+ 0.09,+ )+ self.box(+ "Tower bay recessed vertical gasket",+ add(center, (width * 0.31, panel_y, sign * (depth / 2 + 0.16))),+ (0.055, panel_height * 0.86, 0.035),+ "rubber",+ 0.01,+ )+ self.box(+ f"Lateral spine panel {level}",+ add(center, (sign * (width / 2 + 0.05), middle, 0)),+ (0.14, top - bottom - 1.1, depth * 0.54),+ "ceramic-warm",+ 0.08,+ )+ for rise in (2.0, top - bottom - 2.0):+ self.box(+ "Tower coupling access cover",+ add(center, (sign * (width / 2 + 0.14), bottom + rise, 0)),+ (0.18, 1.4, 1.5),+ "metal",+ 0.06,+ )+ # Four independently staggered aerial racks define the communications silhouette.+ for index, angle in enumerate(+ (0.15, math.pi / 2 + 0.15, math.pi + 0.15, math.pi * 1.5 + 0.15)+ ):+ normal = (math.sin(angle), 0, math.cos(angle))+ tangent = (math.cos(angle), 0, -math.sin(angle))+ radius = 5.25+ bottom, top = 7.0, 29 + (index % 3) * 5+ low = add(center, add(scale(normal, radius), (0, bottom, 0)))+ high = add(center, add(scale(normal, radius), (0, top, 0)))+ for sign in (-1, 1):+ self.beam(+ "Aerial rack paired rail",+ add(low, scale(tangent, sign * 0.48)),+ add(high, scale(tangent, sign * 0.48)),+ 0.11,+ "metal",+ 10,+ )+ for step in range(int((top - bottom) / 2.5)):+ a = add(low, add(scale(tangent, -0.48 if step % 2 else 0.48), (0, step * 2.5, 0)))+ b = add(+ low, add(scale(tangent, 0.48 if step % 2 else -0.48), (0, (step + 1) * 2.5, 0))+ )+ self.beam("Aerial rack diagonal truss", a, b, 0.05, "structure", 8)+ for panel_index in range(3):+ height = top - 2.1 - panel_index * 6.2+ at = add(center, add(scale(normal, radius + 0.12), (0, height, 0)))+ self.box(+ "Staggered RF antenna module", at, (1.35, 3.8, 0.62), "ceramic", 0.2, angle+ )+ self.box(+ "RF module backing and heat sink",+ add(at, scale(normal, -0.40)),+ (1.15, 3.55, 0.25),+ "painted-alloy",+ 0.08,+ angle,+ )+ for offset in (-0.32, 0, 0.32):+ self.beam(+ "RF cooling rib",+ add(+ at, add(scale(tangent, offset), add(scale(normal, -0.57), (0, -1.4, 0)))+ ),+ add(+ at, add(scale(tangent, offset), add(scale(normal, -0.57), (0, 1.4, 0)))+ ),+ 0.035,+ "metal",+ 8,+ )+ self.beam(+ "Aerial rack base brace",+ add(center, add(scale(normal, 6.35), (0, 0.8, 0))),+ low,+ 0.24,+ "painted-alloy",+ 8,+ )+ # Open upper lattice carries short antenna panels; it is not a cone cladding.+ for sign_x in (-1, 1):+ for sign_z in (-1, 1):+ self.beam(+ "Upper mast structural chord",+ add(center, (sign_x * 1.18, 46.8, sign_z * 1.05)),+ add(center, (sign_x * 0.58, 57, sign_z * 0.52)),+ 0.09,+ "metal",+ 10,+ )+ for step in range(5):+ y = 47 + step * 2+ radius = 1.18 - step * 0.11+ for sign in (-1, 1):+ self.beam(+ "Upper mast bracing",+ add(center, (-radius, y, sign * radius)),+ add(center, (radius - 0.1, y + 2, sign * (radius - 0.1))),+ 0.045,+ "structure",+ 8,+ )+ for sign, height in [(-1, 50), (1, 54)]:+ self.box(+ "Upper point-to-point aerial",+ add(center, (sign * 1.6, height, 0)),+ (0.6, 3.0, 0.72),+ "ceramic",+ 0.16,+ )+ self.beam(+ "Upper aerial mount",+ add(center, (0, height - 0.4, 0)),+ add(center, (sign * 1.6, height - 0.4, 0)),+ 0.09,+ "metal",+ )+ self.cylinder("Top antenna shaft", add(center, (0, 59.2, 0)), 0.20, 4.4, "metal", top=0.11)+ self.cylinder(+ "Blue beacon enclosure", add(center, (0, 61.6, 0)), 0.43, 0.5, "blue", top=0.32+ )+ self.cylinder("Lightning tip", add(center, (0, 61.94, 0)), 0.07, 0.12, "metal", top=0.01)+ for height, x in ((16, 4.2), (32, -3.0), (45, 1.9)):+ self.box(+ "Sparse blue relay hardware",+ add(center, (x, height, 0.5)),+ (0.18, 0.95, 0.20),+ "blue",+ 0.06,+ )+ self.box(+ "Blank mast brand plate",+ add(center, (0, 12.6, 3.78)),+ (3.4, 2.8, 0.12),+ "ceramic",+ 0.10,+ )+ self.anchor(+ "mast-brand-slot",+ add(center, (0, 12.6, 3.86)),+ kind="branding-slot",+ verified_source=False,+ )+ self.collider("communications-mast", add(center, (0, 31, 0)), (14, 62, 14))++ def reflector(self, identifier, radius, depth, height, aim):+ self.group("05 " + identifier)+ center = self.layout["buildings"][identifier]["local"]+ self.cylinder(+ identifier + " foundation",+ add(center, (0, 0.25, 0)),+ radius * 0.7,+ 0.5,+ "concrete",+ vertices=64,+ )+ self.cylinder(+ identifier + " equipment house",+ add(center, (0, 2, 0)),+ radius * 0.61,+ 3.6,+ "ceramic-warm",+ vertices=12,+ )+ self.ring(+ identifier + " slew bearing", add(center, (0, 4, 0)), radius * 0.53, 0.25, "metal"+ )+ self.cylinder(+ identifier + " azimuth pedestal",+ add(center, (0, 6.4, 0)),+ 2.5,+ 4.5,+ "structure",+ top=1.7,+ vertices=24,+ )+ direction = normalized(aim)+ horizontal = normalized(cross((0, 1, 0), direction))+ vertical = normalized(cross(direction, horizontal))+ origin = add(center, (0, height, 0))++ def position(point):+ return add(+ origin,+ add(+ scale(horizontal, point[0]),+ add(scale(direction, point[1]), scale(vertical, point[2])),+ ),+ )++ vertices, faces = dish_mesh(radius, depth)+ self.mesh(+ identifier + " parabolic front and rear shell",+ [position(point) for point in vertices],+ faces,+ "ceramic",+ True,+ )+ for fraction in (0.33, 0.67, 1.0):+ ring_radius = radius * fraction+ self.tube(+ identifier + " reflector seam",+ [+ position(+ (+ ring_radius * math.cos(math.tau * i / 72),+ depth * fraction**2 + 0.018,+ ring_radius * math.sin(math.tau * i / 72),+ )+ )+ for i in range(72)+ ],+ 0.018 if fraction < 1 else 0.075,+ "metal",+ True,+ 1,+ )+ for index in range(16):+ angle = math.tau * index / 16+ self.tube(+ identifier + " radial panel seam",+ [+ position(+ (+ radius * fraction * math.cos(angle),+ depth * fraction**2 + 0.021,+ radius * fraction * math.sin(angle),+ )+ )+ for fraction in [i / 20 for i in range(1, 21)]+ ],+ 0.015,+ "ceramic-warm",+ resolution=1,+ )+ self.tube(+ identifier + " rear structural rib",+ [+ position(+ (+ radius * fraction * math.cos(angle),+ depth * fraction**2 - 0.20 - 0.25 * (1 - fraction),+ radius * fraction * math.sin(angle),+ )+ )+ for fraction in [i / 12 for i in range(13)]+ ],+ 0.09,+ "structure",+ resolution=1,+ )+ for fraction in (0.35, 0.72):+ self.tube(+ identifier + " rear circumferential brace",+ [+ position(+ (+ radius * fraction * math.cos(math.tau * i / 64),+ depth * fraction**2 - 0.28,+ radius * fraction * math.sin(math.tau * i / 64),+ )+ )+ for i in range(64)+ ],+ 0.13,+ "metal",+ True,+ 1,+ )+ focus = position((0, radius**2 / (4 * depth), 0))+ for index in range(3):+ angle = math.tau * index / 3+ rim = position(+ (radius * 0.87 * math.cos(angle), depth * 0.87**2, radius * 0.87 * math.sin(angle))+ )+ self.beam(identifier + " feed support strut", rim, focus, 0.075, "structure", 10)+ self.beam(+ identifier + " receiver horn",+ add(focus, scale(direction, -0.55)),+ add(focus, scale(direction, 0.22)),+ 0.26,+ "gold",+ 16,+ )+ for sign in (-1, 1):+ lower = add(center, (sign * 2.1, 7.5, 0))+ upper = position((sign * 2.9, -0.48, 0))+ self.beam(identifier + " elevation yoke", lower, upper, 0.46, "structure", 8)+ self.beam(+ identifier + " hydraulic actuator",+ add(center, (sign * 1.3, 5.2, -0.8)),+ position((sign * 2, -0.6, -radius * 0.5)),+ 0.16,+ "metal",+ 12,+ )+ for index in range(6):+ angle = math.tau * index / 6+ side = (math.sin(angle), 0, math.cos(angle))+ panel = add(center, add(scale(side, radius * 0.58), (0, 1.9, 0)))+ self.box(+ identifier + " radial service panel", panel, (2.1, 2.35, 0.2), "ceramic", 0.1, angle+ )+ self.collider(+ identifier + " base", add(center, (0, 4.5, 0)), (radius * 1.3, 9, radius * 1.3)+ )+ self.anchor(+ identifier + " mechanism", origin, kind="exterior-equipment", access="not-accessible"+ )++ def radome(self, identifier, radius, total_height):+ self.group("06 " + identifier)+ center = self.layout["buildings"][identifier]["local"]+ drum_height = total_height - radius+ self.cylinder(+ identifier + " slab",+ add(center, (0, 0.2, 0)),+ radius + 0.75,+ 0.4,+ "concrete",+ vertices=72,+ )+ self.cylinder(+ identifier + " support drum",+ add(center, (0, drum_height / 2, 0)),+ radius,+ drum_height,+ "ceramic-warm",+ vertices=48,+ )+ self.ring(+ identifier + " dark weather seal",+ add(center, (0, drum_height, 0)),+ radius,+ 0.13,+ "rubber",+ )+ vertices = [add(center, (0, total_height, 0))]+ faces = []+ rings, segments = 12, 48+ for ring in range(1, rings + 1):+ phi = ring / rings * math.pi / 2+ for index in range(segments):+ angle = math.tau * index / segments+ vertices.append(+ add(+ center,+ (+ radius * math.sin(phi) * math.cos(angle),+ drum_height + radius * math.cos(phi),+ radius * math.sin(phi) * math.sin(angle),+ ),+ )+ )+ for index in range(segments):+ faces.append((0, 1 + (index + 1) % segments, 1 + index))+ for ring in range(rings - 1):+ for index in range(segments):+ following = (index + 1) % segments+ a, b = 1 + ring * segments + index, 1 + ring * segments + following+ faces.extend(((a, b, a + segments), (b, b + segments, a + segments)))+ self.mesh(identifier + " double-sided RF shell", vertices, faces, "ceramic", True)+ # Thin raised triangular seams convey assembled RF panels at all angles.+ for ring in range(2, rings + 1, 2):+ phi = ring / rings * math.pi / 2+ r, y = radius * math.sin(phi) + 0.012, drum_height + radius * math.cos(phi)+ self.ring(+ identifier + " latitudinal panel seal",+ add(center, (0, y, 0)),+ r,+ 0.027,+ "ceramic-warm",+ 48,+ )+ for index in range(16):+ angle = math.tau * index / 16+ points = []+ for ring in range(1, rings + 1):+ phi = ring / rings * math.pi / 2+ offset = 0.055 * (ring % 2)+ points.append(+ add(+ center,+ (+ (radius + 0.015) * math.sin(phi) * math.cos(angle + offset),+ drum_height + (radius + 0.015) * math.cos(phi),+ (radius + 0.015) * math.sin(phi) * math.sin(angle + offset),+ ),+ )+ )+ self.tube(+ identifier + " meridian panel seal", points, 0.028, "ceramic-warm", resolution=1+ )+ for index in range(12):+ angle = math.tau * index / 12+ x, z = radius * math.sin(angle), radius * math.cos(angle)+ self.box(+ identifier + " base pilaster",+ add(center, (x, drum_height / 2, z)),+ (0.36, drum_height - 0.3, 0.4),+ "metal",+ 0.035,+ angle,+ )+ if index % 3 == 0:+ self.box(+ identifier + " service status light",+ add(center, (x * 1.025, drum_height - 1.3, z * 1.025)),+ (0.7, 0.16, 0.16),+ "warm-light",+ 0.02,+ angle,+ )+ self.box(+ identifier + " sealed maintenance door",+ add(center, (0, 1.6, radius + 0.05)),+ (2.5, 3.1, 0.18),+ "structure",+ 0.1,+ )+ self.collider(+ identifier,+ add(center, (0, total_height / 2, 0)),+ (radius * 2, total_height, radius * 2),+ )++ def operations(self):+ self.group("07 Operations shell and working interior")+ building = self.layout["buildings"]["operations"]+ center, size = building["local"], building["size"]+ x, y, z = center+ width, height, depth = size+ self.box(+ "Operations load-bearing floor",+ add(center, (0, -0.24, 0)),+ (width, 0.40, depth),+ "concrete",+ 0.06,+ )+ self.box(+ "Interior finished floor",+ add(center, (0, -0.018, 0)),+ (width - 0.8, 0.036, depth - 0.8),+ "paving",+ 0,+ )+ for name, wall_center, wall_size in operations_walls(center, size):+ self.collider("operations-" + name, wall_center, wall_size)+ if name.startswith("south-"):+ self.box(+ "Operations " + name + " sill",+ (wall_center[0], y + 0.48, wall_center[2]),+ (wall_size[0], 0.96, wall_size[2]),+ "ceramic",+ 0.045,+ )+ self.box(+ "Operations " + name + " clerestory",+ (wall_center[0], y + 2.15, wall_center[2]),+ (wall_size[0], 2.25, 0.12),+ "glass",+ 0.02,+ )+ self.box(+ "Operations " + name + " upper wall",+ (wall_center[0], y + 5.65, wall_center[2]),+ (wall_size[0], 4.7, wall_size[2]),+ "ceramic",+ 0.045,+ )+ for offset in (-0.3, 0, 0.3):+ self.box(+ "Operations glazing mullion",+ (wall_center[0] + wall_size[0] * offset, y + 2.15, wall_center[2] + 0.04),+ (0.085, 2.34, 0.2),+ "metal",+ 0.015,+ )+ else:+ self.box(+ "Operations " + name,+ wall_center,+ wall_size,+ "structure" if name.startswith("jamb") else "ceramic",+ 0.07 if name.startswith("jamb") else 0.045,+ )+ self.box("Open door head", (x, y + 3.15, z + depth / 2), (3, 0.3, 0.6), "structure", 0.05)+ for sign in (-1, 1):+ self.box(+ "Door parked in open position",+ (x + sign * 2.35, y + 1.5, z + depth / 2 + 0.27),+ (1.4, 2.95, 0.12),+ "metal",+ 0.07,+ )+ self.box(+ "Door amber hazard strip",+ (x + sign * 1.48, y + 1.4, z + depth / 2 + 0.32),+ (0.1, 2.6, 0.018),+ "ochre",+ 0.008,+ )+ self.box(+ "Operations roof structure",+ (x, y + 7.75, z),+ (width + 0.4, 0.5, depth + 0.4),+ "painted-alloy",+ 0.16,+ )+ self.box(+ "Operations roof ceramic cap",+ (x, y + 8, z),+ (width - 0.2, 0.12, depth - 0.2),+ "roof-alloy",+ 0.08,+ )+ self.collider("operations-roof", (x, y + 7.8, z), (width, 0.4, depth))+ self.box(+ "Entrance canopy", (x, y + 3.65, z + depth / 2 + 0.95), (5, 0.24, 2.3), "ceramic", 0.10+ )+ self.box(+ "Entrance light",+ (x, y + 3.51, z + depth / 2 + 0.8),+ (3.9, 0.035, 0.12),+ "warm-light",+ 0.012,+ )+ self.text(+ "Operations wayfinding",+ "OPERATIONS",+ (x, y + 5.05, z + depth / 2 + 0.04),+ 0.73,+ "structure",+ )+ self.text(+ "Station number", "COMMS 01", (x, y + 4.13, z + depth / 2 + 0.04), 0.3, "structure"+ )+ for dx in (-8.5, 8.5):+ self.box(+ "Front weather-protected service recess",+ (x + dx, y + 5.6, z + depth / 2 + 0.1),+ (1, 2.2, 0.16),+ "structure",+ 0.08,+ )+ for dy in (5.1, 5.45, 5.8, 6.15):+ self.box(+ "Recess louver",+ (x + dx, y + dy, z + depth / 2 + 0.23),+ (0.78, 0.065, 0.1),+ "metal",+ 0.01,+ )+ self.roof_plant("Operations", center, width, depth, y + 8.06)+ for sign in (-1, 1):+ for panel_index in range(4):+ panel_z = z - 4.8 + panel_index * 3.2+ side_x = x + sign * (width / 2 - 0.10)+ self.box(+ "Operations side service cassette gasket",+ (side_x, y + 3.7, panel_z),+ (0.19, 5.7, 2.86),+ "rubber",+ 0.07,+ )+ self.box(+ "Operations side alloy service cassette",+ (side_x + sign * 0.04, y + 3.7, panel_z),+ (0.16, 5.42, 2.6),+ "ceramic-warm" if panel_index % 2 else "ceramic",+ 0.07,+ )+ self.box(+ "Cassette flush fastener strip",+ (side_x + sign * 0.13, y + 5.7, panel_z),+ (0.05, 0.10, 2.22),+ "metal",+ 0.008,+ )+ self.box(+ "Operations plinth dust rail",+ (x + sign * (width / 2 - 0.06), y + 0.27, z),+ (0.24, 0.45, depth - 0.35),+ "dust-coated",+ 0.05,+ )+ for dx in (-5.8, 5.8):+ self.box(+ "Recessed entry access panel gasket",+ (x + dx, y + 5.5, z + depth / 2 + 0.015),+ (3.6, 2.85, 0.05),+ "rubber",+ 0.09,+ )+ self.box(+ "Recessed entry access panel",+ (x + dx, y + 5.5, z + depth / 2 + 0.045),+ (3.34, 2.58, 0.04),+ "ceramic-warm",+ 0.07,+ )+ for sign in (-1, 1):+ self.box(+ "Airlock frame outer reveal",+ (x + sign * 1.73, y + 1.6, z + depth / 2 + 0.32),+ (0.18, 3.2, 0.30),+ "ceramic-warm",+ 0.05,+ )+ self.box(+ "Airlock jamb recessed gasket",+ (x + sign * 1.34, y + 1.46, z + depth / 2 + 0.33),+ (0.18, 2.92, 0.035),+ "rubber",+ 0.02,+ )+ # Functional desk is north of the canonical player/agent anchor, never on it.+ desk = (x, y + 0.87, z - 2.9)+ self.box("Communications desk worktop", desk, (5.4, 0.15, 1.5), "ceramic-warm", 0.12)+ for dx in (-2.1, 2.1):+ self.box(+ "Desk pedestal", (x + dx, y + 0.42, z - 2.9), (0.6, 0.84, 1.1), "structure", 0.1+ )+ self.box(+ "Communications workstation display housing",+ (x, y + 1.65, z - 3.34),+ (4.9, 1.45, 0.20),+ "structure",+ 0.12,+ )+ self.box(+ "Blank authoritative display surface",+ (x, y + 1.65, z - 3.22),+ (4.5, 1.15, 0.035),+ "screen",+ 0.03,+ )+ self.box(+ "Desk keyboard inset", (x, y + 0.96, z - 2.60), (1.9, 0.045, 0.45), "rubber", 0.035+ )+ self.collider("console-desk", (x, y + 0.85, z - 2.9), (5.4, 1.7, 1.5))+ for dx in (-7.3, 7.3):+ self.box(+ "Interior equipment rack",+ (x + dx, y + 1.35, z - 4.8),+ (1.8, 2.7, 1.3),+ "structure",+ 0.12,+ )+ self.collider("equipment-rack-" + str(dx), (x + dx, y + 1.35, z - 4.8), (1.8, 2.7, 1.3))+ for level in range(5):+ self.box(+ "Rack service drawer",+ (x + dx, y + 0.35 + level * 0.48, z - 4.12),+ (1.55, 0.37, 0.07),+ "metal",+ 0.025,+ )+ for dx in (-5, 5):+ self.box(+ "Interior ceiling light",+ (x + dx, y + 7.48, z),+ (0.45, 0.05, 8),+ "warm-light",+ 0.015,+ )+ self.anchor(+ "communications-console",+ center,+ kind="station",+ station_id="communications-console",+ backend_authoritative=True,+ )+ self.anchor(+ "console-display",+ (x, y + 1.65, z - 3.19),+ kind="display",+ station_id="communications-console",+ )+ self.anchor(+ "operations-door",+ (x, y, z + depth / 2),+ kind="door",+ clear_width=2.4,+ clear_height=3.0,+ state="open",+ )+ self.anchor(+ "operations-brand-slot",+ (x + 5.8, y + 5.7, z + depth / 2 + 0.2),+ kind="branding-slot",+ verified_source=False,+ )++ def service(self):+ self.group("08 Power and service structures")+ center = self.layout["buildings"]["service-east"]["local"]+ x, _, z = center+ self.box("Service tower foundation", (x, 0.15, z), (12, 0.3, 12), "concrete", 0.15)+ self.box("Service tower shell", (x, 5.7, z), (11, 11.4, 11), "ceramic-warm", 0.45)+ self.box("Service tower roof", (x, 11.6, z), (11.5, 0.4, 11.5), "roof-alloy", 0.2)+ self.roof_plant("Service tower", center, 11.5, 11.5, 11.82)+ for sign in (-1, 1):+ self.box(+ "Service tower vertical spine",+ (x + sign * 4.6, 5.8, z + 5.55),+ (0.65, 10.8, 0.35),+ "structure",+ 0.1,+ )+ for height in (3.0, 6.0, 9.0):+ self.box(+ "Service tower service panel",+ (x + sign * 2.1, height, z + 5.55),+ (2.1, 2.1, 0.22),+ "ceramic",+ 0.12,+ )+ self.box(+ "Service panel inspection slit",+ (x + sign * 2.1, height + 0.4, z + 5.68),+ (0.6, 0.12, 0.06),+ "warm-light",+ 0.01,+ )+ self.collider("service-east", (x, 6, z), (12, 12, 12))+ for index, (px, pz) in enumerate([(3, -24), (14, -24), (13, 20)]):+ self.box(+ f"Service module {index} plinth", (px, 0.15, pz), (8, 0.3, 7), "concrete", 0.12+ )+ self.box(+ f"Service module {index} shell",+ (px, 2.4, pz),+ (7.4, 4.5, 6.4),+ "ceramic-warm",+ 0.32,+ )+ self.box(+ f"Service module {index} roof", (px, 4.8, pz), (7.7, 0.35, 6.7), "roof-alloy", 0.12+ )+ self.box(+ f"Service module {index} sealed door",+ (px, 1.6, pz + 3.25),+ (2.1, 3.1, 0.15),+ "structure",+ 0.1,+ )+ self.box(+ f"Service module {index} vent",+ (px + 2.4, 3, pz + 3.3),+ (1.2, 1.2, 0.2),+ "metal",+ 0.04,+ )+ self.roof_plant(f"Service module {index}", (px, 0, pz), 7.7, 6.7, 4.98)+ for sign in (-1, 1):+ self.box(+ "Module insulated corner reveal",+ (px + sign * 3.52, 2.5, pz + 3.08),+ (0.24, 4.1, 0.28),+ "painted-alloy",+ 0.06,+ )+ self.box(+ "Module lower dust flashing",+ (px + sign * 3.68, 0.6, pz),+ (0.16, 0.48, 6.25),+ "dust-coated",+ 0.03,+ )+ for offset in (-0.72, -0.36, 0, 0.36, 0.72):+ self.box(+ "Module vent horizontal blade",+ (px + 2.4, 3 + offset * 0.6, pz + 3.42),+ (1.06, 0.07, 0.16),+ "painted-alloy",+ 0.02,+ )+ self.collider(f"service-module-{index}", (px, 2.5, pz), (8, 5, 7))+ for x, z in [(-7, -25), (23, -9), (18, 23)]:+ self.cylinder("Auxiliary mast footing", (x, 0.4, z), 0.85, 0.8, "concrete", vertices=16)+ self.cylinder(+ "Auxiliary aerial mast", (x, 6.1, z), 0.17, 11.4, "metal", top=0.07, vertices=12+ )+ for height in (3, 7.5):+ self.box(+ "Auxiliary aerial panel",+ (x + 0.26, height, z),+ (0.20, 1.65, 0.36),+ "ceramic",+ 0.035,+ )+ self.cylinder("Auxiliary blue beacon", (x, 11.9, z), 0.13, 0.25, "blue", vertices=16)+ # Deliberate utility runs along the north service corridor, behind doors.+ for index in range(3):+ self.tube(+ "North utility distribution pipe",+ [+ (-10, 0.6 + index * 0.28, -18),+ (-10, 0.6 + index * 0.28, -19.5),+ (23, 0.6 + index * 0.28, -19.5),+ (25, 0.6 + index * 0.28, -16),+ ],+ 0.09,+ "metal",+ resolution=2,+ )+ for x in (-8, -2, 4, 10, 16, 22):+ self.box("Utility support saddle", (x, 0.42, -19.5), (0.22, 0.84, 1), "structure", 0.04)++ def signage(self):+ self.group("09 Wayfinding and blank branding slots")+ self.box("Outpost name sign structure", (27, 2.0, 35), (25, 3.5, 0.45), "structure", 0.18)+ self.text(+ "Outpost identification", "COMMUNICATIONS OUTPOST", (27, 2.25, 35.26), 0.95, "ceramic"+ )+ self.text(+ "District wayfinding",+ "EASTERN DISTRICT / OPERATIONS",+ (27, 1.25, 35.26),+ 0.36,+ "ceramic-warm",+ )+ for x in (17, 37):+ self.box("Name sign stanchion", (x, 0.8, 35), (0.6, 1.6, 0.7), "metal", 0.06)+ self.collider("district-sign", (27, 2, 35), (25, 3.5, 0.5))+ self.box("Reserved brand plate", (10, 1.6, 35), (3, 2.8, 0.3), "ceramic-warm", 0.12)+ self.anchor(+ "district-brand-slot", (10, 1.6, 35.2), kind="branding-slot", verified_source=False+ )++ def export_batches(self):+ bpy = self.bpy+ depsgraph = bpy.context.evaluated_depsgraph_get()+ batches = defaultdict(+ lambda: {"vertices": [], "faces": [], "smooth": [], "uvs": [], "colors": []}+ )+ source_count = 0+ for obj in list(self.source.all_objects):+ if obj.type not in {"MESH", "CURVE", "FONT"}:+ continue+ evaluated = obj.evaluated_get(depsgraph)+ mesh = evaluated.to_mesh()+ if mesh is None:+ continue+ source_count += 1+ try:+ matrix = obj.matrix_world+ normal_matrix = matrix.to_3x3().inverted().transposed()+ transformed = [tuple(matrix @ vertex.co) for vertex in mesh.vertices]+ # Split by material with compact vertex remapping per source object.+ for material_index in {polygon.material_index for polygon in mesh.polygons}:+ material = (+ mesh.materials[material_index]+ if len(mesh.materials) > material_index+ else obj.data.materials[0]+ )+ batch = batches[material.name]+ family = self.material_families.get(material.name)+ tile_metres = SURFACE_PROFILES[family]["tile_metres"] if family else 1+ base = material.diffuse_color[:3]+ part_tint = 0.96 + 0.07 * (+ math.sin(sum(map(ord, obj.name)) * 0.713) * 0.5 + 0.5+ )+ remap = {}+ for polygon in mesh.polygons:+ if polygon.material_index != material_index:+ continue+ face = []+ uvs, colors = [], []+ normal = normal_matrix @ polygon.normal+ dominant = max(range(3), key=lambda axis: abs(normal[axis]))+ axes = ((1, 2), (0, 2), (0, 1))[dominant]+ for old in polygon.vertices:+ if old not in remap:+ remap[old] = len(batch["vertices"])+ batch["vertices"].append(transformed[old])+ face.append(remap[old])+ point = transformed[old]+ uvs.append((point[axes[0]] / tile_metres, point[axes[1]] / tile_metres))+ dust = 0+ if family in {"paint", "metal"}:+ dust = min(0.16, max(0, 1.2 - point[2]) * 0.085)+ if normal.z > 0.7:+ dust += 0.035+ tint = [+ min(+ 1,+ max(+ 0,+ base[i] * part_tint * (1 - dust)+ + (0.34, 0.22, 0.13)[i] * dust,+ ),+ )+ for i in range(3)+ ]+ colors.append((*tint, 1))+ batch["faces"].append(face)+ batch["smooth"].append(polygon.use_smooth)+ batch["uvs"].append(uvs)+ batch["colors"].append(colors)+ finally:+ evaluated.to_mesh_clear()+ triangles = 0+ for name, batch in sorted(batches.items()):+ mesh = bpy.data.meshes.new("Batched " + name)+ mesh.from_pydata(batch["vertices"], [], batch["faces"])+ mesh.materials.append(self.materials[name])+ mesh.uv_layers.new(name="Surface metres")+ if name in self.material_families:+ mesh.color_attributes.new(name="Surface tint", type="FLOAT_COLOR", domain="CORNER")+ # Creating another custom-data layer invalidates retained Blender RNA+ # handles. Reacquire both after allocation or UV writes corrupt colors.+ uv = mesh.uv_layers["Surface metres"]+ color = mesh.color_attributes.get("Surface tint")+ for polygon, smooth, uvs, colors in zip(+ mesh.polygons, batch["smooth"], batch["uvs"], batch["colors"], strict=True+ ):+ polygon.use_smooth = smooth+ for index, loop in enumerate(polygon.loop_indices):+ uv.data[loop].uv = uvs[index]+ if color is not None:+ color.data[loop].color = colors[index]+ for polygon, uvs in zip(mesh.polygons, batch["uvs"], strict=True):+ for index, loop in enumerate(polygon.loop_indices):+ actual = mesh.uv_layers["Surface metres"].data[loop].uv+ if any(abs(actual[axis] - uvs[index][axis]) > 0.0001 for axis in range(2)):+ raise ValueError(f"UV data was overwritten in {name}")+ if color is not None:+ for value in mesh.color_attributes["Surface tint"].data:+ if not all(math.isfinite(c) and 0 <= c <= 1 for c in value.color):+ raise ValueError(f"linear color data was overwritten in {name}")+ mesh.update()+ mesh.calc_loop_triangles()+ triangles += len(mesh.loop_triangles)+ obj = bpy.data.objects.new("Outpost / " + name, mesh)+ self.export.objects.link(obj)+ obj["asset_id"], obj["material_batch"] = ASSET_ID, name+ obj["role"] = "visual"+ for record in [*self.colliders, *self.anchors]:+ obj = bpy.data.objects.new(record["id"], None)+ obj.empty_display_type = "CUBE" if "shape" in record else "ARROWS"+ obj.empty_display_size = 0.35+ obj.location = blender_point(+ record.get("center", record.get("position", record.get("start", (0, 0, 0))))+ )+ obj["mars_kind"] = "collider" if "shape" in record else "anchor"+ obj["mars_contract"] = json.dumps(record, sort_keys=True)+ self.export.objects.link(obj)+ self.source.hide_viewport = True+ self.source.hide_render = True+ return {+ "source_objects": source_count,+ "export_meshes": len(batches),+ "triangles": triangles,+ }++ def build(self):+ self.terrain()+ self.paths()+ self.bridge()+ self.tower()+ self.reflector("dish-west", 10.1, 2.5, 14.8, (-0.45, 0.75, 0.50))+ self.reflector("dish-east", 12.0, 3.1, 18.2, (0.50, 0.80, 0.25))+ self.radome("radome-north", 8.5, 17)+ self.radome("radome-south", 10.2, 18)+ self.operations()+ self.service()+ self.signage()+ return self.export_batches()+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument(+ "--definition", type=Path, default=ROOT / "jarvis/society/mars/definition.json"+ )+ parser.add_argument("--study", type=Path, default=STUDY)+ parser.add_argument("--validate-export", type=Path)+ parser.add_argument("--sanitize-source", action="store_true")+ parser.add_argument("--validate-source", action="store_true")+ args = parser.parse_args(sys.argv[sys.argv.index("--") + 1 :] if "--" in sys.argv else [])+ if args.validate_export is not None:+ print(+ json.dumps(+ validate_glb_material_attributes(args.validate_export.read_bytes()), indent=2+ )+ )+ return+ study = args.study.resolve()+ if not study.is_relative_to((ROOT / "art/studies").resolve()):+ raise ValueError("authored sources must stay in this repository's isolated studies")+ manifest_path = study / "study.json"+ manifest = json.loads(manifest_path.read_text(encoding="utf-8"))+ if manifest["approval"]["status"] != "pending" and not args.validate_source:+ raise ValueError("do not overwrite an approved reference with an unreviewed rebuild")+ if args.sanitize_source or args.validate_source:+ import bpy++ source_path = study / "source/communications-outpost.blend"+ bpy.ops.wm.open_mainfile(filepath=str(source_path), load_ui=True, use_scripts=False)+ if args.sanitize_source:+ metadata = sanitize_source_metadata(bpy)+ bpy.context.preferences.filepaths.save_version = 0+ bpy.ops.wm.save_as_mainfile(+ filepath=str(source_path),+ check_existing=False,+ relative_remap=False,+ compress=False,+ )+ contract_path = study / "source/geometry-contract.json"+ contract = json.loads(contract_path.read_text(encoding="utf-8"))+ contract.update(+ source_sha256=hashlib.sha256(source_path.read_bytes()).hexdigest(),+ source_bytes=source_path.stat().st_size,+ source_metadata_validation=metadata,+ )+ contract_path.write_text(+ json.dumps(contract, indent=2) + "\n", encoding="utf-8", newline="\n"+ )+ else:+ metadata = validate_source_path_records(source_path_records(bpy))+ triangles, meshes = 0, 0+ for obj in bpy.data.collections["Export"].all_objects:+ if obj.type == "MESH":+ obj.data.calc_loop_triangles()+ triangles += len(obj.data.loop_triangles)+ meshes += 1+ print(json.dumps({**metadata, "export_meshes": meshes, "triangles": triangles}, indent=2))+ return+ layout = canonical_layout(args.definition)+ author = Author(layout, study)+ report = author.build()+ if report["triangles"] > TRIANGLE_TARGET:+ raise ValueError(f"reference triangle target exceeded: {report['triangles']}")+ source_path = study / "source/communications-outpost.blend"+ source_path.parent.mkdir(parents=True, exist_ok=True)+ author.bpy.context.scene.unit_settings.system = "METRIC"+ author.bpy.context.scene.unit_settings.scale_length = 1+ author.bpy.context.scene["runtime_origin"] = list(layout["origin"])+ author.bpy.context.scene["layout_version"] = layout["layout_version"]+ author.bpy.context.scene["seed"] = layout["seed"]+ author.bpy.context.preferences.filepaths.save_version = 0+ source_metadata = sanitize_source_metadata(author.bpy)+ author.bpy.ops.wm.save_as_mainfile(+ filepath=str(source_path), check_existing=False, relative_remap=False, compress=False+ )+ operations = layout["buildings"]["operations"]+ floor_bounds = [+ [operations["local"][axis] + sign * (operations["size"][axis] / 2 - 0.4) for axis in (0, 2)]+ for sign in (-1, 1)+ ]+ report.update(+ {+ "asset_id": ASSET_ID,+ "stage": "authored-reference-unreviewed",+ "blender_version": author.bpy.app.version_string,+ "seed": layout["seed"],+ "layout_version": layout["layout_version"],+ "definition_sha256": layout["definition_sha256"],+ "world_translation": layout["origin"],+ "source_axes": "Blender Z-up; runtime (x,y,z) maps to Blender (x,-z,y)",+ "export_axes": "Runtime Y-up via glTF exporter export_yup=True",+ "triangle_target": TRIANGLE_TARGET,+ "source_bytes": source_path.stat().st_size,+ "source_sha256": hashlib.sha256(source_path.read_bytes()).hexdigest(),+ "source_metadata_validation": source_metadata,+ "material_profiles": SURFACE_PROFILES,+ "walk_surfaces": {+ "coordinates": "asset-local runtime Y-up metres",+ "route-01": {"surface": "bridge", "node_height_offset": 0},+ "route-02": {"surface": "road", "node_height_offset": 0.006},+ "route-03": {"surface": "footpath", "node_height_offset": 0.006},+ "route-04": {+ "surface": "operations-entry",+ "approach_surface": "terrace",+ "interior_surface": "operations",+ },+ "route-05": {"surface": "road", "node_height_offset": 0.006},+ "perimeter": {"top_y": 0.006},+ "terrace": {+ "top_y": -0.03,+ "footprint": [[x, z] for x, _, z in author.rounded_perimeter(-0.03)],+ },+ "operations": {+ "structural_slab_top_y": -0.04,+ "finished_floor_top_y": 0,+ "finished_floor_xz_bounds": floor_bounds,+ "south_door_threshold_z": operations["local"][2] + operations["size"][2] / 2,+ "approach_terrace_top_y": -0.03,+ },+ },+ "colliders": author.colliders,+ "anchors": author.anchors,+ "runtime_evidence": [],+ "limitations": [+ "Runtime appearance, movement and collision integration are not yet verified.",+ "Source includes no character, rover, approved logo or fabricated task activity.",+ "No visual approval or production-catalog promotion is granted.",+ "Material batching reduces object selection granularity; "+ "stable anchors remain separate.",+ "Editable source rebuilds may vary in Blender metadata; "+ "byte identity is not promised.",+ ],+ }+ )+ (study / "source/geometry-contract.json").write_text(+ json.dumps(report, indent=2) + "\n", encoding="utf-8", newline="\n"+ )+ asset = {+ "id": ASSET_ID,+ "kind": "building",+ "source": "source/communications-outpost.blend",+ "collection": "Export",+ "export": "exports/communications-outpost.glb",+ }+ manifest["assets"] = [item for item in manifest["assets"] if item["id"] != ASSET_ID] + [asset]+ manifest_path.write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8", newline="\n")+ print(+ json.dumps(+ {+ key: report[key]+ for key in [+ "asset_id",+ "source_objects",+ "export_meshes",+ "triangles",+ "source_bytes",+ "stage",+ ]+ },+ indent=2,+ )+ )+++if __name__ == "__main__":+ main()diff --git a/scripts/art/capture_companion_shapes.mjs b/scripts/art/capture_companion_shapes.mjsnew file mode 100644index 0000000000..d3b02274f1--- /dev/null+++ b/scripts/art/capture_companion_shapes.mjs@@ -0,0 +1,25 @@+/** Capture the shipping SVG silhouettes as editable Blender authoring input. */+import { createRequire } from "node:module";+import { fileURLToPath } from "node:url";+import path from "node:path";+import fs from "node:fs";++const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");+const frontend = path.join(root, "jarvis/ui/web/frontend");+const require = createRequire(path.join(frontend, "package.json"));+const { build } = require("esbuild");+const result = await build({+ stdin: { contents: `import { createElement } from 'react';+ import { renderToStaticMarkup } from 'react-dom/server';+ import { AgentSymbol } from './src/components/society/AgentSymbol';+ import { COMPANION_SHAPES } from './src/components/society/companion/appearance';+ export default Object.fromEntries(COMPANION_SHAPES.map(shape => [shape, renderToStaticMarkup(createElement(AgentSymbol, { shape, color:'#ffffff', size:128 }))]));`,+ resolveDir: frontend, loader: "tsx" },+ bundle: true, platform: "node", format: "cjs", jsx: "automatic", write: false,+ loader: { ".css": "empty" },+});+const module = { exports: {} };+new Function("require", "module", "exports", result.outputFiles[0].text)(require, module, module.exports);+const output = path.join(root, "art/studies/agent-symbol-companions/source/shapes.json");+fs.writeFileSync(output, JSON.stringify(module.exports.default, null, 2) + "\n");+console.log("Captured seven source silhouettes.");diff --git a/scripts/art/project_mars_collision.py b/scripts/art/project_mars_collision.pynew file mode 100644index 0000000000..5ed983b6aa--- /dev/null+++ b/scripts/art/project_mars_collision.py@@ -0,0 +1,111 @@+"""Project authored Outpost collision/support into the portable Mars definition."""++from __future__ import annotations++import argparse+import hashlib+import json+import math+from pathlib import Path++ROOT = Path(__file__).resolve().parents[2]+CANONICAL = ROOT / "jarvis/society/mars/definition.json"+FRONTEND = ROOT / "jarvis/ui/web/frontend/src/components/society/mars/worldDefinition.json"+SOURCE = ROOT / "art/studies/mars-outpost-reference/source/geometry-contract.json"+++def project_collision(definition: dict, source: dict) -> dict:+ """Keep geometry in world metres; source-relative paths never enter runtime."""+ origin = source["world_translation"]+ boxes, surfaces = [], []+ for collider in source["colliders"]:+ if collider["shape"] == "box":+ center, size = collider["center"], collider["size"]+ boxes.append(+ {+ "id": "outpost:" + collider["id"],+ "min": [center[i] + origin[i] - size[i] / 2 for i in range(3)],+ "max": [center[i] + origin[i] + size[i] / 2 for i in range(3)],+ }+ )+ elif collider["shape"] == "plateau":+ surfaces.append(+ {+ "id": "outpost:plateau",+ "polygon": [[x + origin[0], z + origin[2]] for x, z in collider["footprint"]],+ "plane": [0, 0, origin[1] + collider["top_y"]],+ }+ )+ terrace = source["walk_surfaces"]["terrace"]+ surfaces.append(+ {+ "id": "outpost:terrace",+ "polygon": [[x + origin[0], z + origin[2]] for x, z in terrace["footprint"]],+ "plane": [0, 0, origin[1] + terrace["top_y"]],+ }+ )+ nodes = {row["id"]: row["position"] for row in definition["navigation"]["nodes"]}+ # The split navigation segments share the same authored, continuous road.+ # Runtime support must not acquire cracks at artificial graph boundaries.+ edges = {+ row["id"]: row+ for row in definition["navigation"].get("surface_edges", definition["navigation"]["edges"])+ }+ source_edges = dict(edges)+ for migration in definition["navigation"].get("graph_migrations", []):+ for row in migration["source_descriptor"]["navigation"]["edges"]:+ source_edges.setdefault(row["id"], row)+ for edge_id in ("route-01", "route-02", "route-03", "route-05"):+ edge = source_edges[edge_id]+ start, end = nodes[edge["from"]], nodes[edge["to"]]+ dx, dz = end[0] - start[0], end[2] - start[2]+ distance = math.hypot(dx, dz)+ rx, rz = dz / distance * edge["width"] / 2, -dx / distance * edge["width"] / 2+ slope = (end[1] - start[1]) / distance**2+ a, b = slope * dx, slope * dz+ offset = source["walk_surfaces"][edge_id]["node_height_offset"]+ surfaces.append(+ {+ "id": "outpost:" + edge_id,+ "polygon": [+ [start[0] - rx, start[2] - rz],+ [start[0] + rx, start[2] + rz],+ [end[0] + rx, end[2] + rz],+ [end[0] - rx, end[2] - rz],+ ],+ "plane": [a, b, start[1] + offset - a * start[0] - b * start[2]],+ }+ )+ return {+ "version": 1,+ "source_sha256": hashlib.sha256(+ json.dumps(source, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()+ ).hexdigest(),+ "solid_boxes": boxes,+ "support_surfaces": surfaces,+ }+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument(+ "--check", action="store_true", help="Reject stale projections without writing"+ )+ args = parser.parse_args()+ definition = json.loads(CANONICAL.read_text(encoding="utf-8"))+ projected = project_collision(definition, json.loads(SOURCE.read_text(encoding="utf-8")))+ if args.check:+ if definition["navigation"].get("collision") != projected:+ raise SystemExit("Canonical Mars collision projection is stale")+ if json.loads(FRONTEND.read_text(encoding="utf-8")) != definition:+ raise SystemExit("Frontend Mars definition projection is stale")+ else:+ definition["navigation"]["collision"] = projected+ encoded = json.dumps(definition, indent=2, ensure_ascii=False, allow_nan=False) + "\n"+ CANONICAL.write_text(encoded, encoding="utf-8")+ FRONTEND.write_text(encoded, encoding="utf-8")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/scripts/art/render_gigi_avatar.py b/scripts/art/render_gigi_avatar.pynew file mode 100644index 0000000000..4d740ebb15--- /dev/null+++ b/scripts/art/render_gigi_avatar.py@@ -0,0 +1,26 @@+"""Render the existing Gigi source as the small profile mark, without AI services."""++from pathlib import Path++import bpy+from mathutils import Vector++ROOT = Path(__file__).resolve().parents[2]+source = ROOT / "art/studies/agent-symbol-companions/source/gigi-reference.blend"+bpy.ops.wm.open_mainfile(filepath=str(source), use_scripts=False)+scene = bpy.context.scene+camera = scene.camera+camera.location = (0.17, -1.2, 0.43)+camera.rotation_euler = (+ (Vector((0, 0, 0.205)) - camera.location).to_track_quat("-Z", "Y").to_euler()+)+camera.data.ortho_scale = 0.50+scene.render.engine = "CYCLES"+scene.cycles.samples = 32+scene.render.resolution_x = scene.render.resolution_y = 512+scene.render.resolution_percentage = 100+scene.render.film_transparent = True+scene.render.image_settings.file_format = "PNG"+scene.render.image_settings.color_mode = "RGBA"+scene.render.filepath = str(ROOT / "jarvis/ui/web/frontend/src/assets/gigi-companion-avatar.png")+bpy.ops.render.render(write_still=True)diff --git a/scripts/art/sample_companion_outlines.py b/scripts/art/sample_companion_outlines.pynew file mode 100644index 0000000000..673823c7b7--- /dev/null+++ b/scripts/art/sample_companion_outlines.py@@ -0,0 +1,35 @@+"""Sample the captured local SVG profiles into Blender's retained outline input.++Authoring-only dependency: Playwright with Chromium. No website or API is used.+"""++import json+from pathlib import Path++from playwright.sync_api import sync_playwright++source = Path(__file__).resolve().parents[2] / "art/studies/agent-symbol-companions/source"+shapes = json.loads((source / "shapes.json").read_text(encoding="utf-8"))+with sync_playwright() as playwright:+ browser = playwright.chromium.launch(headless=True)+ page = browser.new_page()+ outlines = {}+ for name, markup in shapes.items():+ page.set_content(markup)+ outline = page.locator("[data-agent-body] > :first-child")+ if outline.count() == 0:+ # Retained authoring captures predate the animated SVG grouping.+ outline = page.locator("svg > :first-child")+ outlines[name] = outline.evaluate(+ """e => {+ const length = e.getTotalLength();+ return Array.from({length:96}, (_,i) => {+ const p = e.getPointAtLength(length*i/96);+ return [Number(p.x.toFixed(5)),Number(p.y.toFixed(5))];+ });+ }"""+ )+ browser.close()+(source / "outlines.json").write_text(+ json.dumps(outlines, separators=(",", ":")) + "\n", encoding="utf-8"+)diff --git a/scripts/sync_mars_definition.py b/scripts/sync_mars_definition.pynew file mode 100644index 0000000000..9b19dda124--- /dev/null+++ b/scripts/sync_mars_definition.py@@ -0,0 +1,31 @@+"""Copy or verify the frontend projection of the packaged canonical Mars layout."""++from __future__ import annotations++import argparse+from pathlib import Path++ROOT = Path(__file__).resolve().parents[1]+SOURCE = ROOT / "jarvis/society/mars/definition.json"+TARGET = ROOT / "jarvis/ui/web/frontend/src/components/society/mars/worldDefinition.json"+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--check", action="store_true")+ args = parser.parse_args()+ source = SOURCE.read_bytes()+ if args.check:+ if not TARGET.is_file() or TARGET.read_bytes() != source:+ print("Mars definition differs; run python scripts/sync_mars_definition.py")+ return 1+ print("Mars definition projection matches")+ return 0+ TARGET.parent.mkdir(parents=True, exist_ok=True)+ TARGET.write_bytes(source)+ print("Updated frontend Mars definition projection")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/scripts/verify_gpt_live.py b/scripts/verify_gpt_live.pyindex a669e3e792..8227a46f48 100644--- a/scripts/verify_gpt_live.py+++ b/scripts/verify_gpt_live.py@@ -191,7 +191,13 @@ def main() -> None:print(encoded)if args.report:args.report.write_text(encoded + "\n", encoding="utf-8")- if result["failed"] or result["tool_calls"] != 1 or not result["verified_result_spoken"]:+ if (+ result["failed"]+ or result["timed_out"]+ or result["tool_calls"] != 1+ or not result["verified_result_spoken"]+ or (args.reconnect and not result["reconnected"])+ ):raise SystemExit(1)diff --git a/tests/contract/fixtures/agent-companion.json b/tests/contract/fixtures/agent-companion.jsonnew file mode 100644index 0000000000..e0d5cce1bf--- /dev/null+++ b/tests/contract/fixtures/agent-companion.json@@ -0,0 +1,19 @@+{+ "valid": [+ {"shape":"circle","color":"#8b5cf6"},+ {"shape":"cloud","color":"#112233","eyes":"lines","enabled":false,"sizeM":0.25,"followDistanceM":2},+ {"shape":"drop","color":"#FFAA00","eyes":"dots","enabled":true,"sizeM":0.8,"followDistanceM":0.5}+ ],+ "invalid": [+ {"shape":"unknown","color":"#123456"},+ {"shape":"circle","color":"url(remote)"},+ {"shape":"circle","color":"#fff"},+ {"shape":"circle","color":"#123456","eyes":"human"},+ {"shape":"circle","color":"#123456","enabled":"false"},+ {"shape":"circle","color":"#123456","sizeM":10},+ {"shape":"circle","color":"#123456","sizeM":0},+ {"shape":"circle","color":"#123456","followDistanceM":-1},+ {"shape":"circle","color":"#123456","followDistanceM":"1"},+ {"shape":"circle","color":"#123456","url":"https://example.org"}+ ]+}diff --git a/tests/contract/test_agent_companion.py b/tests/contract/test_agent_companion.pynew file mode 100644index 0000000000..76ca7b33c9--- /dev/null+++ b/tests/contract/test_agent_companion.py@@ -0,0 +1,81 @@+"""Avatar JSON companion parity, SQLite persistence and headless API round trips."""++import json+from pathlib import Path++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient+from pydantic import ValidationError++from jarvis.society.companion import CompanionAppearance, validate_avatar_companion+from jarvis.society.runtime import SocietyRuntime+from jarvis.ui.web.society_routes import router++CASES = json.loads((Path(__file__).parent / "fixtures/agent-companion.json").read_text())++[email protected]("case", CASES["valid"])+def test_shared_companion_contract_accepts(case):+ assert CompanionAppearance.model_validate(case).shape == case["shape"]++[email protected]("case", CASES["invalid"])+def test_shared_companion_contract_rejects(case):+ with pytest.raises(ValidationError):+ CompanionAppearance.model_validate(case)+++def test_legacy_and_imported_characters_survive_companion_validation():+ old = {+ "contract": 1,+ "base": "rogue",+ "model": "/api/society/figures/custom.glb",+ "parts": {"head": "hat"},+ }+ assert validate_avatar_companion(old) == old+ updated = validate_avatar_companion({**old, "companion": CASES["valid"][0]})+ assert {k: v for k, v in updated.items() if k != "companion"} == old+++def test_fresh_headless_create_edit_reload_without_inference_or_credentials(tmp_path):+ """This visual feature works with no provider key, GPU, microphone or window."""+ avatar = {+ "contract": 1,+ "archetype": "biped",+ "base": "rogue",+ "parts": {},+ "companion": CASES["valid"][0],+ }++ def open_app():+ runtime = SocietyRuntime(tmp_path, seed_starter_team=False)+ app = FastAPI()+ app.include_router(router)+ app.state.society_factory = lambda: runtime+ return app, runtime++ app, runtime = open_app()+ with TestClient(app) as client:+ try:+ response = client.post(+ "/api/society/agents", json={"name": "Companion contract", "avatar": avatar}+ )+ assert response.status_code == 200, response.text+ agent = response.json()["agent"]+ url = f"/api/society/agents/{agent['agent_id']}"+ updated = {**avatar, "companion": CASES["valid"][1]}+ response = client.patch(url, json={"avatar": updated})+ assert response.status_code == 200, response.text+ assert response.json()["agent"]["avatar"]["companion"]["enabled"] is False+ bad = client.patch(url, json={"avatar": {**avatar, "companion": CASES["invalid"][0]}})+ assert bad.status_code == 409+ finally:+ client.portal.call(runtime.close)+ app, runtime = open_app()+ with TestClient(app) as client:+ try:+ restored = client.get(url).json()["agent"]["avatar"]+ assert restored == updated+ finally:+ client.portal.call(runtime.close)diff --git a/tests/contract/test_chat_tool_choices.py b/tests/contract/test_chat_tool_choices.pyindex 49641d9456..11ab9cc8bd 100644--- a/tests/contract/test_chat_tool_choices.py+++ b/tests/contract/test_chat_tool_choices.py@@ -294,6 +294,22 @@ def test_discovery_route_serves_catalog_and_openapi_metadata(tmp_path, monkeypatassert operation["tags"] and operation["summary"] and operation["x-jarvis-readonly"]+async def test_artifact_row_is_bilingual_and_searchable():+ """The Add-menu pin for artifacts is found via DE and EN words."""+ rows = build_catalog(+ {"create_artifact": tool("create_artifact", "Build an ARTIFACT page", "monitor")}+ )+ by_id = {row.id: row for row in rows}+ row = by_id["tool:create_artifact"]+ assert row.brand == "artifact"+ assert "artefakt" in row.label.lower()+ assert "artifact" in row.label.lower()+ found_de, _ = await search_catalog(rows, "artefakt")+ assert [r.id for r in found_de] == ["tool:create_artifact"]+ found_en, _ = await search_catalog(rows, "artifact")+ assert [r.id for r in found_en] == ["tool:create_artifact"]++@pytest.mark.parametrize("card_pin", [False, True])async def test_subscription_turn_receives_browser_selection_only_for_current_turn(tmp_path, monkeypatch, card_pindiff --git a/tests/contract/test_gpt_live.py b/tests/contract/test_gpt_live.pyindex 5f27f8f70b..955f8c14b8 100644--- a/tests/contract/test_gpt_live.py+++ b/tests/contract/test_gpt_live.py@@ -329,7 +329,7 @@ async def test_local_manual_response_does_not_block_receiving_audio(ledger):@pytest.mark.asyncio-async def test_browser_audio_releases_the_native_wake_microphone(monkeypatch):+async def test_browser_audio_keeps_wake_capture_until_the_browser_takes_over(monkeypatch):from jarvis.realtime import factoryfrom jarvis.speech.pipeline import SpeechPipeline, _SessionInputBuffer@@ -346,8 +346,14 @@ async def test_browser_audio_releases_the_native_wake_microphone(monkeypatch):pipeline._claim_wake_capture_for_session = claimmonkeypatch.setattr(factory, "realtime_browser_audio", lambda cfg: True)async with pipeline._capture_first_session_input() as buffer:+ assert not original._closed+ assert buffer is original+ from jarvis.live import startup++ startup.offer("wake-capture", buffer)+ await startup.take("wake-capture", None)assert original._closed- assert buffer.capture is None+ assert original.released.is_set()def test_tool_text_is_redacted_without_corrupting_image_bytes():@@ -536,6 +542,244 @@ async def test_late_transcript_cannot_reopen_tool_execution_after_close(ledger):})assert not session._tools.accepting+++async def test_cancelled_work_stays_cancelled_when_a_new_request_arrives(ledger):+ from jarvis.safety.tool_executor import VOICE_CONFIRM_SENTINEL++ started, release = asyncio.Event(), asyncio.Event()++ class DelayedApprovalGateway(Gateway):+ def __init__(self):+ super().__init__()+ self.cancelled = []++ async def execute(self, name, args, request):+ self.calls.append((name, args, request))+ if len(self.calls) == 1:+ started.set()+ await release.wait()+ assert request.cancel_token.is_cancelled()+ return ToolResult(False, "Approval needed", VOICE_CONFIRM_SENTINEL)+ assert not request.cancel_token.is_cancelled()+ return ToolResult(True, "New request completed")++ async def cancel_pending(self, trace):+ self.cancelled.append(trace)+ return True++ gateway = DelayedApprovalGateway()+ runtime = LiveTools(gateway, ledger, "s", language="en", backend_model="chosen")+ args = {"name": "write-file", "arguments_json": '{"text":"work"}'}+ job = asyncio.create_task(runtime.execute("old", "call_tool", args, 0))+ await started.wait()+ await runtime.cancel_work()+ runtime.revision += 1+ runtime.accept_new_input()+ release.set()+ assert (await job)["status"] == "superseded"+ assert gateway.cancelled == [gateway.calls[0][2].trace_id]+ assert not runtime._pending+ assert (await runtime.execute("new", "call_tool", args, runtime.revision))["success"]++[email protected]("name", ["end_call", "confirm_action", "call_tool"])+async def test_cancelled_generation_cannot_act_after_new_input(ledger, name):+ gateway = Gateway()+ runtime = LiveTools(gateway, ledger, "s", language="en", backend_model="chosen")+ await runtime.cancel_work()+ runtime.revision += 1+ runtime.accept_new_input()+ result = await runtime.execute("stale", name, {}, 0)+ assert result["status"] == "superseded"+ assert not runtime.end_requested+ assert not gateway.calls+++async def test_task_keeps_starting_agent_after_settings_change():+ from jarvis.brain.manager import BrainManager+ from jarvis.core.model_selection import operation_model++ worker = SimpleNamespace(provider="openai-api", model="original", reasoning_effort="medium")+ config = SimpleNamespace(brain=SimpleNamespace(worker=worker))+ started, release = asyncio.Event(), asyncio.Event()++ class Manager(BrainManager):+ def __init__(self):+ self._config = config++ async def _run_task_with_selection(self, **kwargs):+ started.set()+ await release.wait()+ assert self._task_provider_chain("deep") == [("openai", "original")]+ assert self._tool_model_provider() == "openai"+ assert self._tool_model_model("openai") == "original"+ return "done"++ task = asyncio.create_task(Manager().run_task(prompt="A scheduled request"))+ await started.wait()+ worker.provider = "claude-cli"+ worker.model = "replacement"+ release.set()+ assert await task == "done"+ assert operation_model.get() is None++[email protected]("terminal", ["session.started", "error", "session.closed"])+async def test_provider_test_uses_continuous_contract_and_closes_session(monkeypatch, terminal):+ from jarvis.brain.provider_test import _default_realtime_probe+ from jarvis.core import config, registry+ from jarvis.live import recovery++ opened, sent, closed = [], [], []++ class Connection:+ async def receive(self):+ return {"type": terminal, "error": {"message": "private provider body"}}++ async def send(self, event):+ sent.append(event)++ async def close(self):+ closed.append(True)++ class Provider:+ continuous_conversation = True+ credential_candidates = (("test", "TEST"),)++ def __init__(self, *, api_key):+ assert api_key == "synthetic"++ async def open_session(self, start):+ opened.append(start)+ return Connection()++ async def permit():+ return None++ monkeypatch.setattr(registry, "load", lambda *args, **kwargs: Provider)+ monkeypatch.setattr(config, "get_secret_any", lambda *args: "synthetic")+ monkeypatch.setattr(recovery, "connection_permit", permit)+ cfg = SimpleNamespace(live=LiveConfig(configured=True, backend_model="chosen-model"))+ if terminal == "session.started":+ assert await _default_realtime_probe(SimpleNamespace(id="test"), cfg, timeout_s=1) >= 0+ assert sent == [{"type": "session.close"}]+ else:+ with pytest.raises(RuntimeError, match="selected session") as error:+ await _default_realtime_probe(SimpleNamespace(id="test"), cfg, timeout_s=1)+ assert "private provider body" not in str(error.value)+ assert not sent+ assert opened[0].session["delegation"]["responses"]["model"] == "chosen-model"+ assert opened[0].session["store"] is False+ assert opened[0].offer_sdp == ""+ assert closed == [True]+++def test_live_profile_capability_reaches_api_and_frontend(monkeypatch):+ from pathlib import Path+ from typing import get_args, get_type_hints++ from jarvis.ui.web import provider_routes as routes+ from jarvis.ui.web.provider_spec import ProviderSpec, get_spec++ monkeypatch.setattr(routes, "_is_credential_present", lambda *args: False)+ monkeypatch.setattr(routes.cfg_mod, "get_secret", lambda *args, **kwargs: None)+ spec = get_spec("openai-live")+ payload = routes._spec_to_payload(spec, active_brain=None, active_tts=None, active_stt=None)+ assert payload["configuration_surface"] == "live"+ source = Path("jarvis/ui/web/frontend/src/hooks/useProviders.ts").read_text(encoding="utf-8")+ union = " | ".join(+ f'"{value}"' for value in get_args(get_type_hints(ProviderSpec)["configuration_surface"])+ )+ assert f"configuration_surface?: {union};" in source+++def test_browser_audio_does_not_wait_for_a_legacy_desktop_offer(monkeypatch):+ from fastapi import FastAPI+ from fastapi.testclient import TestClient++ from jarvis.realtime import factory+ from jarvis.ui.web import settings_routes++ monkeypatch.setattr(factory, "realtime_browser_audio", lambda cfg: True)+ monkeypatch.setattr(settings_routes, "_realtime_available_provider", lambda cfg: "openai-live")+ monkeypatch.setattr(settings_routes, "_realtime_requires_webrtc_offer", lambda cfg: True)+ monkeypatch.setattr(settings_routes, "_realtime_handshake_budget_s", lambda cfg: 60)++ async def broker_probe(required):+ raise AssertionError("Browser-owned audio creates its offer on demand")++ monkeypatch.setattr(settings_routes, "_realtime_transport_offer_ready", broker_probe)+ app = FastAPI()+ app.include_router(settings_routes.router)+ app.state.config = SimpleNamespace(voice=SimpleNamespace(mode="realtime"))+ response = TestClient(app).get("/api/settings/voice-mode")+ assert response.status_code == 200+ assert response.json()["browser_audio"] is True+ assert response.json()["transport_offer_detail"] is None+++async def test_sdp_keeps_its_terminal_crlf_through_validation_and_broker():+ from jarvis.realtime.offer_broker import (+ RealtimeTransportOfferBroker,+ validate_webrtc_offer_sdp,+ )++ offer = "v=0\r\no=- 123 1 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"+ answer = offer.replace("123", "456")+ assert validate_webrtc_offer_sdp(offer) == offer+ broker = RealtimeTransportOfferBroker()+ registration = await broker.register("roundtrip", offer)+ lease = await broker.acquire(timeout_s=0.1)+ assert lease is not None+ assert lease.offer_sdp == offer+ await lease.answer(answer)+ assert (await registration.wait()).answer_sdp == answer+ await registration.cancel()+++async def test_large_catalog_fits_rtc_and_remains_fully_discoverable(ledger):+ import json++ class LargeGateway(Gateway):+ def catalog(self):+ return tuple(+ SupervisorToolDescriptor(+ f"service/tool_{index:03d}",+ "Description " * 120,+ {"type": "object", "properties": {"text": {"type": "string"}}},+ "safe",+ )+ for index in range(90)+ )++ runtime = LiveTools(LargeGateway(), ledger, "s", language="en", backend_model="chosen")+ assert len(json.dumps(runtime.declarations()).encode()) <= 24_000+ offset, names = 0, []+ while True:+ result = await runtime.execute(+ f"page-{offset}", "discover_tools", {"query": "", "offset": offset}, 0+ )+ assert len(json.dumps(result).encode()) < 25_000+ names.extend(tool["name"] for tool in result["tools"])+ if result["next_offset"] is None:+ break+ assert result["next_offset"] > offset+ offset = result["next_offset"]+ assert names == [tool.name for tool in runtime.catalog()]+ assert len(set(names)) == 90+ result = await runtime.execute(+ "last-tool", "call_tool", {"name": names[-1], "arguments_json": "{}"}, 0+ )+ assert result["success"]++@pytest.mark.asyncioasync def test_live_drives_jarvis_bar_indicators(ledger):"""Thinking while the model works, speaking while it talks — on both transports."""@@ -599,14 +843,15 @@ async def test_live_drives_jarvis_bar_indicators(ledger):"end_ms": 100,})- assert {"type": "tts_start"} in json_frames- assert {"type": "speaking"} in json_frames+ assert {"type": "speaking"} not in json_framesassert binary_frames == []+ assert session.phase == "thinking"+ await session.handle_control({"type": "playback_state", "active": True})+ assert {"type": "speaking"} in json_framesassert session.phase == "speaking"await response_completed(session)- types = [frame["type"] for frame in json_frames]- assert "tts_end" in types- assert "turn_complete" in types+ assert session.phase == "speaking"+ await session.handle_control({"type": "playback_state", "active": False})assert session.phase == "listening"# PCM transport: the same signals plus the forwarded audio itself.@@ -635,6 +880,7 @@ async def test_live_drives_jarvis_bar_indicators(ledger):await session._event({"type": "session.output_audio.delta", "delta": pcm, "start_ms": 0, "end_ms": 10})+ await session.handle_control({"type": "playback_state", "active": True})assert session.phase == "speaking"await session.handle_control({"type": "barge_in"})assert {"type": "tts_cancel"} in json_frames@@ -672,3 +918,38 @@ async def test_live_assistant_transcript_keeps_thinking_visible(ledger):thinking = [frame for frame in json_frames if frame["type"] == "thinking"]assert len(thinking) == 1assert session.phase == "thinking"+++async def test_live_usage_keeps_the_calls_model_after_a_settings_change(ledger):+ async def send(event):+ return None++ cfg = SimpleNamespace(+ brain=SimpleNamespace(reply_language="en"),+ live=LiveConfig(configured=True, backend_model="next-call-model"),+ )+ session = LiveVoiceSession(+ session_id="s",+ send_json=send,+ send_binary=send,+ config=cfg,+ providers=[SimpleNamespace(name="test")],+ )+ session._ledger = ledger+ session._tools = LiveTools(+ Gateway(), ledger, "s", language="en", backend_model="starting-model"+ )+ await session._event(+ {+ "type": "response.event",+ "delegation_id": "d",+ "event": {+ "type": "response.completed",+ "response": {"id": "usage", "usage": {"input_tokens": 3}},+ },+ }+ )+ assert ledger._db.execute("SELECT model FROM live_backend_usage").fetchone() == (+ "starting-model",+ )diff --git a/tests/contract/test_live_conversation.py b/tests/contract/test_live_conversation.pynew file mode 100644index 0000000000..a30913f630--- /dev/null+++ b/tests/contract/test_live_conversation.py@@ -0,0 +1,202 @@+"""Continuous voice survives EventBus, SQLite, API serialization and UI replay."""++import re+from dataclasses import fields+from pathlib import Path+from types import SimpleNamespace+from uuid import uuid4++import pytest+from pydantic import TypeAdapter++from jarvis.core.bus import EventBus+from jarvis.core.events import (+ BrainTurnCompleted,+ BrainTurnStarted,+ Event,+ ReasoningSummaryUpdated,+ VoiceSessionStarted,+ VoiceTranscriptUpdated,+)+from jarvis.live import runtime+from jarvis.live.native import NativeLiveVoiceSession+from jarvis.live.session import LiveVoiceSession+from jarvis.live.state import LiveLedger, TranscriptFragment+from jarvis.live.transcript import LiveTranscript, read_legacy_transcript+from jarvis.sessions.recorder import SessionRecorder+from jarvis.sessions.store import SessionStore+from jarvis.speech.pipeline import PipelineState, SpeechPipeline+from jarvis.ui.web.chats_routes import ChatTurn, _live_voice_messages+++def feed(projector, role, text, start, end, *, snapshot=False):+ return projector.feed(+ session_id="voice",+ trace_id=uuid4(),+ event_id=str(uuid4()),+ role=role,+ text=text,+ start_ms=start,+ end_ms=end,+ snapshot=snapshot,+ )+++def test_fast_followups_and_overlap_keep_distinct_speaker_segments():+ projector = LiveTranscript()+ first = feed(projector, "user", "Hello", 0, 100)+ answer = feed(projector, "assistant", "Hi", 200, 300)+ again = feed(projector, "user", "Hello", 350, 450)+ assert first.segment_id != again.segment_id # Repetition is not duplicate delivery.+ tail = feed(projector, "assistant", " there", 280, 500)+ assert tail.segment_id == answer.segment_id # Overlap continues the existing speech.+ assert tail.text == "Hi there"+ assert tail.revision == 2+ assert again.text == "Hello"+ late = feed(projector, "user", "!", 90, 100)+ assert late.segment_id == first.segment_id+ assert late.text == "Hello!"+ newest = feed(projector, "user", " again", 450, 500)+ assert newest.segment_id == again.segment_id+ assert newest.text == "Hello again"+++def test_pre_fix_fragment_history_is_recoverable_without_rewriting(tmp_path):+ path = tmp_path / "live.db"+ ledger = LiveLedger(path)+ for i, (role, text) in enumerate([("user", "Hello"), ("assistant", "Hi"), ("user", "Hello")]):+ ledger.append(TranscriptFragment("old", str(i), role, text, i * 400, i * 400 + 100))+ ledger.close()+ before = path.read_bytes()+ assert [(row.role, row.text) for row in read_legacy_transcript(path, "old")] == [+ ("user", "Hello"),+ ("assistant", "Hi"),+ ("user", "Hello"),+ ]+ assert path.read_bytes() == before+++def test_running_browser_call_blocks_a_competing_native_start(monkeypatch):+ pipeline = SpeechPipeline.__new__(SpeechPipeline)+ pipeline._state = PipelineState.IDLE+ pipeline._dictation_blocks_activation = lambda: False+ pipeline._capture_permission_allowed = lambda: True+ monkeypatch.setattr(runtime, "_active", {"browser": object()})+ monkeypatch.setattr(runtime, "_opening", set())+ assert not pipeline._activation_allowed()+ # The native parent of this same call is allowed to maintain it.+ pipeline._current_voice_session_id = "browser"+ assert pipeline._activation_allowed()+++ "event_class,interface",+ [+ (VoiceTranscriptUpdated, "VoiceTranscriptSnapshot"),+ (ReasoningSummaryUpdated, "ReasoningSummarySnapshot"),+ ],+)+def test_python_typescript_payload_parity(event_class, interface):+ source = (+ Path(__file__).resolve().parents[2] / "jarvis/ui/web/frontend/src/lib/liveTranscript.ts"+ ).read_text(encoding="utf-8")+ body = source.split(f"export interface {interface} {{", 1)[1].split("}", 1)[0]+ assert set(re.findall(r"^\s+(\w+):", body, re.MULTILINE)) == (+ {f.name for f in fields(event_class)} - {f.name for f in fields(Event)}+ )+ value = event_class()+ adapter = TypeAdapter(event_class)+ assert adapter.validate_json(adapter.dump_json(value)) == value+++async def test_both_live_adapters_publish_every_speaker_to_the_bus(tmp_path):+ bus = EventBus()+ observed = []++ async def record(event):+ observed.append(event)++ async def send(_frame):+ pass++ bus.subscribe(VoiceTranscriptUpdated, record)+ for cls in (LiveVoiceSession, NativeLiveVoiceSession):+ session = cls(+ session_id="voice",+ bus=bus,+ send_json=send,+ send_binary=send,+ providers=[SimpleNamespace(name="test")],+ config=SimpleNamespace(brain=SimpleNamespace(reply_language="en")),+ )+ ledger = LiveLedger(tmp_path / f"{cls.__name__}.db")+ session._ledger = ledger+ session._tools = SimpleNamespace(user_text="", revision=0, accept_new_input=lambda: None)+ try:+ if cls is LiveVoiceSession:+ for i, (role, text) in enumerate(+ [("input", "Hello"), ("output", "Hi"), ("input", "Again")]+ ):+ await session._event(+ {+ "type": f"session.{role}_transcript.delta",+ "delta": text,+ "event_id": str(i),+ "start_ms": i * 400,+ "end_ms": i * 400 + 100,+ }+ )+ else:+ for role, text in [+ ("input_transcript", "Hello"),+ ("output_transcript_delta", "Hi"),+ ("input_transcript", "Again"),+ ]:+ await session._native_event(+ SimpleNamespace(type=role, text=text, is_final=False)+ )+ assert [e.role for e in observed[-3:]] == ["user", "assistant", "user"]+ finally:+ ledger.close()+++async def test_recorded_live_conversation_reopens_as_multiple_messages_with_trace(tmp_path):+ store = SessionStore(tmp_path / "sessions.db")+ store.open()+ bus = EventBus()+ recorder = SessionRecorder(store)+ recorder.attach(bus)+ try:+ await bus.publish(VoiceSessionStarted(session_id="voice", language="en"))+ projector = LiveTranscript()+ await bus.publish(feed(projector, "user", "Read settings", 0, 100))+ await bus.publish(BrainTurnStarted(provider="test", model="thinking"))+ await bus.publish(+ ReasoningSummaryUpdated(+ response_id="reason", text="Checking the selected setting.", done=True+ )+ )+ await bus.publish(BrainTurnCompleted(provider="test", model="thinking"))+ await bus.publish(feed(projector, "assistant", "It is ", 200, 300))+ await bus.publish(feed(projector, "assistant", "enabled.", 300, 400))+ await bus.publish(feed(projector, "user", "Thanks", 500, 600))+ await bus.publish(feed(projector, "assistant", "Welcome", 700, 800))+ rows = store.get_events("voice")+ messages = _live_voice_messages(rows)+ assert [m.role for m in messages] == ["user", "assistant", "user", "assistant"]+ assert [m.text for m in messages] == [+ "Read settings",+ "It is enabled.",+ "Thanks",+ "Welcome",+ ]+ assert any(e["name"] == "ReasoningSummaryUpdated" for e in messages[1].trace["events"])+ assert [ChatTurn.model_validate_json(m.model_dump_json()) for m in messages] == messages+ # Persisted snapshots retain their field contract, not just a text blob.+ caption = next(e.payload for e in rows if e.kind == "VoiceTranscriptUpdated")+ assert caption["session_id"] == "voice"+ assert caption["segment_id"] and caption["revision"] == 1+ finally:+ store.close()diff --git a/tests/contract/test_live_media_feedback.py b/tests/contract/test_live_media_feedback.pynew file mode 100644index 0000000000..47aa8a2769--- /dev/null+++ b/tests/contract/test_live_media_feedback.py@@ -0,0 +1,210 @@+"""Portable media-to-native-bar contract, without a device or provider account."""++import asyncio+import re+from pathlib import Path+from types import SimpleNamespace++import pytest++from jarvis.audio import level_tap, mic_level+from jarvis.core.bus import EventBus+from jarvis.core.events import AudioOutFirst, SystemStateChanged+from jarvis.live.media import MediaLevels+from jarvis.live.native import NativeLiveVoiceSession+from jarvis.live.session import LiveVoiceSession+from tests.fakes.voice_surface import VoiceSurface+from ui.orb.bus_bridge import OrbBusBridge+++def snapshot(*, input_level=0.0, output_level=0.0, input_active=False, playback_active=False):+ return dict(+ type="media_levels",+ input_level=input_level,+ output_level=output_level,+ input_active=input_active,+ playback_active=playback_active,+ )++[email protected](params=[LiveVoiceSession, NativeLiveVoiceSession])+def presentation(request):+ surface = VoiceSurface()+ bus = EventBus()+ frames, events = [], []+ bridge = OrbBusBridge(bus, surface, idle_animations_enabled=False)+ bus.subscribe(SystemStateChanged, bridge._on_state)+ bus.subscribe(AudioOutFirst, bridge._on_audio_out_first)++ async def record(event):+ events.append((type(event).__name__, getattr(event, "new_state", None)))++ async def send(frame):+ frames.append(frame)++ bus.subscribe(SystemStateChanged, record)+ bus.subscribe(AudioOutFirst, record)+ session = request.param(+ session_id="media-test",+ bus=bus,+ send_json=send,+ send_binary=send,+ config=SimpleNamespace(brain=SimpleNamespace(reply_language="en")),+ providers=[SimpleNamespace(name="test")],+ )+ session._connection = object()+ # Amplitude must never visit a ledger or execute a tool.+ session._ledger = object()+ mic_level.reset_for_tests()+ level_tap.reset()+ unsub_mic = mic_level.subscribe(bridge._on_mic_level)+ unsub_output = level_tap.subscribe(bridge._note_tts_level)+ yield session, surface, frames, events+ session._closing = True+ session._clear_media_levels()+ unsub_mic()+ unsub_output()+ level_tap.reset()+ mic_level.reset_for_tests()+++async def test_native_microphone_meter_remains_visible_while_connecting(presentation):+ _session, surface, _frames, _events = presentation+ bus = _session._bus+ await bus.publish(SystemStateChanged(new_state="LISTENING", previous="IDLE"))+ await bus.publish(SystemStateChanged(new_state="CONNECTING", previous="LISTENING"))+ mic_level.publish(0.65)+ assert surface.mode == "listen"+ assert surface.level == pytest.approx(0.65)+++async def test_interim_speech_work_and_reply_reach_the_actual_surface(presentation):+ session, surface, frames, events = presentation+ await session.handle_control(snapshot(input_level=0.61, input_active=True))+ assert surface.mode == "listen"+ assert surface.level == pytest.approx(0.61)+ mic_level.feed(0.0) # An idle native wake detector cannot erase browser levels.+ assert surface.level == pytest.approx(0.61)+ await session.handle_control(snapshot())+ await session._note_thinking()+ session._response_revisions["work"] = 0+ await session.handle_control(snapshot(output_level=0.74, playback_active=True))+ assert surface.mode == "speak" # SPEAKING alone leaves the native bar thinking.+ assert surface.level == pytest.approx(0.74)+ assert events.index(("SystemStateChanged", "SPEAKING")) < events.index(("AudioOutFirst", None))+ await session._note_thinking()+ assert surface.mode == "speak"+ assert frames[-1]["type"] == "speaking"+ await session.handle_control(snapshot())+ assert surface.mode == "think"+ # A correction is visible immediately without cancelling background work.+ await session.handle_control(snapshot(input_level=0.48, input_active=True))+ assert surface.mode == "listen"+ assert surface.level == pytest.approx(0.48)+ await session.handle_control(snapshot())+ assert surface.mode == "think"+ await session.handle_control(snapshot(output_level=0.82, playback_active=True))+ assert surface.mode == "speak"+ assert events.count(("AudioOutFirst", None)) == 2+ await session.handle_control(snapshot(output_level=0.3, playback_active=True))+ assert events.count(("AudioOutFirst", None)) == 2+ session._response_revisions.clear()+ await session.handle_control(snapshot(input_level=0.66, input_active=True))+ assert surface.mode == "listen"+ assert surface.level == pytest.approx(0.66)+++async def test_expired_and_closed_media_cannot_leave_stuck_levels(presentation):+ session, surface, _, _ = presentation+ await session.handle_control(snapshot(output_level=0.7, playback_active=True))+ session._expire_media_levels()+ await asyncio.gather(*tuple(session._control_tasks))+ assert not session.playback_active+ assert surface.level == 0+ assert surface.mode == "listen"+ session._closing = True+ session._clear_media_levels()+ await session.handle_control(snapshot(input_level=0.9, input_active=True))+ assert surface.level == 0+++ "bad",+ [+ {"input_level": float("nan")},+ {"output_level": float("inf")},+ {"input_level": -1},+ {"output_level": 1.1},+ {"playback_active": "true"},+ {"input_active": 1},+ {"input_level": True},+ {"unexpected": "ignored"},+ ],+)+async def test_invalid_measurements_cannot_repaint_the_bar(presentation, bad):+ session, surface, frames, _ = presentation+ await session.handle_control({**snapshot(), **bad})+ assert surface.mode == "idle"+ assert not frames+ assert session._media_timeout is None+++def test_python_typescript_media_fields_stay_in_parity():+ root = Path(__file__).resolve().parents[2]+ source = (root / "jarvis/ui/web/frontend/src/lib/mediaLevels.ts").read_text(encoding="utf-8")+ fields = re.search(r"interface MediaLevels\s*\{([^}]+)\}", source).group(1)+ assert set(re.findall(r"^\s*(\w+):", fields, re.M)) == set(MediaLevels.model_fields)+ assert 'type: "media_levels"' in fields+++async def test_speech_completion_keeps_other_work_visible(presentation):+ session, surface, _, _ = presentation+ await session.handle_control(snapshot())+ work = asyncio.create_task(asyncio.Event().wait())+ session._jobs.add(work)+ try:+ await session._note_turn_end()+ assert surface.mode == "think"+ work.cancel()+ await asyncio.gather(work, return_exceptions=True)+ # A completed job may still be in the set until its done callback runs.+ await session.handle_control(snapshot(output_level=0.6, playback_active=True))+ await session.handle_control(snapshot())+ assert surface.mode == "listen"+ finally:+ work.cancel()+ await asyncio.gather(work, return_exceptions=True)+++async def test_older_loaded_microphone_module_does_not_end_voice(presentation, monkeypatch):+ session, surface, _, _ = presentation+ monkeypatch.delattr(mic_level, "claim_external")+ monkeypatch.delattr(mic_level, "release_external")+ await session.handle_control(snapshot(input_level=0.6, input_active=True))+ assert session.is_active+ assert not session.failed+ await session.handle_control(snapshot(output_level=0.7, playback_active=True))+ assert surface.mode == "speak"+ session._clear_media_levels()+ assert session.is_active+++async def test_meter_sink_failure_is_not_a_session_failure(presentation, monkeypatch):+ session, surface, _, _ = presentation++ def unavailable_meter(owner):+ raise RuntimeError("Synthetic meter failure")++ monkeypatch.setattr(mic_level, "claim_external", unavailable_meter)+ await session.handle_control(snapshot(input_level=0.6, input_active=True))+ assert session.is_active+ assert not session.failed+ await session.handle_control({"type": "playback_state", "active": True})+ assert surface.mode == "speak"diff --git a/tests/contract/test_live_startup_audio.py b/tests/contract/test_live_startup_audio.pynew file mode 100644index 0000000000..2c46adf1d3--- /dev/null+++ b/tests/contract/test_live_startup_audio.py@@ -0,0 +1,89 @@+"""Wake/browser handoff is portable, bounded, ephemeral and consumed once."""++import asyncio+import base64+import re+import time+from array import array+from pathlib import Path++import pytest++from jarvis.core.protocols import AudioChunk+from jarvis.live import startup+from jarvis.live.media import InputPrefix+from jarvis.speech.pipeline import _SessionInputBuffer+++def test_input_prefix_python_typescript_field_parity():+ source = (+ Path(__file__).resolve().parents[2]+ / "jarvis/ui/web/frontend/src/lib/startupAudio.ts"+ ).read_text(encoding="utf-8")+ interface = source.split("export interface InputPrefix {", 1)[1].split("}", 1)[0]+ assert set(re.findall(r"^\s+(\w+):", interface, re.MULTILINE)) == set(InputPrefix.model_fields)+++async def test_prefix_trims_browser_overlap_and_releases_capture_once():+ now = time.time_ns()+ source = _SessionInputBuffer(+ initial=(+ AudioChunk(+ pcm=array("h", range(160)).tobytes(),+ sample_rate=16000,+ timestamp_ns=now,+ ),+ )+ )+ startup.offer("one", source)+ result = await startup.take("one", (now - 5_000_000) / 1_000_000)+ assert result["type"] == "input_prefix"+ assert result["sample_rate"] == 16000+ # Epoch floats have sub-microsecond precision; at most one boundary sample.+ assert 79 <= len(base64.b64decode(result["audio"])) // 2 <= 80+ assert source.released.is_set()+ assert await startup.take("one", now / 1_000_000) is None+++async def test_cancelled_start_cannot_supply_audio_to_a_later_call():+ source = _SessionInputBuffer()+ startup.offer("cancelled", source)+ startup.discard("cancelled")+ assert await startup.take("cancelled", time.time() * 1000) is None+ assert await startup.take("other", time.time() * 1000) is None+ await source.close()++[email protected]("timestamp", [None, float("nan"), 1, True])+async def test_old_or_invalid_capture_releases_the_native_lease(timestamp):+ source = _SessionInputBuffer()+ startup.offer("invalid", source)+ if timestamp is None:+ assert await startup.take("invalid", timestamp) is None+ else:+ with pytest.raises(ValueError):+ await startup.take("invalid", timestamp)+ assert source.released.is_set()+++async def test_cross_thread_handoff_uses_the_capture_owners_event_loop():+ now = time.time_ns()+ source = _SessionInputBuffer(+ initial=(+ AudioChunk(+ pcm=b"\x01\x00" * 160,+ sample_rate=16000,+ timestamp_ns=now,+ ),+ )+ )+ startup.offer("thread", source)+ result = await asyncio.to_thread(+ lambda: asyncio.run(startup.take("thread", now / 1_000_000 + 10))+ )+ assert len(base64.b64decode(result["audio"])) == 320+ assert source.released.is_set()diff --git a/tests/contract/test_live_surface_lifecycle.py b/tests/contract/test_live_surface_lifecycle.pynew file mode 100644index 0000000000..174af7a3d3--- /dev/null+++ b/tests/contract/test_live_surface_lifecycle.py@@ -0,0 +1,135 @@+"""Live media state reaches desktop surfaces and wake ownership cannot linger."""++import asyncio+from types import SimpleNamespace++import pytest++from jarvis.core.bus import EventBus+from jarvis.core.events import BrowserVoiceRequested, SystemStateChanged+from jarvis.live import runtime+from jarvis.live.session import LiveVoiceSession+++async def test_rtp_playback_reaches_native_bar_without_sideband_audio():+ bus = EventBus()+ states = []+ frames = []++ async def changed(event):+ states.append(event.new_state)+ assert event.trace_id == session._indicator_trace_id++ async def send(frame):+ frames.append(frame)++ bus.subscribe(SystemStateChanged, changed)+ session = LiveVoiceSession(+ session_id="live-indicators",+ bus=bus,+ send_json=send,+ send_binary=send,+ config=SimpleNamespace(brain=SimpleNamespace(reply_language="en")),+ providers=[SimpleNamespace(name="test")],+ )+ await session._publish_phase("connecting")+ await session._publish_phase()+ await session._note_thinking()+ session._response_revisions["work"] = 0+ await session.handle_control({"type": "playback_state", "active": True})+ await session.handle_control({"type": "playback_state", "active": True})+ await session.handle_control({"type": "playback_state", "active": False})+ session._response_revisions.clear()+ await session.handle_control({"type": "playback_state", "active": True})+ await session.handle_control({"type": "playback_state", "active": False})+ await session.end()+ await session._publish_phase("listening")+ await session.handle_control({"type": "playback_state", "active": True})+ assert states == [+ "CONNECTING",+ "LISTENING",+ "THINKING",+ "SPEAKING",+ "THINKING",+ "SPEAKING",+ "LISTENING",+ "IDLE",+ ]+ assert {"type": "thinking"} in frames+++async def test_expired_wake_retracts_the_browser_request(monkeypatch):+ monkeypatch.setattr(runtime, "_active", {})+ monkeypatch.setattr(runtime, "_watchers", set())+ requests = []+ bus = EventBus()++ async def requested(event):+ requests.append(event.action)++ bus.subscribe(BrowserVoiceRequested, requested)+ assert await runtime.run_browser_call(bus, asyncio.Event(), timeout_s=0.01) == "error"+ assert requests == ["start", "stop"]+ assert not runtime._watchers+++async def test_cancelled_wake_never_starts_a_late_call(monkeypatch):+ monkeypatch.setattr(runtime, "_active", {})+ monkeypatch.setattr(runtime, "_watchers", set())+ requests = []+ bus = EventBus()+ started = asyncio.Event()++ async def requested(event):+ requests.append(event.action)+ started.set()++ bus.subscribe(BrowserVoiceRequested, requested)+ task = asyncio.create_task(runtime.run_browser_call(bus, asyncio.Event()))+ await started.wait()+ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await task+ assert requests == ["start", "stop"]+ assert not runtime._watchers+++async def test_hangup_before_handoff_does_not_start_browser(monkeypatch):+ monkeypatch.setattr(runtime, "_active", {})+ monkeypatch.setattr(runtime, "_watchers", set())+ requests = []+ bus = EventBus()++ async def requested(event):+ requests.append(event.action)++ bus.subscribe(BrowserVoiceRequested, requested)+ hangup = asyncio.Event()+ hangup.set()+ assert await runtime.run_browser_call(bus, hangup) == "hotkey"+ assert requests == ["stop"]+++async def test_new_input_recovers_after_task_cancellation(tmp_path):+ from jarvis.live.state import LiveLedger+ from jarvis.live.tools import LiveTools++ ledger = LiveLedger(tmp_path / "live.sqlite3")+ try:+ tools = LiveTools(SimpleNamespace(), ledger, "s", language="en", backend_model="chosen")+ old_token = tools.cancel_token+ await tools.cancel_work()+ assert old_token.is_cancelled()+ assert not tools.accepting+ assert tools.revision == 1+ tools.accept_new_input()+ assert tools.accepting+ assert not tools.cancel_token.is_cancelled()+ assert old_token.is_cancelled()+ finally:+ ledger.close()diff --git a/tests/contract/test_live_tool_efficiency.py b/tests/contract/test_live_tool_efficiency.pynew file mode 100644index 0000000000..1ae56a672c--- /dev/null+++ b/tests/contract/test_live_tool_efficiency.py@@ -0,0 +1,161 @@+"""Cost reductions must preserve the selected model and every authorized capability."""++import json++import pytest++from jarvis.brain.cost import calculate_cost_usd+from jarvis.core.protocols import SupervisorToolDescriptor, ToolResult+from jarvis.live.config import LiveConfig+from jarvis.live.cost import backend_cost_usd+from jarvis.live.discovery import discover+from jarvis.live.state import LiveLedger+from jarvis.live.tools import LiveTools+++def descriptor(name, description, *, size=0):+ return SupervisorToolDescriptor(+ name,+ description,+ {+ "type": "object",+ "properties": {"text": {"type": "string", "description": "x" * size}},+ "required": ["text"],+ "additionalProperties": False,+ },+ "monitor",+ )+++class Gateway:+ def __init__(self, tools):+ self.tools = tuple(tools)+ self.calls = []++ def catalog(self):+ return self.tools++ async def execute(self, name, arguments, request):+ self.calls.append((name, arguments, request))+ return ToolResult(True, {"verified": True, "text": arguments["text"]})+++def test_large_catalog_is_deferred_without_model_or_reasoning_downgrade(tmp_path):+ gateway = Gateway(+ descriptor(f"tool_{i:03}", "Available application tool", size=900) for i in range(100)+ )+ ledger = LiveLedger(tmp_path / "live.db")+ try:+ runtime = LiveTools(gateway, ledger, "s", language="en", backend_model="selected")+ eager = runtime.declarations()+ deferred = runtime.declarations(defer_catalog=True)+ assert len(json.dumps(deferred)) < len(json.dumps(eager)) * 0.15+ assert "x" * 900 not in json.dumps(deferred)+ assert all(tool.name in deferred[1]["description"] for tool in gateway.tools)+ assert {tool["name"] for tool in deferred} == {+ "discover_tools",+ "call_tool",+ "confirm_action",+ "end_call",+ }+ config = LiveConfig(configured=True, backend_model="selected", reasoning_effort="high")+ backend = config.session_config(language="en", tools=deferred)["delegation"]["responses"]+ assert backend["model"] == "selected"+ assert backend["reasoning"]["effort"] == "high"+ assert "max_output_tokens" not in backend+ assert {tool["type"] for tool in backend["tools"]} == {"function", "web_search"}+ finally:+ ledger.close()+++def test_sentence_query_finds_available_agent_status_instead_of_empty_results():+ tools = [+ descriptor("agent_status", "Read the status of active agents and their tasks"),+ descriptor("write_file", "Write a file"),+ descriptor("list_files", "List files in a directory"),+ ]+ result = discover(tools, "list Jarvis agents current active agents tasks status")+ assert result["tools"][0]["name"] == "agent_status"+ assert "write_file" not in {tool["name"] for tool in result["tools"]}+++def test_exact_lookup_keeps_full_schema_and_does_not_include_name_mentions():+ requested = descriptor("agent_status", "Read agent status", size=20000)+ result = discover([descriptor("help", "See agent_status"), requested], "agent_status")+ assert result["total"] == 1+ assert result["tools"][0]["parameters"] == requested.input_schema+ assert result["next_offset"] is None+++def test_pagination_keeps_every_tool_reachable_and_stable():+ catalog = [descriptor(f"tool_{i:02}", "Read data", size=6000) for i in range(13)]+ offset, names = 0, []+ while offset is not None:+ result = discover(reversed(catalog), "", offset)+ assert result["tools"]+ names.extend(tool["name"] for tool in result["tools"])+ offset = result["next_offset"]+ assert names == [tool.name for tool in catalog]+ assert discover(catalog, "", 999)["next_offset"] is None+++def test_empty_search_explains_how_to_recover_without_inventing_tools():+ result = discover([descriptor("write_file", "Write data")], "nonexistent-capability")+ assert result["tools"] == []+ assert "empty query" in result["hint"]+++async def test_discovered_tool_uses_existing_executor_validation_and_durable_receipt(tmp_path):+ gateway = Gateway([descriptor("write_file", "Write a file")])+ ledger = LiveLedger(tmp_path / "live.db")+ try:+ runtime = LiveTools(gateway, ledger, "s", language="en", backend_model="selected")+ runtime.declarations(defer_catalog=True)+ found = await runtime.execute("find", "discover_tools", {"query": "write file"}, 0)+ assert found["tools"][0]["parameters"] == gateway.tools[0].input_schema+ assert gateway.calls == []+ args = {"name": "write_file", "arguments_json": '{"text":"unchanged quality"}'}+ result = await runtime.execute("run", "call_tool", args, 0)+ assert result["success"] is True+ assert result["output"]["text"] == "unchanged quality"+ assert await runtime.execute("run", "call_tool", args, 0) == result+ assert len(gateway.calls) == 1+ assert gateway.calls[0][2].config_snapshot["live_backend_model"] == "selected"+ bad = {"name": "write_file", "arguments_json": '{"text":123}'}+ assert (await runtime.execute("invalid", "call_tool", bad, 0))["success"] is False+ assert len(gateway.calls) == 1+ finally:+ ledger.close()+++def test_current_live_backend_usage_is_priced_instead_of_silently_free():+ # Realistic cached tool-loop usage; cached tokens must not pay the input rate again.+ assert calculate_cost_usd("gpt-5.6-terra", 16390, 2162, 124475) == pytest.approx(0.083619)+++def test_cache_writes_and_reasoning_are_not_free_or_double_counted():+ usage = {+ "input_tokens": 10337,+ "input_tokens_details": {"cache_write_tokens": 10143, "cached_tokens": 0},+ "output_tokens": 59,+ "output_tokens_details": {"reasoning_tokens": 32},+ }+ assert backend_cost_usd("gpt-5.6-terra", usage) == pytest.approx(0.0264535)+ assert backend_cost_usd("gpt-5.6-terra", {"input_tokens": 1000}) == pytest.approx(0.002)+ assert backend_cost_usd("gpt-5.6-terra", {}) == 0+++def test_native_direct_tools_remain_available(tmp_path):+ ledger = LiveLedger(tmp_path / "live.db")+ try:+ runtime = LiveTools(+ Gateway([descriptor("write_file", "Write data")]),+ ledger,+ "s",+ language="en",+ backend_model="",+ )+ assert any(tool["name"].startswith("jarvis_") for tool in runtime.declarations())+ finally:+ ledger.close()diff --git a/tests/contract/test_mars_background_api.py b/tests/contract/test_mars_background_api.pynew file mode 100644index 0000000000..4fa63bbc3a--- /dev/null+++ b/tests/contract/test_mars_background_api.py@@ -0,0 +1,75 @@+"""Window background controls thread-hop native calls and share a bounded status contract."""++from __future__ import annotations++import re+import threading+from pathlib import Path+from typing import get_args, get_type_hints++from fastapi import FastAPI+from fastapi.testclient import TestClient++from jarvis.ui.desktop_background import BackgroundStatus+from jarvis.ui.web.desktop_routes import router+++class FakeDesktop:+ def __init__(self):+ self.enabled = False+ self.native_thread = None++ def get_background_status(self):+ self.native_thread = threading.get_ident()+ return {+ "available": True, "reason": None, "enabled": self.enabled,+ "mode": "foreground", "window_open": True,+ }++ def set_background_mode(self, enabled):+ self.enabled = enabled+ return self.get_background_status()+++def test_native_calls_are_off_loop_and_enable_requires_boolean():+ app = FastAPI()+ app.include_router(router)+ native = FakeDesktop()+ app.state.desktop_app = native++ @app.get("/loop-thread")+ async def loop_thread():+ return {"thread": threading.get_ident()}++ with TestClient(app) as client:+ loop = client.get("/loop-thread").json()["thread"]+ assert client.get("/api/window/background").json()["enabled"] is False+ assert native.native_thread != loop+ assert client.post("/api/window/background", json={"enabled": "yes"}).status_code == 422+ assert not native.enabled+ assert client.post("/api/window/background", json={"enabled": True}).json()["enabled"]+ assert native.native_thread != loop+++def test_headless_reports_existing_background_owner_without_claiming_a_window():+ app = FastAPI()+ app.include_router(router)+ with TestClient(app) as client:+ response = client.get("/api/window/background").json()+ assert response == {+ "available": False, "reason": "headless_host", "enabled": True,+ "mode": "background", "window_open": False,+ }+ assert client.post("/api/window/background", json={"enabled": False}).json() == response+++def test_background_mode_python_typescript_parity():+ source = (+ Path(__file__).resolve().parents[2]+ / "jarvis/ui/web/frontend/src/components/society/mars/MarsBackgroundControl.tsx"+ ).read_text(encoding="utf-8")+ block = re.search(r"BACKGROUND_MODES\s*=\s*\[([^]]+)\]", source)+ assert block+ assert tuple(re.findall(r'"([^"]+)"', block[1])) == get_args(+ get_type_hints(BackgroundStatus)["mode"]+ )diff --git a/tests/contract/test_mars_definition.py b/tests/contract/test_mars_definition.pynew file mode 100644index 0000000000..cb2073ed46--- /dev/null+++ b/tests/contract/test_mars_definition.py@@ -0,0 +1,211 @@+"""The new canonical world has stable, portable and navigable placement data."""++from __future__ import annotations++import json+import math+from pathlib import Path++import pytest++from jarvis.society.mars.definition import load_definition, validate_definition++ROOT = Path(__file__).resolve().parents[2]+++def test_packaged_definition_matches_frontend_and_has_no_private_runtime_paths():+ definition = load_definition()+ projection = ROOT / "jarvis/ui/web/frontend/src/components/society/mars/worldDefinition.json"+ assert json.loads(projection.read_text(encoding="utf-8")) == definition+ encoded = json.dumps(definition)+ assert "Downloads" not in encoded and ".blend" not in encoded+ assert definition["stations"][0]["checkpoint"] == "hub:comms"+ assert definition["status"] == "blockout"+ assert all(row["stage"] == "blockout" for row in definition["districts"])+++def test_reloads_do_not_share_mutable_state():+ original = load_definition()+ original["districts"].clear()+ assert len(load_definition()["districts"]) == 10++[email protected]("kind", ["unknown", "disconnected", "narrow", "version", "infinite"])+def test_invalid_navigation_is_rejected(kind):+ definition = load_definition()+ routes = definition["navigation"]["edges"]+ if kind == "unknown":+ routes[0]["to"] = "missing"+ elif kind == "disconnected":+ definition["navigation"]["nodes"].append({"id": "orphan", "position": [0, 48, 0]})+ elif kind == "narrow":+ routes[0]["width"] = 2+ elif kind == "version":+ definition["navigation"]["version"] = 2+ else:+ definition["navigation"]["nodes"][0]["position"][0] = float("inf")+ with pytest.raises(ValueError):+ validate_definition(definition)+++def test_bounds_contain_tallest_landmark_and_station_rejects_unknown_anchor():+ definition = load_definition()+ foundry = next(d for d in definition["districts"] if d["id"] == "foundry")+ assert definition["bounds"]["max"][1] >= foundry["center"][1] + foundry["landmark_height"]+ definition["stations"][0]["anchor"] = "unreachable-console"+ with pytest.raises(ValueError):+ validate_definition(definition)+++def test_visit_targets_reuse_existing_nodes_and_have_no_task_authority():+ data = load_definition()+ destinations = data["navigation"]["destinations"]+ assert {+ row["id"]: row["anchor"] for row in destinations if not row["id"].startswith("rover-")+ } == {+ "outpost-approach": "console-approach",+ "outpost-bridge-staging": "outpost-west",+ }+ assert all(set(row) == {"id", "name", "anchor", "capacity"} for row in destinations)+ assert all(row["capacity"] == 1 for row in destinations)+ assert len(data["stations"]) == 1+++def test_rover_docks_and_access_share_authored_collision_and_separate_bodies():+ from jarvis.society.mars.mobility_geometry import MobilityGeometry++ data = load_definition()+ nav = data["navigation"]+ geometry = MobilityGeometry(data)+ nodes = {row["id"]: row for row in nav["nodes"]}+ stations = {row["id"]: row["anchor"] for row in nav["destinations"]}+ a, b = nav["rover_docks"]+ assert geometry.path_clear(nodes[a["node_id"]]["position"], nodes[b["node_id"]]["position"])+ for dock in nav["rover_docks"]:+ assert dock["node_id"] not in stations.values()+ for station in [dock["boarding_station_id"], *dock["exit_station_ids"]]:+ assert geometry.capsule_clear(nodes[stations[station]]["position"])+ edges = {row["id"]: row for row in nav["edges"]}+ for label, end in (("a", "lead"), ("b", "tail")):+ crossing = f"corridor:route05-{end}"+ assert crossing in edges[f"route-05-{end}"]["resource_ids"]+ assert crossing in edges[f"rover-{label}-access-1"]["resource_ids"]+ assert crossing in edges[f"rover-{label}-access-4"]["resource_ids"]+ assert f"clearance:rover-{label}" in nodes[f"rover-{label}-dock"]["resource_ids"]+ assert "corridor:route05-lead" in edges["route-03"]["resource_ids"]+ assert "corridor:route05-lead" in edges["rover-a-access-5"]["resource_ids"]+ assert "corridor:route05-lead" in nodes["rover-a-alternate"]["resource_ids"]+ assert "corridor:route05-lead" in nodes["rover-a-alternate-shoulder"]["resource_ids"]+ assert edges["rover-b-access-2"]["to"] == "rover-b-exit"+++def test_parked_rover_does_not_clip_the_existing_console_approach():+ from jarvis.society.mars.mobility_geometry import _rectangle, _segment_distance++ data = load_definition()+ nav = data["navigation"]+ nodes = {node["id"]: node["position"] for node in nav["nodes"]}+ dock = nav["rover_docks"][0]+ center = nodes[dock["node_id"]]+ footprint = _rectangle((center[0], center[2]), dock["yaw"], 3.4, 4.8)+ start, end = nodes["outpost-arrival"], nodes["console-approach"]+ for step in range(101):+ t = step / 100+ point = (start[0] + (end[0] - start[0]) * t, start[2] + (end[2] - start[2]) * t)+ assert (+ min(+ _segment_distance(point, p, q)+ for p, q in zip(footprint, footprint[1:] + footprint[:1], strict=True)+ )+ >= 0.6+ )+++def test_rover_collision_is_reproducible_from_authored_source_and_roads_stay_unchanged():+ from scripts.art.project_mars_collision import project_collision++ data = load_definition()+ source = json.loads(+ (ROOT / "art/studies/mars-outpost-reference/source/geometry-contract.json").read_text(+ "utf-8"+ )+ )+ assert data["navigation"]["collision"] == project_collision(data, source)+ old = data["navigation"]["graph_migrations"][0]["source_descriptor"]["navigation"]+ assert data["navigation"]["surface_edges"] == old["edges"]+ assert len(data["navigation"]["surface_edges"]) == 25+ assert len(data["navigation"]["edges"]) == 37+++ "failure",+ [+ "wall",+ "no_support",+ "same_exit",+ "same_position",+ "bumper",+ "missing",+ "capacity",+ "nan",+ "far",+ ],+)+def test_invalid_rover_dock_is_not_published(failure):+ data = load_definition()+ nav = data["navigation"]+ dock = nav["rover_docks"][0]+ node = next(row for row in nav["nodes"] if row["id"] == "rover-a-board")+ if failure == "wall":+ point = node["position"]+ nav["collision"]["solid_boxes"].append(+ {+ "id": "blocked",+ "min": [point[0] - 1, 58, point[2] - 1],+ "max": [point[0] + 1, 61, point[2] + 1],+ }+ )+ elif failure == "no_support":+ for surface in nav["collision"]["support_surfaces"]:+ surface["plane"][2] -= 2+ elif failure == "same_exit":+ dock["exit_station_ids"][1] = dock["exit_station_ids"][0]+ elif failure == "same_position":+ primary = next(row for row in nav["nodes"] if row["id"] == "rover-a-exit")+ alternate = next(row for row in nav["nodes"] if row["id"] == "rover-a-alternate")+ alternate["position"] = primary["position"].copy()+ elif failure == "bumper":+ center = next(row for row in nav["nodes"] if row["id"] == dock["node_id"])["position"]+ node["position"] = [+ center[0] + 2.4 * math.sin(dock["yaw"]),+ center[1],+ center[2] + 2.4 * math.cos(dock["yaw"]),+ ]+ elif failure == "missing":+ dock["boarding_station_id"] = "missing"+ elif failure == "capacity":+ nav["rovers"][0]["seat_capacity"] = True+ elif failure == "nan":+ nav["rovers"][0]["width_m"] = float("nan")+ else:+ node["position"][0] -= 5+ with pytest.raises(ValueError):+ validate_definition(data)+++ "patch",+ [+ {"capacity": 2},+ {"capacity": True},+ {"anchor": "missing"},+ {"capability": "send-email"},+ {"name": ""},+ {"id": "communications-console"},+ ],+)+def test_invalid_visit_target_cannot_create_a_task_station(patch):+ data = load_definition()+ data["navigation"]["destinations"][0].update(patch)+ with pytest.raises(ValueError):+ validate_definition(data)diff --git a/tests/contract/test_mars_http.py b/tests/contract/test_mars_http.pynew file mode 100644index 0000000000..f47a3d96b8--- /dev/null+++ b/tests/contract/test_mars_http.py@@ -0,0 +1,329 @@+"""Authenticated Mars HTTP contracts with real storage and a test-only executor.++No provider is called. These prove request, authority, privacy and backend-loop+behavior; they do not stand in for live-provider, desktop-close or visual acceptance.+"""++from __future__ import annotations++import asyncio+from dataclasses import dataclass++import httpx+import pytest+from fastapi import FastAPI++from jarvis.society.mars.models import CommandState, DispatchRejected+from jarvis.society.mars.service import MarsStationService+from jarvis.society.mars.store import MarsStore+from jarvis.ui.web.mars_routes import _reconcile_loop, router+from jarvis.ui.web.surface_security import SurfaceSecurity++pytestmark = pytest.mark.no_auto_web_auth++_BASE = "http://127.0.0.1:47821"+_PREFIX = "/api/society/mars"+_TEST_CREDENTIAL = "mars-http-fixture-credential" # noqa: S105 - test-only credential+_HEADERS = {"Authorization": f"Bearer {_TEST_CREDENTIAL}", "Origin": _BASE}+++class FixtureExecutor:+ """Test-only authority; completion changes only on explicit fixture evidence."""++ def __init__(self) -> None:+ self.dispatches: list[str] = []+ self.cancellations: list[tuple[str, str]] = []+ self.completed = asyncio.Event()+ self.dispatched = asyncio.Event()+ self.records: dict[str, dict] = {}+ self.allow_credentials = True++ async def authorize(self, *, agent_id: str, capability_id: str) -> None:+ if agent_id not in {"one", "two"} or capability_id != "communication-draft":+ raise DispatchRejected("permission_denied", 403)++ async def dispatch(self, *, agent_id, command_id, trace_id, draft):+ self.dispatches.append(command_id)+ self.records[command_id] = {"state": "active", "task_ref": f"fixture-task:{command_id}"}+ self.dispatched.set()+ return self.records[command_id]++ async def inspect(self, *, agent_id, command_id, trace_id, task_ref):+ current = self.records[command_id]+ if self.completed.is_set() and current["state"] == "active":+ current = {+ "state": "completed",+ "task_ref": current["task_ref"],+ "result_ref": f"fixture-result:{command_id}",+ }+ self.records[command_id] = current+ return current++ async def cancel(self, *, agent_id, command_id, trace_id, task_ref):+ self.cancellations.append((agent_id, command_id))+ self.records[command_id] = {"state": "canceled", "task_ref": task_ref}+ return {**self.records[command_id], "cancel_attempt": "attempted"}+++@dataclass+class HttpWorld:+ app: FastAPI+ secured: SurfaceSecurity+ service: MarsStationService+ executor: FixtureExecutor++ def client(self) -> httpx.AsyncClient:+ return httpx.AsyncClient(+ transport=httpx.ASGITransport(app=self.secured),+ base_url=_BASE,+ )+++async def world(tmp_path):+ executor = FixtureExecutor()+ service = MarsStationService(MarsStore(tmp_path / "mars.db"), executor)+ await service.start()+ app = FastAPI()+ app.include_router(router)+ # Inject only the executor-bearing composition. All HTTP handlers, storage,+ # station coordination and the outer authentication boundary are production code.+ app.state.mars_station = service+ owner = asyncio.create_task(_reconcile_loop(service), name="mars-http-test-owner")+ app.state.mars_station_task = owner+ secured = SurfaceSecurity(+ app,+ control_key_validator=lambda value: (+ executor.allow_credentials and value == _TEST_CREDENTIAL+ ),+ session_validator=lambda _value: False,+ )+ try:+ yield HttpWorld(app, secured, service, executor)+ finally:+ owner.cancel()+ await asyncio.gather(owner, return_exceptions=True)+ await service.close()+++def _body(request_id="one", **changes):+ return {"request_id": request_id, "draft": "Private draft for operator review.", **changes}+++async def _wait_for_state(world: HttpWorld, command_id: str, state: CommandState):+ async with asyncio.timeout(3):+ while (await world.service.store.get(command_id)).state is not state: # noqa: ASYNC110 - observe committed state, not an executor signal+ await asyncio.sleep(0.01)+++ "headers,status",+ [+ ({"Origin": _BASE}, 401),+ ({"Origin": _BASE, "Authorization": "Bearer wrong-fixture"}, 401),+ ({**_HEADERS, "Origin": "https://foreign.invalid"}, 403),+ ({**_HEADERS, "Origin": "null"}, 403),+ ],+)+async def test_missing_credentials_and_foreign_origins_never_reach_station(world, headers, status):+ async with world.client() as client:+ response = await client.post(+ f"{_PREFIX}/agents/one/commands", headers=headers, json=_body()+ )+ snapshot = await client.get(f"{_PREFIX}/snapshot", headers=headers)+ assert response.status_code == status and snapshot.status_code == status+ assert (await world.service.store.snapshot()).seq == 0+ assert world.executor.dispatches == []+++async def test_revoked_credential_cannot_read_existing_private_state(world):+ async with world.client() as client:+ response = await client.post(+ f"{_PREFIX}/agents/one/commands", headers=_HEADERS, json=_body()+ )+ assert response.status_code == 200+ world.executor.allow_credentials = False+ denied = await client.get(f"{_PREFIX}/snapshot", headers=_HEADERS)+ assert denied.status_code == 401+ assert response.json()["command_id"] not in denied.text+++async def test_authenticated_request_cannot_invent_an_authorized_agent(world):+ async with world.client() as client:+ denied = await client.post(+ f"{_PREFIX}/agents/invented/commands", headers=_HEADERS, json=_body()+ )+ assert denied.status_code == 403+ assert denied.json()["detail"]["reason"] == "permission_denied"+ assert (await world.service.store.snapshot()).seq == 0+ assert not world.executor.dispatches+++ "change",+ [+ {"schema_version": 2},+ {"layout_version": 2},+ {"world_id": "mars:swarm:other"},+ {"transform": [0, 1, 2]},+ {"agent_id": "forged"},+ {"capability_id": "send-email"},+ ],+)+async def test_stale_and_malformed_station_requests_reject_without_mutation(world, change):+ async with world.client() as client:+ response = await client.post(+ f"{_PREFIX}/agents/one/commands",+ headers=_HEADERS,+ json=_body(**change),+ )+ assert response.status_code == 422+ assert response.json() == {"detail": {"reason": "invalid_station_request"}}+ assert (await world.service.store.snapshot()).seq == 0+ assert not world.executor.dispatches++[email protected]("failure", ["version", "length", "extra", "field_name", "body_type"])+async def test_validation_failures_do_not_echo_credential_input(world, failure, caplog):+ credential = "sk-proj-" + "A1" * 20 # Deliberately synthetic shape.+ if failure == "version":+ body = _body(schema_version=2, draft=credential)+ elif failure == "length":+ body = _body(draft=credential + " prose" * 1000)+ elif failure == "extra":+ body = _body(unexpected_private_field=credential)+ elif failure == "field_name":+ body = {**_body(), credential: "unexpected key"}+ else:+ body = credential+ async with world.client() as client:+ response = await client.post(f"{_PREFIX}/agents/one/commands", headers=_HEADERS, json=body)+ assert response.status_code == 422+ assert credential not in response.text and credential not in caplog.text+ assert response.json() == {"detail": {"reason": "invalid_station_request"}}+ assert response.headers["cache-control"] == "no-store"+ assert (await world.service.store.snapshot()).seq == 0+ assert not world.executor.dispatches+++async def test_credential_guard_returns_only_settings_direction_after_valid_schema(world, caplog):+ credential = "sk-proj-" + "A1" * 20+ async with world.client() as client:+ response = await client.post(+ f"{_PREFIX}/agents/one/commands",+ headers=_HEADERS,+ json=_body(draft="Please use this key " + credential),+ )+ assert response.status_code == 422+ assert response.json() == {"detail": {"reason": "credential_input_use_api_key_settings"}}+ assert credential not in response.text and credential not in caplog.text+ assert (await world.service.store.snapshot()).seq == 0+++async def test_event_query_validation_is_bounded_and_does_not_echo_private_cursor(world):+ credential = "sk-proj-" + "A1" * 20+ async with world.client() as client:+ bad_limit = await client.get(f"{_PREFIX}/events?limit=201", headers=_HEADERS)+ bad_cursor = await client.get(+ f"{_PREFIX}/events", headers=_HEADERS, params={"after_seq": credential}+ )+ assert bad_limit.status_code == 422 and bad_cursor.status_code == 422+ assert credential not in bad_cursor.text+ assert bad_cursor.json() == {"detail": {"reason": "invalid_station_request"}}+++async def test_two_http_clients_share_idempotency_and_bounded_delivered_cursor(world):+ async with world.client() as first, world.client() as second:+ submitted = await asyncio.gather(+ first.post(f"{_PREFIX}/agents/one/commands", headers=_HEADERS, json=_body()),+ second.post(f"{_PREFIX}/agents/one/commands", headers=_HEADERS, json=_body()),+ )+ assert all(response.status_code == 200 for response in submitted)+ command_id = submitted[0].json()["command_id"]+ assert submitted[1].json()["command_id"] == command_id+ await world.service.reconcile()+ mismatch = await first.post(+ f"{_PREFIX}/agents/one/commands",+ headers=_HEADERS,+ json=_body(draft="Different request content."),+ )+ assert mismatch.status_code == 409+ assert mismatch.json()["detail"]["reason"] == "idempotency_payload_mismatch"+ snapshot = await first.get(f"{_PREFIX}/snapshot", headers=_HEADERS)+ page = (await first.get(f"{_PREFIX}/events?after_seq=0&limit=1", headers=_HEADERS)).json()+ assert len(page["events"]) == 1+ assert page["next_cursor"] == page["events"][0]["seq"] < page["latest_seq"]+ assert page["has_more"] and not page["resync_required"]+ next_page = (+ await first.get(+ f"{_PREFIX}/events?after_seq={page['next_cursor']}&limit=1",+ headers=_HEADERS,+ )+ ).json()+ assert next_page["events"][0]["seq"] == page["next_cursor"] + 1+ assert len(world.executor.dispatches) == 1+ assert len(snapshot.json()["commands"]) == 1+ assert "draft" not in snapshot.json()["commands"][0]+ assert _body()["draft"] not in snapshot.text+ assert _body()["draft"] not in str(page)+++async def test_cancel_is_scoped_to_command_agent_and_does_not_repeat(world):+ async with world.client() as client:+ created = await client.post(+ f"{_PREFIX}/agents/one/commands", headers=_HEADERS, json=_body()+ )+ command_id = created.json()["command_id"]+ await _wait_for_state(world, command_id, CommandState.ACTIVE)+ foreign = await client.post(+ f"{_PREFIX}/agents/two/commands/{command_id}/cancel",+ headers=_HEADERS,+ )+ assert foreign.status_code == 404 and not world.executor.cancellations+ own = await client.post(+ f"{_PREFIX}/agents/one/commands/{command_id}/cancel",+ headers=_HEADERS,+ )+ assert own.status_code == 200+ await _wait_for_state(world, command_id, CommandState.CANCELED)+ repeated = await client.post(+ f"{_PREFIX}/agents/one/commands/{command_id}/cancel",+ headers=_HEADERS,+ )+ assert repeated.status_code == 200 and repeated.json()["state"] == "canceled"+ assert world.executor.cancellations == [("one", command_id)]+++async def test_process_reconcile_finishes_after_every_http_client_closes(world):+ owner = world.app.state.mars_station_task+ async with world.client() as client:+ created = await client.post(+ f"{_PREFIX}/agents/one/commands", headers=_HEADERS, json=_body()+ )+ command_id = created.json()["command_id"]+ await asyncio.wait_for(world.executor.dispatched.wait(), timeout=2)+ # Every HTTP client is now closed. Only the production backend owner loop+ # can reconcile the fixture's evidence into the durable station result.+ world.executor.completed.set()+ await _wait_for_state(world, command_id, CommandState.COMPLETED)+ assert not owner.done()+ async with world.client() as reopened:+ snapshot = (await reopened.get(f"{_PREFIX}/snapshot", headers=_HEADERS)).json()+ assert snapshot["commands"][0]["command_id"] == command_id+ assert snapshot["commands"][0]["state"] == "completed"+ assert snapshot["commands"][0]["result_ref"] == f"fixture-result:{command_id}"+ assert len(world.executor.dispatches) == 1+ assert world.app.state.mars_station_task is owner+++def test_private_validation_wrapper_preserves_station_openapi_schema():+ app = FastAPI()+ app.include_router(router)+ schema = app.openapi()+ operation = schema["paths"][f"{_PREFIX}/agents/{{agent_id}}/commands"]["post"]+ body = operation["requestBody"]["content"]["application/json"]["schema"]+ assert body["$ref"] == "#/components/schemas/StationCommand"+ command = schema["components"]["schemas"]["StationCommand"]+ assert set(command["required"]) == {"request_id", "draft"}+ assert command["properties"]["draft"]["maxLength"] == 4000+ assert operation["x-jarvis-dangerous"] is Truediff --git a/tests/contract/test_mars_mobility_geometry.py b/tests/contract/test_mars_mobility_geometry.pynew file mode 100644index 0000000000..c43933af08--- /dev/null+++ b/tests/contract/test_mars_mobility_geometry.py@@ -0,0 +1,133 @@+"""Authored support and solid geometry, with no renderer or native dependency."""++from __future__ import annotations++import copy+import math++import pytest++from jarvis.society.mars.mobility_geometry import MobilityGeometry+++def definition():+ return {+ "navigation": {+ "collision": {+ "version": 1,+ "source_sha256": "a" * 64,+ "solid_boxes": [{"id": "wall", "min": [4, 0, -2], "max": [5, 4, 2]}],+ "support_surfaces": [+ {+ "id": "deck",+ "polygon": [[-20, -20], [20, -20], [20, 20], [-20, 20]],+ "plane": [0, 0, 0],+ }+ ],+ }+ }+ }+++def test_capsule_cannot_exit_into_wall_or_over_edge():+ geometry = MobilityGeometry(definition())+ assert geometry.capsule_clear([0, 0, 0])+ assert geometry.capsule_clear([3.3, 0, 0])+ assert not geometry.capsule_clear([3.5, 0, 0])+ assert not geometry.capsule_clear([4.5, 0, 0])+ assert not geometry.capsule_clear([19.5, 0, 0])+ assert not geometry.capsule_clear([0, 3, 0])+ assert not geometry.capsule_clear([0, -3, 0])+++def test_low_ceiling_blocks_capsule_but_overhead_structure_does_not():+ data = definition()+ box = data["navigation"]["collision"]["solid_boxes"][0]+ box.update(min=[-2, 1.7, -2], max=[2, 4, 2])+ assert not MobilityGeometry(data).capsule_clear([0, 0, 0])+ box["min"][1] = 2+ assert MobilityGeometry(data).capsule_clear([0, 0, 0])+++def test_vehicle_checks_rotated_full_body_and_swept_path_not_only_endpoints():+ geometry = MobilityGeometry(definition())+ assert geometry.vehicle_clear([0, 0, 0], 0)+ assert not geometry.vehicle_clear([2, 0, 0], math.pi / 2)+ assert geometry.vehicle_clear([10, 0, 0], math.pi / 2)+ assert not geometry.path_clear([0, 0, 0], [10, 0, 0])+ assert geometry.path_clear([-10, 0, -10], [10, 0, -10])+ assert not geometry.path_clear([-19, 0, -10], [10, 0, -10])+++def test_bridge_support_preserves_grade_and_rejects_gap():+ data = definition()+ surfaces = data["navigation"]["collision"]["support_surfaces"]+ surfaces[0]["plane"] = [0.05, 0, 0]+ geometry = MobilityGeometry(data)+ assert geometry.path_clear([-10, -0.5, -10], [10, 0.5, -10])+ assert not geometry.path_clear([-10, 0, -10], [10, 0, -10])+ surfaces[0]["polygon"] = [[-20, -20], [-1, -20], [-1, 20], [-20, 20]]+ right = copy.deepcopy(surfaces[0])+ right.update(id="right", polygon=[[1, -20], [20, -20], [20, 20], [1, 20]])+ surfaces.append(right)+ assert not MobilityGeometry(data).path_clear([-10, -0.5, -10], [10, 0.5, -10])+++def test_concave_shore_cannot_cut_through_vehicle_between_supported_corners():+ data = definition()+ data["navigation"]["collision"]["support_surfaces"][0]["polygon"] = [+ [-20, -20],+ [20, -20],+ [20, 20],+ [0.2, 20],+ [0.2, 0],+ [-0.2, 0],+ [-0.2, 20],+ [-20, 20],+ ]+ geometry = MobilityGeometry(data)+ assert not geometry.vehicle_clear([0, 0, 0], 0)+ assert not geometry.supported([0, 0, -0.1], 0.6)+++def test_corner_to_corner_notch_does_not_grant_support_under_the_vehicle():+ data = definition()+ data["navigation"]["collision"]["support_surfaces"][0]["polygon"] = [+ [-20, -20],+ [20, -20],+ [20, 20],+ [1.7, 20],+ [1.7, -2.4],+ [-1.7, 2.4],+ [-1.7, 20],+ [-20, 20],+ ]+ geometry = MobilityGeometry(data)+ assert not geometry.supported([0, 0, 1])+ assert not geometry.vehicle_clear([0, 0, 0], 0)++[email protected]("bad", [float("nan"), float("inf"), -float("inf")])+def test_invalid_positions_fail_closed(bad):+ geometry = MobilityGeometry(definition())+ assert not geometry.capsule_clear([bad, 0, 0])+ assert not geometry.vehicle_clear([0, 0, 0], bad)+ assert not geometry.path_clear([0, 0, 0], [bad, 0, 0])++[email protected]("change", ["missing", "nan", "duplicate", "degenerate", "bounds"])+def test_invalid_packaged_collision_rejected(change):+ data = definition()+ collision = data["navigation"]["collision"]+ if change == "missing":+ data["navigation"].pop("collision")+ elif change == "nan":+ collision["support_surfaces"][0]["plane"][0] = float("nan")+ elif change == "duplicate":+ collision["solid_boxes"].append(collision["solid_boxes"][0])+ elif change == "degenerate":+ collision["support_surfaces"][0]["polygon"] = [[0, 0], [1, 1], [2, 2]]+ else:+ collision["solid_boxes"][0]["min"][0] = 10+ with pytest.raises(ValueError):+ MobilityGeometry(data)diff --git a/tests/contract/test_mars_navigation.py b/tests/contract/test_mars_navigation.pynew file mode 100644index 0000000000..ae7bd95566--- /dev/null+++ b/tests/contract/test_mars_navigation.py@@ -0,0 +1,105 @@+"""Portable navigation contract: real graph, strict messages, independent leases."""++from __future__ import annotations++import json++import aiosqlite+import pytest+from pydantic import ValidationError++from jarvis.society.mars.definition import load_definition+from jarvis.society.mars.models import StationCommand, StationError+from jarvis.society.mars.navigation import NavigationGraph+from jarvis.society.mars.navigation_models import MoveCommand, NavigationState, TravelMode+from jarvis.society.mars.navigation_service import MarsNavigationService+from jarvis.society.mars.navigation_store import MarsNavigationStore+from jarvis.society.mars.store import MarsStore+++def test_canonical_routes_support_pedestrian_outpost_but_rover_stops_before_interior():+ graph = NavigationGraph(load_definition())+ assert graph.spawn_node == "outpost-arrival"+ assert graph.path(graph.spawn_node, "communications-console", TravelMode.PEDESTRIAN) == (+ "route-03",+ "route-04",+ )+ assert graph.path(graph.spawn_node, "communications-console", TravelMode.ROVER) is None+++ "patch",+ [+ {"world_id": "other"},+ {"schema_version": True},+ {"graph_version": True},+ {"layout_version": 0},+ {"position": [1, 2, 3]},+ {"draft": "private input"},+ ],+)+def test_move_contract_rejects_cross_world_or_client_position_and_private_payload(patch):+ data = {"request_id": "request", "station_id": "communications-console", **patch}+ with pytest.raises(ValidationError):+ MoveCommand.model_validate_json(json.dumps(data))+++async def test_navigation_does_not_acquire_task_lease_or_change_actual_task_state(tmp_path):+ calls = []++ async def authorize(agent_id, station_id, mode):+ calls.append((agent_id, station_id, mode))+ return True++ station = MarsStore(tmp_path / "work.db")+ navigation = MarsNavigationService(+ MarsNavigationStore(tmp_path / "navigation.db"), load_definition(), authorize=authorize+ )+ await station.open()+ await navigation.start()+ try:+ task = await station.submit(+ "ordinary-agent", StationCommand(request_id="work", draft="Draft a short handover.")+ )+ before = await station.snapshot()+ journey = await navigation.submit(+ "ordinary-agent", MoveCommand(request_id="visit", station_id="communications-console")+ )+ await navigation.advance(unavailable_stations=["communications-console"])+ await navigation.cancel("ordinary-agent", journey.command_id)+ assert await station.snapshot() == before+ assert (await station.get(task.command_id)).state.value == "queued"+ assert len(calls) == 2+ payload = (await navigation.snapshot()).model_dump_json()+ assert "Draft a short handover" not in payload+ assert not {"draft", "task_ref", "result_ref"} & json.loads(payload)["commands"][0].keys()+ finally:+ await navigation.close()+ await station.close()+++async def test_sql_and_public_state_values_match_and_unknown_graph_is_rejected(tmp_path):+ async def authorize(*args):+ return True++ store = MarsNavigationStore(tmp_path / "navigation.db")+ service = MarsNavigationService(store, load_definition(), authorize=authorize)+ await service.start()+ try:+ with pytest.raises(StationError, match="navigation_graph_version_mismatch"):+ await service.submit(+ "agent",+ MoveCommand(+ request_id="visit", station_id="communications-console", graph_version=2+ ),+ )+ async with aiosqlite.connect(store.path) as conn:+ async with conn.execute(+ "SELECT sql FROM sqlite_master WHERE name='navigation_commands'"+ ) as cursor:+ schema = (await cursor.fetchone())[0]+ for state in NavigationState:+ assert "'" + state.value + "'" in schema+ assert (await service.snapshot()).commands == ()+ finally:+ await service.close()diff --git a/tests/contract/test_mars_navigation_http.py b/tests/contract/test_mars_navigation_http.pynew file mode 100644index 0000000000..fac0203af8--- /dev/null+++ b/tests/contract/test_mars_navigation_http.py@@ -0,0 +1,461 @@+"""Production navigation HTTP, authority and lifecycle with real local journals.++The runtime shell opens the real roster only. Station work uses an explicitly+labeled fixture executor, never a provider or an external operation.+"""++from __future__ import annotations++import asyncio+import json+import os+import subprocess+import sys+from pathlib import Path+from types import SimpleNamespace++import httpx+import pytest+from click.testing import CliRunner+from fastapi import FastAPI, HTTPException+from starlette.datastructures import State++from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS+from jarvis.society.mars.definition import load_definition+from jarvis.society.mars.models import StationCommand+from jarvis.society.mars.navigation_models import MoveCommand, NavigationState+from jarvis.society.mars.navigation_ordinary import OrdinaryNavigationAuthority+from jarvis.society.mars.navigation_service import MarsNavigationService+from jarvis.society.mars.navigation_store import MarsNavigationStore+from jarvis.society.roster import Roster+from jarvis.society.store import SocietyStore+from jarvis.ui.web.mars_routes import (+ ensure_mars_navigation,+ ensure_mars_station,+ router,+ schedule_mars_resume,+ stop_mars_station,+)+from jarvis.ui.web.surface_security import SurfaceSecurity++pytestmark = pytest.mark.no_auto_web_auth++BASE = "http://127.0.0.1:47821"+PREFIX = "/api/society/mars"+CREDENTIAL = "navigation-fixture-control-key"+HEADERS = {"Authorization": f"Bearer {CREDENTIAL}", "Origin": BASE}+++class RosterRuntime:+ """Local fixture shell: real ordinary identity storage, no task runtime."""++ def __init__(self, data_dir):+ self.store = SocietyStore(data_dir / "society.db")+ self.roster = Roster(self.store)+ self.ready = asyncio.Event()+ self.ready.set()+ self.starting = asyncio.Event()+ self.started = False++ async def ensure_started(self):+ self.starting.set()+ await self.ready.wait()+ if not self.started:+ await self.store.open()+ for name in ("One", "Two"):+ await self.roster.create(name=name)+ self.started = True++ def chat_service(self):+ raise AssertionError("A visit must not open a chat or call a provider")+++class FixtureStationExecutor:+ """Explicit task boundary for testing independence from a slow inspection."""++ def __init__(self, _runtime):+ self.dispatched = []+ self.inspection_started = asyncio.Event()+ self.inspection_gate = asyncio.Event()++ async def authorize(self, **_kwargs):+ return None++ async def dispatch(self, *, command_id, **_kwargs):+ self.dispatched.append(command_id)+ return {"state": "active", "task_ref": "fixture-task:" + command_id}++ async def inspect(self, *, task_ref, **_kwargs):+ self.inspection_started.set()+ await self.inspection_gate.wait()+ return {"state": "active", "task_ref": task_ref}++ async def cancel(self, **_kwargs):+ raise AssertionError("Stopping navigation must never cancel ordinary work")+++def shell(data_dir, monkeypatch):+ import jarvis.society.mars.ordinary as ordinary++ runtime = RosterRuntime(data_dir)+ executor = FixtureStationExecutor(runtime)+ monkeypatch.setattr(ordinary, "OrdinaryStationExecutor", lambda _runtime: executor)+ calls = []++ def factory():+ calls.append("factory")+ return runtime++ return State({"society_factory": factory}), runtime, executor, calls+++async def world(tmp_path, monkeypatch):+ state, runtime, executor, calls = shell(tmp_path, monkeypatch)+ app = FastAPI()+ app.state = state+ app.include_router(router)+ security = SurfaceSecurity(+ app,+ control_key_validator=lambda value: value == CREDENTIAL,+ session_validator=lambda _value: False,+ )++ def client():+ return httpx.AsyncClient(transport=httpx.ASGITransport(app=security), base_url=BASE)++ try:+ yield SimpleNamespace(+ app=app, runtime=runtime, executor=executor, calls=calls, client=client+ )+ finally:+ await stop_mars_station(state)+ await runtime.store.close()+++def body(request_id="visit", destination="communications-console", **changes):+ return {"request_id": request_id, "station_id": destination, **changes}+++async def post(client, agent="one", **kwargs):+ return await client.post(f"{PREFIX}/agents/{agent}/moves", headers=HEADERS, json=body(**kwargs))+++ "headers,status",+ [+ ({"Origin": BASE}, 401),+ ({**HEADERS, "Authorization": "Bearer invalid-fixture"}, 401),+ ({**HEADERS, "Origin": "https://foreign.invalid"}, 403),+ ],+)+async def test_authentication_precedes_navigation_initialization(world, headers, status):+ async with world.client() as client:+ read = await client.get(f"{PREFIX}/navigation/snapshot", headers=headers)+ write = await client.post(f"{PREFIX}/agents/one/moves", headers=headers, json=body())+ cancel = await client.post(f"{PREFIX}/agents/one/moves/unknown/cancel", headers=headers)+ assert read.status_code == write.status_code == cancel.status_code == status+ assert world.calls == []+ assert not world.runtime.store.path.exists()++[email protected]("state", ["invented", "archived", "kill_switch"])+async def test_real_roster_and_execution_stop_control_movement(world, state):+ service = await ensure_mars_navigation(world.app.state)+ agent = "one"+ if state == "invented":+ agent = "fabricated-worker"+ elif state == "archived":+ await world.runtime.roster.update(agent, {"state": "archived"})+ else:+ await world.runtime.store.set_kill_switch(True)+ async with world.client() as client:+ response = await post(client, agent)+ assert response.status_code == 403+ assert response.json()["detail"]["reason"] == "navigation_not_authorized"+ assert (await service.snapshot()).commands == ()+ assert world.executor.dispatched == []+++ "patch,reason",+ [+ ({"mode": "rover"}, "unsupported_navigation_mode"),+ ({"mode": "spaceship"}, "unsupported_navigation_mode"),+ ({"world_id": "mars:another"}, "invalid_navigation_request"),+ ({"graph_version": True}, "invalid_navigation_request"),+ ({"position": [1, 2, 3]}, "invalid_navigation_request"),+ ({"agent_id": "forged"}, "invalid_navigation_request"),+ ({"draft": "private communication"}, "invalid_navigation_request"),+ ],+)+async def test_public_api_rejects_unsupported_mode_or_forged_body_before_initialization(+ world, patch, reason+):+ async with world.client() as client:+ response = await post(client, **patch)+ assert response.status_code == 422+ assert response.json() == {"detail": {"reason": reason}}+ assert world.calls == []++[email protected]("location", ["extra_value", "extra_key", "body", "actor_path"])+async def test_private_rejected_input_is_never_echoed_or_logged(world, location, caplog):+ private = "sk-proj-" + "A1" * 20+ payload = body()+ actor = "one"+ if location == "extra_value":+ payload["extra"] = private+ elif location == "extra_key":+ payload[private] = True+ elif location == "body":+ payload = private+ else:+ actor = private + "@invalid"+ async with world.client() as client:+ response = await client.post(+ f"{PREFIX}/agents/{actor}/moves", headers=HEADERS, json=payload+ )+ assert response.status_code == 422+ assert response.json() == {"detail": {"reason": "invalid_navigation_request"}}+ assert response.headers["cache-control"] == "no-store"+ assert private not in response.text and private not in caplog.text+ assert world.calls == []+++async def test_http_clients_share_move_identity_and_only_known_destinations(world):+ async with world.client() as one, world.client() as two:+ first, second = await asyncio.gather(post(one), post(two))+ assert first.status_code == second.status_code == 200+ assert first.json()["command_id"] == second.json()["command_id"]+ conflict = await post(one, destination="outpost-bridge-staging")+ unknown = await post(one, request_id="other", destination="invented-place")+ stale = await post(one, request_id="other", graph_version=2)+ assert conflict.status_code == stale.status_code == 409+ assert unknown.status_code == 404+ snapshot = await one.get(f"{PREFIX}/navigation/snapshot", headers=HEADERS)+ assert len(snapshot.json()["commands"]) == 1+ assert not {"draft", "task_ref", "result_ref"} & snapshot.json()["commands"][0].keys()+ assert world.executor.dispatched == []+ assert world.calls == ["factory"]+++async def test_move_cancel_leaves_actual_task_and_other_actor_unchanged(world):+ station = await ensure_mars_station(world.app.state)+ task = await station.submit("one", StationCommand(request_id="work", draft="Fixture draft."))+ async with asyncio.timeout(2):+ while (await station.store.get(task.command_id)).state.value != "active": # noqa: ASYNC110 - wait for the real station coordinator's persisted dispatch receipt+ await asyncio.sleep(0.01)+ before = await station.store.get(task.command_id)+ async with world.client() as client:+ created = await post(client)+ command = created.json()["command_id"]+ foreign = await client.post(f"{PREFIX}/agents/two/moves/{command}/cancel", headers=HEADERS)+ assert foreign.status_code == 404+ canceled = await client.post(f"{PREFIX}/agents/one/moves/{command}/cancel", headers=HEADERS)+ repeated = await client.post(f"{PREFIX}/agents/one/moves/{command}/cancel", headers=HEADERS)+ assert canceled.json() == repeated.json()+ assert canceled.json()["state"] == "canceled"+ assert await station.store.get(task.command_id) == before+ assert world.executor.dispatched == [task.command_id]+++async def test_canonical_two_agent_handoff_waits_for_safe_departure(world):+ service = await ensure_mars_navigation(world.app.state)+ # Keep HTTP/storage/graph/authority production code; replace only wall clock+ # so the 40-metre journey can be verified deterministically without sleeping.+ owner = world.app.state.mars_navigation_task+ owner.cancel()+ await asyncio.gather(owner, return_exceptions=True)+ now = [100_000]+ service.store.clock = lambda: now[0]++ async def advance(count):+ for _ in range(count):+ now[0] += 1000+ await service.advance()+ occupancy = (await service.snapshot()).occupancies+ assert len({row.resource_id for row in occupancy}) == len(occupancy), [+ (row.resource_id, row.owner, row.position) for row in occupancy+ ]++ async with world.client() as client:+ first = (await post(client)).json()["command_id"]+ second = (await post(client, "two")).json()["command_id"]+ await advance(25)+ assert (await service.store.get(first)).state is NavigationState.ARRIVED+ waiting = await service.store.get(second)+ assert waiting.state is NavigationState.QUEUEING and waiting.presence == "spawn_queue"+ departure = await post(client, request_id="depart", destination="outpost-bridge-staging")+ assert departure.status_code == 200+ departing_id = departure.json()["command_id"]+ await advance(65)+ assert (await service.store.get(departing_id)).state is NavigationState.ARRIVED+ assert (await service.store.get(second)).state is NavigationState.ARRIVED+ visits = (await client.get(f"{PREFIX}/navigation/snapshot", headers=HEADERS)).json()+ latest = {row["agent_id"]: row for row in visits["commands"]}+ assert latest["one"]["current_node"] == "outpost-west"+ assert latest["two"]["current_node"] == "console"+ assert world.executor.dispatched == []+++async def test_slow_station_inspection_cannot_block_zero_client_navigation(world):+ station = await ensure_mars_station(world.app.state)+ await station.submit("one", StationCommand(request_id="work", draft="Fixture draft."))+ async with world.client() as client:+ command = (await post(client)).json()["command_id"]+ await asyncio.wait_for(world.executor.inspection_started.wait(), 3)+ navigation = world.app.state.mars_navigation+ before = await navigation.store.get(command)+ async with asyncio.timeout(2):+ while (await navigation.store.get(command)).position == before.position: # noqa: ASYNC110 - observe committed backend progress without any HTTP client+ await asyncio.sleep(0.02)+ assert not world.executor.inspection_gate.is_set()+ assert not world.app.state.mars_station_task.done()+ assert not world.app.state.mars_navigation_task.done()+++async def test_both_surfaces_share_initialization_and_canceled_waiter_does_not_own_it(world):+ state = world.app.state+ world.runtime.ready.clear()+ first = asyncio.create_task(ensure_mars_navigation(state))+ await world.runtime.starting.wait()+ second = asyncio.create_task(ensure_mars_station(state))+ first.cancel()+ with pytest.raises(asyncio.CancelledError):+ await first+ assert not state.mars_station_initialization_task.done()+ world.runtime.ready.set()+ station = await second+ assert station is state.mars_station+ assert await ensure_mars_navigation(state) is state.mars_navigation+ assert world.calls == ["factory"]+ assert state.mars_navigation_task.get_name() == "mars-navigation-owner"+++async def test_stop_fences_both_surfaces_and_releases_both_journal_owners(world):+ state = world.app.state+ navigation = await ensure_mars_navigation(state)+ station = state.mars_station+ tasks = [state.mars_navigation_task, state.mars_station_task]+ await stop_mars_station(state)+ assert all(task.done() for task in tasks)+ assert state.mars_station is state.mars_navigation is None+ with pytest.raises(HTTPException):+ await ensure_mars_navigation(state)+ await navigation.store.open()+ await station.store.open()+ await navigation.store.close()+ await station.store.close()+++async def test_navigation_journal_alone_resumes_without_http_client(tmp_path, monkeypatch):+ state, runtime, _executor, calls = shell(tmp_path, monkeypatch)+ await runtime.ensure_started()+ navigation = MarsNavigationService(+ MarsNavigationStore(tmp_path / "mars" / "navigation.db"),+ load_definition(),+ authorize=OrdinaryNavigationAuthority(runtime),+ )+ await navigation.start()+ command = await navigation.submit("one", MoveCommand(**body()))+ await navigation.close()+ assert not (tmp_path / "mars" / "ordinary.db").exists()+ try:+ schedule_mars_resume(state, tmp_path)+ await state.mars_station_startup_task+ resumed = state.mars_navigation+ async with asyncio.timeout(2):+ while (await resumed.store.get(command.command_id)).position == command.position: # noqa: ASYNC110 - verify the owned loop, no HTTP client exists+ await asyncio.sleep(0.02)+ assert calls == ["factory"]+ finally:+ await stop_mars_station(state)+ await runtime.store.close()+++def test_navigation_openapi_models_are_typed_and_dynamic_cli_reaches_routes():+ from jarvis.cli_ctl.dynamic import build_api_group++ app = FastAPI()+ app.include_router(router)+ schema = app.openapi()+ command = schema["components"]["schemas"]["PedestrianMoveCommand"]+ assert command["properties"]["mode"]["const"] == "pedestrian"+ assert set(command["required"]) == {"request_id", "station_id"}+ calls = []++ def runner(method, path, params, body, **kwargs):+ calls.append((method, path, params, body))+ return {"ok": True}++ cli = build_api_group(schema, runner)+ for args in (+ ["get-mars-navigation-snapshot"],+ ["submit-mars-move", "--agent_id", "one", "--json-body", json.dumps(body()), "--yes"],+ ["cancel-mars-move", "--agent_id", "one", "--command_id", "visit", "--yes"],+ ):+ result = CliRunner().invoke(cli, ["mars", *args])+ assert result.exit_code == 0, result.output+ assert [(method, path) for method, path, *_ in calls] == [+ ("get", f"{PREFIX}/navigation/snapshot"),+ ("post", f"{PREFIX}/agents/one/moves"),+ ("post", f"{PREFIX}/agents/one/moves/visit/cancel"),+ ]+ assert calls[1][3] == body()+++async def child_process(data_dir, action):+ runtime = RosterRuntime(data_dir)+ await runtime.ensure_started()+ if action == "seed":+ navigation = MarsNavigationService(+ MarsNavigationStore(data_dir / "mars" / "navigation.db"),+ load_definition(),+ authorize=OrdinaryNavigationAuthority(runtime),+ )+ await navigation.start()+ command = await navigation.submit("one", MoveCommand(**body()))+ (data_dir / "seed.json").write_text(command.model_dump_json(), "utf-8")+ os._exit(0)+ state = State({"society_factory": lambda: runtime})+ seed = json.loads((data_dir / "seed.json").read_text("utf-8"))+ try:+ schedule_mars_resume(state, data_dir)+ await state.mars_station_startup_task+ service = state.mars_navigation+ async with asyncio.timeout(3):+ while True:+ command = await service.store.get(seed["command_id"])+ if command.position != tuple(seed["position"]):+ break+ await asyncio.sleep(0.02)+ (data_dir / "recovered.json").write_text(command.model_dump_json(), "utf-8")+ finally:+ await stop_mars_station(state)+ await runtime.store.close()+++def test_abrupt_process_exit_navigation_resumes_with_no_renderer_or_client(tmp_path):+ for action in ("seed", "recover"):+ result = subprocess.run(+ [sys.executable, str(Path(__file__).resolve()), action, str(tmp_path)],+ capture_output=True,+ text=True,+ encoding="utf-8",+ errors="replace",+ creationflags=NO_WINDOW_CREATIONFLAGS,+ timeout=20,+ check=False,+ )+ assert result.returncode == 0, result.stderr+ seed = json.loads((tmp_path / "seed.json").read_text("utf-8"))+ recovered = json.loads((tmp_path / "recovered.json").read_text("utf-8"))+ assert recovered["command_id"] == seed["command_id"]+ assert recovered["trace_id"] == seed["trace_id"]+ assert recovered["position"] != seed["position"]+ assert recovered["presence"] == "placed"+++if __name__ == "__main__":+ asyncio.run(child_process(Path(sys.argv[2]), sys.argv[1]))diff --git a/tests/contract/test_mars_navigation_parity.py b/tests/contract/test_mars_navigation_parity.pynew file mode 100644index 0000000000..948a326990--- /dev/null+++ b/tests/contract/test_mars_navigation_parity.py@@ -0,0 +1,47 @@+"""Navigation vocabulary stays aligned from SQL storage through the public UI."""++from __future__ import annotations++import json+import re+import sqlite3+from pathlib import Path++import pytest+from fastapi import FastAPI++from jarvis.society.mars.navigation_models import NavigationState+from jarvis.society.mars.navigation_store import _SCHEMA+from jarvis.ui.web.mars_routes import router++ROOT = Path(__file__).resolve().parents[2]+++def test_navigation_states_match_sql_openapi_typescript_and_localized_controls():+ states = {state.value for state in NavigationState}+ with sqlite3.connect(":memory:") as conn:+ conn.executescript(_SCHEMA)+ for index, state in enumerate(sorted(states)):+ conn.execute(+ "INSERT INTO navigation_commands(command_id,agent_id,fingerprint,state,record) "+ "VALUES(?,?,?,?,?)", (str(index), "actor", "fingerprint", state, "{}")+ )+ with pytest.raises(sqlite3.IntegrityError):+ conn.execute(+ "INSERT INTO navigation_commands(command_id,agent_id,fingerprint,state,record) "+ "VALUES('bad','actor','fingerprint','completed','{}')"+ )+ app = FastAPI()+ app.include_router(router)+ components = app.openapi()["components"]["schemas"]+ assert set(components["NavigationState"]["enum"]) == states+ modes = components["PedestrianMoveCommand"]["properties"]["mode"]+ assert modes.get("const", modes.get("enum")) in ("pedestrian", ["pedestrian"])+ source = (ROOT / "jarvis/ui/web/frontend/src/components/society/mars/navigationApi.ts").read_text("utf-8")+ declaration = re.search(r"NAVIGATION_STATES = \[(.*?)\] as const", source)+ assert declaration is not None+ assert set(re.findall(r'"([a-z_]+)"', declaration.group(1))) == states+ for language in ("en", "de", "es"):+ locale = json.loads((ROOT / f"jarvis/ui/web/frontend/src/i18n/locales/society/{language}.json").read_text("utf-8"))["society"]["mars"]+ assert all(locale.get(f"move_state_{state}") for state in states)+ assert locale["stopped_in_place"] and locale["visit_scope"]diff --git a/tests/contract/test_mars_ordinary.py b/tests/contract/test_mars_ordinary.pynew file mode 100644index 0000000000..0dba096674--- /dev/null+++ b/tests/contract/test_mars_ordinary.py@@ -0,0 +1,253 @@+"""Outpost work uses real Society authority; only the provider is a labeled fake."""++from __future__ import annotations++import asyncio+from pathlib import Path+from types import SimpleNamespace++import pytest++from jarvis.agent_chat.service import AgentChatService+from jarvis.agent_chat.store import AgentChatStore+from jarvis.society.events import MsgType, SocietyEnvelope+from jarvis.society.mars.models import CommandState, StationCommand, StationError+from jarvis.society.mars.ordinary import OrdinaryStationExecutor+from jarvis.society.mars.service import MarsStationService+from jarvis.society.mars.store import MarsStore+from jarvis.society.runtime import SocietyRuntime+++class ControlledChat(AgentChatService):+ """No provider invocation: hold one task until the test emits its durable result."""++ def __init__(self, path: Path):+ super().__init__(AgentChatStore(path))+ self.sent: list[dict] = []+ self.cancel_calls: list[tuple[str, str | None]] = []+ self.cancel_status: str | None = "cancelled"++ async def send(self, session_id, text, **kwargs):+ self.sent.append({"session_id": session_id, "text": text, **kwargs})+ return "controlled-turn"++ async def cancel(self, session_id, *, expected_turn_id=None):+ """Controlled terminal race; no real runner/provider or wall-clock sleep."""+ self.cancel_calls.append((session_id, expected_turn_id))+ if self.cancel_status is not None:+ await self._emit(+ session_id,+ {+ "kind": "turn_finished",+ "payload": {"turn_id": expected_turn_id, "status": self.cancel_status},+ },+ )+ return True+++async def ordinary(tmp_path):+ service = ControlledChat(tmp_path / "chat.db")+ runtime = SocietyRuntime(+ tmp_path,+ seed_starter_team=False,+ chat_service=lambda: service,+ cfg=lambda: SimpleNamespace(memory=SimpleNamespace(data_dir=str(tmp_path))),+ )+ await runtime.ensure_started()+ await runtime.roster.create(name="Comms", provider="openai")+ try:+ yield runtime, service, OrdinaryStationExecutor(runtime)+ finally:+ await runtime.close()+ service.store.close()+++async def test_draft_dispatch_reuses_authority_and_does_not_repeat_after_retry(ordinary):+ runtime, service, adapter = ordinary+ args = {"agent_id": "comms", "command_id": "command-1", "trace_id": "mars:test-1"}+ result = await adapter.dispatch(**args, draft="Write a short meeting invitation.")+ assert result["state"] == "active"+ assert result["task_ref"] == "turn:controlled-turn"+ assert service.sent[0]["read_only"] is True+ assert service.sent[0]["direct_user"] is False+ assert await adapter.dispatch(**args, draft="Write a short meeting invitation.") == result+ assert len(service.sent) == 1+ events = await runtime.store.events_for_trace(args["trace_id"])+ assert [event.msg_type for event in events] == [MsgType.ASSIGN, MsgType.CLAIM]+ await service._emit(+ "society:comms",+ { # noqa: SLF001 - controlled provider fixture+ "kind": "assistant_text",+ "payload": {"turn_id": "controlled-turn", "text": "Draft text"},+ },+ )+ await service._emit(+ "society:comms",+ { # noqa: SLF001+ "kind": "turn_finished",+ "payload": {"turn_id": "controlled-turn", "status": "done"},+ },+ )+ async with asyncio.timeout(2):+ while True:+ receipt = await adapter.inspect(**args, task_ref=result["task_ref"])+ if receipt["state"] == "completed":+ break+ await asyncio.sleep(0.01)+ assert receipt["result_ref"]+ assert len(service.sent) == 1+++async def test_pause_kill_and_wrong_identity_cannot_gain_station_execution(ordinary):+ runtime, service, adapter = ordinary+ with pytest.raises(PermissionError):+ await adapter.authorize(agent_id="unknown", capability_id="communication-draft")+ with pytest.raises(PermissionError):+ await adapter.authorize(agent_id="comms", capability_id="send-email")+ await runtime.store.set_kill_switch(True)+ with pytest.raises(PermissionError):+ await adapter.dispatch(+ agent_id="comms", command_id="halted", trace_id="mars:halted", draft="Draft"+ )+ assert not service.sent+++async def test_unrecorded_outcome_never_becomes_success_or_retry(ordinary):+ _, service, adapter = ordinary+ receipt = await adapter.inspect(+ agent_id="comms", command_id="missing", trace_id="mars:missing", task_ref=None+ )+ assert receipt["state"] == "unknown"+ assert not service.sent+++async def test_credentials_never_reach_mars_society_or_chat(ordinary, tmp_path, caplog):+ runtime, chat, adapter = ordinary+ credential = "sk-proj-" + "A1" * 20 # Synthetic shape, never a usable credential.+ before = await runtime.store.last_seq()+ path = tmp_path / "not-created" / "mars.db"+ gateway = MarsStationService(MarsStore(path), adapter)+ command = StationCommand(request_id="secret-rejected", draft="Use this key " + credential)+ with pytest.raises(StationError, match="credential_input_use_api_key_settings") as exc:+ await gateway.submit("comms", command)+ assert exc.value.status_code == 422+ assert not path.exists()+ # Even a direct trusted-adapter caller cannot bypass the pre-persistence guard.+ with pytest.raises(StationError, match="credential_input_use_api_key_settings"):+ await adapter.dispatch(+ agent_id="comms",+ command_id="secret-rejected",+ trace_id="mars:secret-rejected",+ draft=command.draft,+ )+ assert await runtime.store.last_seq() == before+ assert chat.store.get_session("society:comms") is None+ assert not chat.sent and not chat.store.list_events("society:comms")+ assert credential not in caplog.text and credential not in str(exc.value)++[email protected]("terminal,expected", [("done", "completed"), ("cancelled", "canceled")])+async def test_cancel_rechecks_exact_durable_terminal_after_grace_period(+ ordinary, terminal, expected+):+ _, service, adapter = ordinary+ args = {"agent_id": "comms", "command_id": "cancel-race", "trace_id": "mars:cancel-race"}+ active = await adapter.dispatch(**args, draft="Draft a meeting invitation.")+ service.cancel_status = terminal+ outcome = await adapter.cancel(**args, task_ref=active["task_ref"])+ assert outcome["state"] == expected+ assert outcome["cancel_attempt"] == "attempted"+ assert outcome["task_ref"] == "turn:controlled-turn" and outcome["result_ref"]+ assert service.cancel_calls == [("society:comms", "controlled-turn")]+ # A replay reads the recorded terminal and does not issue another stop.+ replay = await adapter.cancel(**args, task_ref=active["task_ref"])+ assert replay["state"] == expected and replay["cancel_attempt"] == "not_attempted"+ assert len(service.cancel_calls) == 1+++async def test_true_stop_receipt_without_terminal_cannot_manufacture_canceled(ordinary):+ _, service, adapter = ordinary+ args = {"agent_id": "comms", "command_id": "no-terminal", "trace_id": "mars:no-terminal"}+ active = await adapter.dispatch(**args, draft="Draft a handover.")+ service.cancel_status = None+ outcome = await adapter.cancel(**args, task_ref=active["task_ref"])+ assert outcome["state"] == "active" and outcome["cancel_attempt"] == "attempted"+ assert outcome.get("result_ref") is None+++async def test_pending_cancel_recovers_missing_claim_without_repeating_dispatch(ordinary, tmp_path):+ runtime, chat, adapter = ordinary+ gateway = MarsStationService(MarsStore(tmp_path / "deferred-mars.db"), adapter)+ await gateway.start()+ try:+ command = await gateway.store.submit(+ "comms", StationCommand(request_id="deferred", draft="Draft the shift handover.")+ )+ await adapter.authorize(agent_id="comms", capability_id="communication-draft")+ # Test-only crash window: an assignment exists, but its accepted task's+ # durable CLAIM has not been recovered yet. No real provider is invoked.+ runtime.scheduler.detach()+ assignment_id = f"mars-assign:{command.command_id}"+ await runtime.store.append_and_publish(+ SocietyEnvelope(+ event_id=assignment_id,+ msg_type=MsgType.ASSIGN,+ from_agent="user",+ to_agent="comms",+ trace_id=command.trace_id,+ payload={"text": command.draft},+ )+ )+ await gateway.reconcile()+ assert (await gateway.store.get(command.command_id)).task_ref is None+ await gateway.cancel("comms", command.command_id)+ await gateway.reconcile()+ pending = await gateway.store.get(command.command_id)+ assert pending.cancel_requested and not pending.cancel_dispatched+ assert not chat.cancel_calls+ # Existing authority recovers the claim; the queued stop targets that+ # exact recovered turn and never creates a replacement assignment.+ await runtime.store.append_and_publish(+ SocietyEnvelope(+ msg_type=MsgType.CLAIM,+ from_agent="comms",+ to_agent="user",+ trace_id=command.trace_id,+ parent_event_id=assignment_id,+ payload={"run_id": "turn:recovered-turn"},+ )+ )+ runtime.scheduler.note_run_started("turn:recovered-turn", "comms")+ await gateway.reconcile()+ canceled = await gateway.store.get(command.command_id)+ assert canceled.state is CommandState.CANCELED+ assert canceled.task_ref == "turn:recovered-turn"+ assert chat.cancel_calls == [("society:comms", "recovered-turn")]+ assert not chat.sent+ assert (+ sum(+ event.msg_type is MsgType.ASSIGN+ for event in await runtime.store.events_for_trace(command.trace_id)+ )+ == 1+ )+ finally:+ await gateway.close()+++async def test_unavailable_chat_service_reports_no_stop_attempt(ordinary):+ runtime, service, adapter = ordinary+ args = {"agent_id": "comms", "command_id": "service-gap", "trace_id": "mars:service-gap"}+ active = await adapter.dispatch(**args, draft="Draft a meeting invitation.")+ original = runtime._get_chat # noqa: SLF001 - isolated unavailable-service fixture+ runtime._get_chat = lambda: None # noqa: SLF001+ try:+ unavailable = await adapter.cancel(**args, task_ref=active["task_ref"])+ finally:+ runtime._get_chat = original # noqa: SLF001+ assert unavailable["cancel_attempt"] == "not_attempted"+ assert not service.cancel_calls+ recovered = await adapter.cancel(**args, task_ref=active["task_ref"])+ assert recovered["state"] == "canceled" and recovered["cancel_attempt"] == "attempted"+ assert len(service.cancel_calls) == 1diff --git a/tests/contract/test_mars_restart_lifecycle.py b/tests/contract/test_mars_restart_lifecycle.pynew file mode 100644index 0000000000..86bdf99b78--- /dev/null+++ b/tests/contract/test_mars_restart_lifecycle.py@@ -0,0 +1,559 @@+"""Real journal/process recovery with a labeled test-only execution boundary.++No renderer, HTTP client or provider participates in the recovery process.+These fixtures prove local checkpoint recovery, not host sleep or live-provider+reconciliation after an external side effect.+"""++from __future__ import annotations++import asyncio+import json+import os+import subprocess+import sys+from pathlib import Path+from types import SimpleNamespace++import pytest+from fastapi import FastAPI, HTTPException, Request+from starlette.datastructures import State++from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS+from jarvis.society.mars.models import (+ CommandState,+ DispatchRejected,+ ExecutionReceipt,+ StationCommand,+ StationError,+)+from jarvis.society.mars.store import MarsStore+from jarvis.ui.web.mars_routes import (+ _service,+ ensure_mars_station,+ schedule_mars_resume,+ stop_mars_station,+)+++class FixtureRuntime:+ def __init__(self, data_dir: Path):+ self.store = SimpleNamespace(path=data_dir / "society.db")+ self.starting = asyncio.Event()+ self.ready = asyncio.Event()+ self.ready.set()++ async def ensure_started(self):+ self.starting.set()+ await self.ready.wait()+++class FixtureExecutor:+ """Deterministic authority; never performs a provider call or external write."""++ def __init__(self, _runtime):+ self.dispatches = []+ self.inspections = []+ self.authorizations = []+ self.denied = False+ self.inspection_started = asyncio.Event()+ self.inspection_gate = asyncio.Event()+ self.inspection_gate.set()++ async def authorize(self, *, agent_id, capability_id):+ self.authorizations.append((agent_id, capability_id))+ if self.denied:+ raise DispatchRejected("permission_denied", 403)++ async def dispatch(self, *, agent_id, command_id, trace_id, draft):+ self.dispatches.append(command_id)+ return {+ "state": "completed",+ "task_ref": f"fixture-task:{command_id}",+ "result_ref": f"fixture-result:{command_id}",+ }++ async def inspect(self, *, agent_id, command_id, trace_id, task_ref):+ self.inspections.append(command_id)+ self.inspection_started.set()+ await self.inspection_gate.wait()+ return {+ "state": "completed",+ "task_ref": task_ref or f"fixture-task:{command_id}",+ "result_ref": f"fixture-result:{command_id}",+ }++ async def cancel(self, **_kwargs):+ raise AssertionError("Recovery cannot invent a cancellation request")+++async def seed_journal(data_dir: Path, checkpoint: str):+ store = MarsStore(data_dir / "mars" / "ordinary.db")+ await store.open()+ command = await store.submit(+ "fixture-agent", StationCommand(request_id="fixture-request", draft="Fictional draft.")+ )+ if checkpoint != "queued":+ claimed = await store.claim_next()+ receipt = ExecutionReceipt(+ state=CommandState.COMPLETED if checkpoint == "completed" else CommandState.ACTIVE,+ task_ref=f"fixture-task:{command.command_id}",+ result_ref=f"fixture-result:{command.command_id}"+ if checkpoint == "completed"+ else None,+ )+ await store.apply(command.command_id, claimed.fence, receipt)+ record = await store.get(command.command_id)+ return store, record+++def setup_state(data_dir: Path, monkeypatch):+ import jarvis.society.mars.ordinary as ordinary++ runtime = FixtureRuntime(data_dir)+ executor = FixtureExecutor(runtime)+ monkeypatch.setattr(ordinary, "OrdinaryStationExecutor", lambda _runtime: executor)+ calls = []++ def factory():+ calls.append("factory")+ return runtime++ return State({"society_factory": factory}), runtime, executor, calls+++async def wait_terminal(service, command_id):+ async with asyncio.timeout(3):+ while True:+ record = await service.store.get(command_id)+ if record.state in {CommandState.COMPLETED, CommandState.FAILED}:+ return record+ await asyncio.sleep(0.01)+++async def test_no_journal_does_not_construct_runtime_or_create_storage(tmp_path, monkeypatch):+ state, _runtime, _executor, calls = setup_state(tmp_path, monkeypatch)+ schedule_mars_resume(state, tmp_path)+ startup = state.mars_station_startup_task+ assert calls == []+ assert not (tmp_path / "mars").exists()+ await startup+ await stop_mars_station(state)+ assert calls == []+ assert not (tmp_path / "mars").exists()+++async def test_queued_recovery_reauthorizes_before_dispatch(tmp_path, monkeypatch):+ store, command = await seed_journal(tmp_path, "queued")+ await store.close()+ state, _runtime, executor, calls = setup_state(tmp_path, monkeypatch)+ executor.denied = True+ try:+ schedule_mars_resume(state, tmp_path)+ await state.mars_station_startup_task+ record = await wait_terminal(state.mars_station, command.command_id)+ assert record.state is CommandState.FAILED+ assert record.reason == "permission_denied"+ assert executor.authorizations == [("fixture-agent", "communication-draft")]+ assert executor.dispatches == []+ assert calls == ["factory"]+ finally:+ await stop_mars_station(state)+++async def test_boot_and_first_api_share_one_service_and_owner(tmp_path, monkeypatch):+ store, _command = await seed_journal(tmp_path, "queued")+ await store.close()+ state, runtime, _executor, calls = setup_state(tmp_path, monkeypatch)+ runtime.ready.clear()+ app = FastAPI()+ app.state = state+ request = Request({"type": "http", "app": app})+ try:+ schedule_mars_resume(state, tmp_path)+ startup = state.mars_station_startup_task+ await asyncio.wait_for(runtime.starting.wait(), 2)+ api = asyncio.create_task(_service(request))+ schedule_mars_resume(state, tmp_path)+ assert state.mars_station_startup_task is startup+ runtime.ready.set()+ await startup+ service = await api+ owner = state.mars_station_task+ assert service is state.mars_station+ assert await ensure_mars_station(state) is service+ assert state.mars_station_task is owner and not owner.done()+ assert calls == ["factory"]+ competing = MarsStore(service.store.path)+ with pytest.raises(StationError, match="world_owned_by_another_process"):+ await competing.open()+ finally:+ runtime.ready.set()+ await stop_mars_station(state)++[email protected]("entry", ["boot", "api"])+async def test_stop_during_runtime_initialization_prevents_late_owner(tmp_path, monkeypatch, entry):+ store, _command = await seed_journal(tmp_path, "queued")+ await store.close()+ state, runtime, executor, _calls = setup_state(tmp_path, monkeypatch)+ runtime.ready.clear()+ if entry == "boot":+ schedule_mars_resume(state, tmp_path)+ pending = state.mars_station_startup_task+ else:+ pending = asyncio.create_task(ensure_mars_station(state))+ await asyncio.wait_for(runtime.starting.wait(), 2)+ stopping = asyncio.create_task(stop_mars_station(state))+ await asyncio.sleep(0)+ assert state.mars_station_stopping+ # Readiness never arrives. Stop owns and cancels initialization even when an+ # API caller, rather than deferred boot, triggered the first factory call.+ await asyncio.wait_for(stopping, 1)+ assert not runtime.ready.is_set()+ outcome = (await asyncio.gather(pending, return_exceptions=True))[0]+ assert isinstance(outcome, asyncio.CancelledError)+ assert getattr(state, "mars_station", None) is None+ assert state.mars_station_task is None+ assert state.mars_station_startup_task is None+ assert state.mars_station_initialization_task is None+ assert executor.dispatches == []+ schedule_mars_resume(state, tmp_path)+ assert state.mars_station_startup_task is None+ with pytest.raises(HTTPException, match="mars_station_stopped"):+ await ensure_mars_station(state)+ # Neither late initialization nor stop leaves the durable owner's file lock held.+ reopened = MarsStore(tmp_path / "mars" / "ordinary.db")+ await reopened.open()+ await reopened.close()+++async def test_canceled_http_waiter_preserves_shared_initialization(tmp_path, monkeypatch):+ state, runtime, executor, calls = setup_state(tmp_path, monkeypatch)+ runtime.ready.clear()+ first = asyncio.create_task(ensure_mars_station(state))+ await asyncio.wait_for(runtime.starting.wait(), 2)+ initialization = state.mars_station_initialization_task+ second = asyncio.create_task(ensure_mars_station(state))+ await asyncio.sleep(0)+ try:+ first.cancel()+ with pytest.raises(asyncio.CancelledError):+ await first+ assert not initialization.done()+ assert state.mars_station_initialization_task is initialization+ runtime.ready.set()+ service = await asyncio.wait_for(second, 2)+ assert service is state.mars_station+ assert calls == ["factory"]+ assert executor.dispatches == []+ assert await ensure_mars_station(state) is service+ finally:+ await stop_mars_station(state)+ await asyncio.gather(first, second, return_exceptions=True)+++async def test_initialization_deadline_is_shared_and_retryable(tmp_path, monkeypatch, caplog):+ import jarvis.ui.web.mars_routes as routes++ monkeypatch.setattr(routes, "_INITIALIZATION_TIMEOUT_S", 0.02)+ state, runtime, _executor, calls = setup_state(tmp_path, monkeypatch)+ runtime.ready.clear()+ first = asyncio.create_task(ensure_mars_station(state))+ second = asyncio.create_task(ensure_mars_station(state))+ outcomes = await asyncio.wait_for(asyncio.gather(first, second, return_exceptions=True), 1)+ assert all(isinstance(outcome, HTTPException) for outcome in outcomes)+ assert "TimeoutError" in caplog.text+ assert calls == ["factory"]+ assert getattr(state, "mars_station", None) is None+ assert state.mars_station_initialization_task.done()+ monkeypatch.setattr(routes, "_INITIALIZATION_TIMEOUT_S", 2.0)+ runtime.ready.set()+ try:+ # Existing runtime ensure_started is retryable; no second runtime is built.+ service = await ensure_mars_station(state)+ assert service is state.mars_station+ assert calls == ["factory"]+ finally:+ await stop_mars_station(state)+++async def test_cancellation_ignoring_startup_cannot_publish_after_stop(tmp_path, monkeypatch):+ import jarvis.ui.web.mars_routes as routes++ state, runtime, executor, _calls = setup_state(tmp_path, monkeypatch)+ runtime.ready.clear()++ async def reluctant_start():+ runtime.starting.set()+ try:+ await runtime.ready.wait()+ except asyncio.CancelledError:+ # Test-only misbehaving collaborator. Production stop must remain+ # bounded and must fence this task even if it later finishes.+ await runtime.ready.wait()++ runtime.ensure_started = reluctant_start+ monkeypatch.setattr(routes, "_INITIALIZATION_STOP_TIMEOUT_S", 0.02)+ pending = asyncio.create_task(ensure_mars_station(state))+ await asyncio.wait_for(runtime.starting.wait(), 2)+ try:+ with pytest.raises(TimeoutError, match="mars_station_shutdown_timeout"):+ await asyncio.wait_for(stop_mars_station(state), 1)+ assert state.mars_station_stopping+ assert not state.mars_station_initialization_task.done()+ runtime.ready.set()+ with pytest.raises(HTTPException):+ await asyncio.wait_for(pending, 1)+ assert getattr(state, "mars_station", None) is None+ assert executor.dispatches == []+ assert not (tmp_path / "mars").exists()+ finally:+ runtime.ready.set()+ await stop_mars_station(state)+ await asyncio.gather(pending, return_exceptions=True)+++async def test_server_stop_finishes_independent_cleanup_after_mars_timeout(tmp_path, monkeypatch):+ import jarvis.clis.shared as cli_shared+ import jarvis.codex_app_server as codex_servers+ import jarvis.marketplace.plugin_shared as plugin_shared+ import jarvis.ui.web.mars_routes as routes+ from jarvis.ui.web.server import WebServer++ state, runtime, executor, _calls = setup_state(tmp_path, monkeypatch)+ runtime.ready.clear()+ cleaned = []++ async def reluctant_start():+ runtime.starting.set()+ try:+ await runtime.ready.wait()+ except asyncio.CancelledError:+ # This misbehaving fixture stays unresolved throughout server.stop().+ await runtime.ready.wait()++ def sync_cleanup(name):+ return lambda *_args, **_kwargs: cleaned.append(name)++ def async_cleanup(name):+ async def action(*_args, **_kwargs):+ cleaned.append(name)++ return action++ runtime.ensure_started = reluctant_start+ runtime.close = async_cleanup("society-runtime")+ monkeypatch.setattr(routes, "_INITIALIZATION_STOP_TIMEOUT_S", 0.02)+ monkeypatch.setattr(cli_shared, "set_active_registry", sync_cleanup("cli-registry"))+ monkeypatch.setattr(+ plugin_shared, "set_active_plugin_registry", sync_cleanup("plugin-registry-handle")+ )+ monkeypatch.setattr(+ codex_servers, "close_shared_codex_app_servers", async_cleanup("codex-servers")+ )+ pending = asyncio.create_task(ensure_mars_station(state))+ await asyncio.wait_for(runtime.starting.wait(), 2)++ # Bypass boot composition only: the entire production WebServer.stop body+ # runs with explicit test-only resource handles and the real Mars lifecycle.+ server = WebServer.__new__(WebServer)+ server.app = SimpleNamespace(state=state)+ for name in (+ "_board_aggregator_task",+ "_realtime_warm_task",+ "_bio_scheduler",+ "_board_evaluator",+ "_board_aggregator",+ "_task_scheduler",+ "_task_cancel_token",+ "_task_scheduler_task",+ "_task_store",+ ):+ setattr(server, name, None)+ server._mic_level_sessions = {"fixture-session"}+ server._stop_mic_level_bridge = sync_cleanup("mic-bridge")+ server._stop_marketplace_refresh_scheduler = async_cleanup("marketplace-refresh")+ server._stop_local_models_health_monitor = async_cleanup("local-model-health")+ server._stop_local_models_autostart = async_cleanup("local-model-autostart")+ server._skill_registry = SimpleNamespace(stop_watcher=sync_cleanup("skill-watcher"))+ server._doc_registry = SimpleNamespace(close=sync_cleanup("doc-watcher"))+ server._plugin_registry = SimpleNamespace(stop=async_cleanup("plugins"))+ server._pty = SimpleNamespace(close_all=sync_cleanup("pty"))+ server._mission_tool_approvals = SimpleNamespace(deny_all=async_cleanup("mission-approvals"))+ state.agent_chat = SimpleNamespace(cancel_all=async_cleanup("chat"))+ state.mission_manager = SimpleNamespace(stop=async_cleanup("missions"))++ browser_started = asyncio.Event()++ async def prepare_browser():+ browser_started.set()+ try:+ await asyncio.Event().wait()+ finally:+ cleaned.append("browser-prepare")++ server._browser_prepare_task = asyncio.create_task(prepare_browser())+ await browser_started.wait()+ server_exit = asyncio.Event()++ class FixtureUvicorn:+ @property+ def should_exit(self):+ return server_exit.is_set()++ @should_exit.setter+ def should_exit(self, value):+ if value:+ cleaned.append("uvicorn-exit")+ server_exit.set()++ uvicorn = server._server = FixtureUvicorn()+ serving = server._serve_task = asyncio.create_task(server_exit.wait())+ try:+ with pytest.raises(+ RuntimeError, match=r"mars_station_shutdown_incomplete \(TimeoutError\)"+ ):+ await asyncio.wait_for(server.stop(), 2)+ assert {+ "browser-prepare",+ "society-runtime",+ "chat",+ "marketplace-refresh",+ "local-model-health",+ "local-model-autostart",+ "skill-watcher",+ "doc-watcher",+ "plugins",+ "pty",+ "mission-approvals",+ "missions",+ "uvicorn-exit",+ "codex-servers",+ } <= set(cleaned)+ assert server._browser_prepare_task is None+ assert server._plugin_registry is None+ assert server._server is server._serve_task is None+ assert uvicorn.should_exit and serving.done()+ assert state.mars_station_stopping+ assert not runtime.ready.is_set()+ assert not state.mars_station_initialization_task.done()+ runtime.ready.set()+ with pytest.raises(HTTPException):+ await asyncio.wait_for(pending, 1)+ assert getattr(state, "mars_station", None) is None+ assert executor.dispatches == []+ finally:+ runtime.ready.set()+ server_exit.set()+ await stop_mars_station(state)+ await asyncio.gather(pending, serving, return_exceptions=True)+++async def test_stop_joins_inspection_before_closing_journal(tmp_path, monkeypatch):+ store, command = await seed_journal(tmp_path, "active")+ await store.close()+ state, _runtime, executor, _calls = setup_state(tmp_path, monkeypatch)+ executor.inspection_gate.clear()+ schedule_mars_resume(state, tmp_path)+ await state.mars_station_startup_task+ owner = state.mars_station_task+ await asyncio.wait_for(executor.inspection_started.wait(), 2)+ await stop_mars_station(state)+ assert owner.done()+ assert executor.dispatches == []+ reopened = MarsStore(tmp_path / "mars" / "ordinary.db")+ try:+ await reopened.open()+ record = await reopened.get(command.command_id)+ assert record.state is CommandState.INTERRUPTED+ assert record.result_ref is None+ finally:+ await reopened.close()+++async def test_recovery_errors_log_only_exception_type(tmp_path, caplog):+ store, _command = await seed_journal(tmp_path, "queued")+ await store.close()++ def failing_factory():+ raise ValueError("PRIVATE-DRAFT-OR-PROVIDER-BODY")++ state = State({"society_factory": failing_factory})+ schedule_mars_resume(state, tmp_path)+ await state.mars_station_startup_task+ await stop_mars_station(state)+ assert "ValueError" in caplog.text+ assert "PRIVATE-DRAFT-OR-PROVIDER-BODY" not in caplog.text+ assert getattr(state, "mars_station", None) is None+++async def child_recover(data_dir: Path):+ import jarvis.society.mars.ordinary as ordinary++ seed = json.loads((data_dir / "seed.json").read_text("utf-8"))+ runtime = FixtureRuntime(data_dir)+ executor = FixtureExecutor(runtime)+ ordinary.OrdinaryStationExecutor = lambda _runtime: executor+ state = State({"society_factory": lambda: runtime})+ try:+ schedule_mars_resume(state, data_dir)+ await state.mars_station_startup_task+ record = await wait_terminal(state.mars_station, seed["command_id"])+ result = record.model_dump(mode="json")+ result.update(dispatches=executor.dispatches, inspections=executor.inspections)+ (data_dir / "recovered.json").write_text(json.dumps(result), "utf-8")+ finally:+ await stop_mars_station(state)++[email protected]("checkpoint", ["queued", "active", "completed"])+def test_abrupt_process_exit_recovers_without_http_clients(tmp_path, checkpoint):+ def child(*args):+ result = subprocess.run(+ [sys.executable, str(Path(__file__).resolve()), *args, str(tmp_path)],+ capture_output=True,+ text=True,+ encoding="utf-8",+ errors="replace",+ creationflags=NO_WINDOW_CREATIONFLAGS,+ timeout=25,+ check=False,+ )+ assert result.returncode == 0, result.stderr++ child("seed", checkpoint)+ child("recover")+ seed = json.loads((tmp_path / "seed.json").read_text("utf-8"))+ recovered = json.loads((tmp_path / "recovered.json").read_text("utf-8"))+ assert recovered["command_id"] == seed["command_id"]+ assert recovered["trace_id"] == seed["trace_id"]+ assert recovered["state"] == "completed"+ assert recovered["result_ref"] == f"fixture-result:{seed['command_id']}"+ if checkpoint == "queued":+ assert recovered["dispatches"] == [seed["command_id"]]+ assert recovered["inspections"] == []+ elif checkpoint == "active":+ assert recovered["dispatches"] == []+ assert recovered["inspections"] == [seed["command_id"]]+ assert recovered["fence"] > seed["fence"]+ assert recovered["task_ref"] == seed["task_ref"]+ else:+ assert recovered["dispatches"] == recovered["inspections"] == []+ assert recovered["task_ref"] == seed["task_ref"]+++if __name__ == "__main__":+ child_dir = Path(sys.argv[-1])+ if sys.argv[1] == "seed":++ async def seed_and_exit():+ _store, record = await seed_journal(child_dir, sys.argv[2])+ (child_dir / "seed.json").write_text(record.model_dump_json(), "utf-8")+ # Model an abrupt owner process exit after the SQLite commit, with+ # no service.close(), connection close, or owner-lock cleanup.+ os._exit(0)++ asyncio.run(seed_and_exit())+ else:+ asyncio.run(child_recover(child_dir))diff --git a/tests/contract/test_mars_rover_http.py b/tests/contract/test_mars_rover_http.pynew file mode 100644index 0000000000..180ee0eed6--- /dev/null+++ b/tests/contract/test_mars_rover_http.py@@ -0,0 +1,143 @@+"""Rover HTTP authority, private validation and durable action replay."""++from __future__ import annotations++import asyncio++import pytest++from jarvis.ui.web.mars_routes import ensure_mars_navigation++from .test_mars_navigation_http import BASE, HEADERS, PREFIX+from .test_mars_navigation_http import world as world++pytestmark = pytest.mark.no_auto_web_auth++[email protected]("action", ["reserve", "board", "travel", "cancel", "exit"])+ "headers,status",+ [({"Origin": BASE}, 401), ({**HEADERS, "Origin": "https://foreign.invalid"}, 403)],+)+async def test_rover_authentication_precedes_owner_creation(world, action, headers, status):+ suffix = "" if action == "reserve" else f"/unknown/{action}"+ payload = {"request_id": "attempt"}+ if action == "reserve":+ payload["vehicle_id"] = "outpost-rover"+ if action == "travel":+ payload["destination_dock_id"] = "outpost-b"+ async with world.client() as client:+ response = await client.post(+ f"{PREFIX}/agents/one/rides{suffix}", headers=headers, json=payload+ )+ assert response.status_code == status+ assert world.calls == []+ assert not world.runtime.store.path.exists()++[email protected]("action", ["reserve", "board", "travel", "cancel", "exit"])+async def test_rejected_rover_input_never_echoes_private_data(world, action, caplog):+ private = "sk-proj-" + "B7" * 20+ suffix = "" if action == "reserve" else f"/unknown/{action}"+ async with world.client() as client:+ response = await client.post(+ f"{PREFIX}/agents/one/rides{suffix}",+ headers=HEADERS,+ json={"request_id": "attempt", private: private},+ )+ assert response.status_code == 422+ assert response.json() == {"detail": {"reason": "invalid_rover_request"}}+ assert private not in response.text + caplog.text+ assert world.calls == []+++async def test_rover_uses_real_agent_and_idempotent_reservation_without_task_dispatch(world):+ service = await ensure_mars_navigation(world.app.state)+ task = world.app.state.mars_navigation_task+ task.cancel()+ await asyncio.gather(task, return_exceptions=True)+ payload = {"request_id": "reserve-http", "vehicle_id": "outpost-rover"}+ async with world.client() as client:+ rejected = await client.post(+ f"{PREFIX}/agents/fabricated/rides", headers=HEADERS, json=payload+ )+ assert rejected.status_code == 403+ first = await client.post(f"{PREFIX}/agents/one/rides", headers=HEADERS, json=payload)+ assert first.status_code == 200, first.text+ second = await client.post(f"{PREFIX}/agents/one/rides", headers=HEADERS, json=payload)+ assert second.status_code == 200+ assert first.json()["ride_id"] == second.json()["ride_id"]+ ride_id = first.json()["ride_id"]+ early = await client.post(+ f"{PREFIX}/agents/one/rides/{ride_id}/board",+ headers=HEADERS,+ json={"request_id": "too-early"},+ )+ assert early.status_code == 409+ other = await client.post(+ f"{PREFIX}/agents/two/rides/{ride_id}/cancel",+ headers=HEADERS,+ json={"request_id": "wrong-actor"},+ )+ assert other.status_code in (403, 404)+ cancel = await client.post(+ f"{PREFIX}/agents/one/rides/{ride_id}/cancel",+ headers=HEADERS,+ json={"request_id": "cancel"},+ )+ assert cancel.status_code == 200+ assert cancel.json()["state"] == "canceled"+ assert (await service.snapshot()).rides[0].ride_id == ride_id+ assert world.executor.dispatched == []+++async def test_canonical_outpost_board_travel_exit_and_retry_through_authenticated_http(world):+ service = await ensure_mars_navigation(world.app.state)+ task = world.app.state.mars_navigation_task+ task.cancel()+ await asyncio.gather(task, return_exceptions=True)+ now = [service.store.clock()]+ service.store.clock = lambda: now[0]+ async with world.client() as client:++ async def action(name, payload, ride_id=None):+ suffix = "" if name == "reserve" else f"/{ride_id}/{name}"+ response = await client.post(+ f"{PREFIX}/agents/one/rides{suffix}", headers=HEADERS, json=payload+ )+ assert response.status_code == 200, response.text+ return response.json()++ async def wait_for(state):+ for _ in range(120):+ now[0] += 500+ await service.advance()+ response = await client.get(f"{PREFIX}/navigation/snapshot", headers=HEADERS)+ assert response.status_code == 200+ snapshot = response.json()+ if snapshot["rides"][0]["state"] == state:+ return snapshot+ pytest.fail(f"Rover failed to reach {state}")++ ride = await action(+ "reserve", {"request_id": "canonical-reserve", "vehicle_id": "outpost-rover"}+ )+ ride_id = ride["ride_id"]+ ready = await wait_for("ready_to_board")+ assert ready["commands"][0]["current_node"] == "rover-a-board"+ boarded = await action("board", {"request_id": "canonical-board"}, ride_id)+ assert boarded["attached"]+ travel = {"request_id": "canonical-travel", "destination_dock_id": "outpost-b"}+ await action("travel", travel, ride_id)+ arrived = await wait_for("arrived")+ assert arrived["vehicles"][0]["current_node"] == "rover-b-dock"+ assert all(body["actor"]["kind"] == "vehicle" for body in arrived["occupancies"])+ result = await action("exit", {"request_id": "canonical-exit"}, ride_id)+ assert result["state"] == "completed" and not result["attached"]+ replay = await action("travel", travel, ride_id)+ assert replay["state"] == "completed"+ snapshot = (await client.get(f"{PREFIX}/navigation/snapshot", headers=HEADERS)).json()+ assert snapshot["vehicles"][0]["ride_id"] is None+ assert snapshot["commands"][0]["current_node"] == "rover-b-exit"+ assert len(snapshot["rides"]) == 1+ assert world.executor.dispatched == []diff --git a/tests/contract/test_mars_rover_parity.py b/tests/contract/test_mars_rover_parity.pynew file mode 100644index 0000000000..0d16ce9aa0--- /dev/null+++ b/tests/contract/test_mars_rover_parity.py@@ -0,0 +1,87 @@+"""Rover states agree across SQL, Python, HTTP and localized client controls."""++from __future__ import annotations++import json+import re+import sqlite3+from pathlib import Path++import pytest+from click.testing import CliRunner+from fastapi import FastAPI++from jarvis.cli_ctl.dynamic import build_api_group+from jarvis.society.mars.navigation_models import RideState+from jarvis.society.mars.navigation_store import _SCHEMA+from jarvis.ui.web.mars_routes import router++ROOT = Path(__file__).resolve().parents[2]+++def test_ride_state_vocabulary_matches_every_boundary():+ states = {state.value for state in RideState}+ with sqlite3.connect(":memory:") as conn:+ conn.executescript(_SCHEMA)+ for state in states:+ conn.execute(+ "INSERT INTO rover_rides(ride_id,agent_id,vehicle_id,state,record) "+ "VALUES(?,?,?,?,?)",+ (state, "agent", "vehicle", state, "{}"),+ )+ with pytest.raises(sqlite3.IntegrityError):+ conn.execute(+ "INSERT INTO rover_rides(ride_id,agent_id,vehicle_id,state,record) "+ "VALUES(?,?,?,?,?)",+ ("invalid", "agent", "vehicle", "animation_completed", "{}"),+ )+ app = FastAPI()+ app.include_router(router)+ assert set(app.openapi()["components"]["schemas"]["RideState"]["enum"]) == states+ source = (+ ROOT / "jarvis/ui/web/frontend/src/components/society/mars/navigationApi.ts"+ ).read_text("utf-8")+ declaration = re.search(r"RIDE_STATES = \[(.*?)\] as const", source)+ assert declaration is not None+ assert set(re.findall(r'"([a-z_]+)"', declaration.group(1))) == states+ for locale in ("en", "de", "es"):+ messages = json.loads(+ (ROOT / f"jarvis/ui/web/frontend/src/i18n/locales/society/{locale}.json").read_text(+ "utf-8"+ )+ )["society"]["mars"]+ assert all(messages[f"rover_state_{state}"] for state in states)+ assert messages["rover_scope"] and messages["rover_uncertain"]+++def test_every_rover_action_is_discoverable_and_correctly_scoped_from_cli():+ app = FastAPI()+ app.include_router(router)+ calls = []++ def run(method, path, params, body, **kwargs):+ calls.append((method, path, body))+ return {"ok": True}++ cli = build_api_group(app.openapi(), run)+ for action in ("reserve", "board", "travel", "cancel", "exit"):+ payload = {"request_id": "same-attempt"}+ if action == "reserve":+ payload["vehicle_id"] = "outpost-rover"+ if action == "travel":+ payload["destination_dock_id"] = "outpost-b"+ args = [+ "mars",+ f"{action}-mars-rover",+ "--agent_id",+ "one",+ "--json-body",+ json.dumps(payload),+ "--yes",+ ]+ if action != "reserve":+ args.extend(["--ride_id", "ride-one"])+ result = CliRunner().invoke(cli, args)+ assert result.exit_code == 0, result.output+ suffix = "" if action == "reserve" else f"/ride-one/{action}"+ assert calls[-1] == ("post", "/api/society/mars/agents/one/rides" + suffix, payload)diff --git a/tests/contract/test_mars_stations.py b/tests/contract/test_mars_stations.pynew file mode 100644index 0000000000..7b2f457dc8--- /dev/null+++ b/tests/contract/test_mars_stations.py@@ -0,0 +1,111 @@+"""Portable station boundary contract using a labeled test-only executor.++This proves renderer independence and durable command semantics, not a real+provider journey, desktop-close persistence, or availability on untested hardware.+"""++from __future__ import annotations++import ast+import json+import re+from pathlib import Path++from fastapi import FastAPI++from jarvis.core.protocols import MarsStationExecutor+from jarvis.society.mars.models import CommandState, StationCommand+from jarvis.society.mars.service import MarsStationService+from jarvis.society.mars.store import MarsStore+++class TestOnlyExecutor:+ """Deterministic fixture behind exactly the production protocol boundary."""++ __test__ = False++ def __init__(self):+ self.accepted = []++ async def authorize(self, *, agent_id: str, capability_id: str) -> None:+ assert agent_id == "fixture-agent" and capability_id == "communication-draft"++ async def dispatch(self, *, agent_id: str, command_id: str, trace_id: str, draft: str) -> dict:+ self.accepted.append(command_id)+ return {"state": "active", "task_ref": "fixture-task:one"}++ async def inspect(+ self, *, agent_id: str, command_id: str, trace_id: str, task_ref: str | None+ ) -> dict:+ assert task_ref == "fixture-task:one"+ return {"state": "completed", "task_ref": task_ref, "result_ref": "fixture-result:one"}++ async def cancel(+ self, *, agent_id: str, command_id: str, trace_id: str, task_ref: str | None+ ) -> dict:+ return {"state": "canceled", "task_ref": task_ref}+++async def test_station_protocol_runs_without_renderer_and_replays_result(tmp_path):+ executor: MarsStationExecutor = TestOnlyExecutor()+ service = MarsStationService(MarsStore(tmp_path / "mars.db"), executor)+ try:+ command = StationCommand(+ request_id="fixture-request", draft="A test-only communication draft."+ )+ created = await service.submit("fixture-agent", command)+ # One claim/dispatch step, then inspection. The background wake may also run;+ # duplicate reconcile calls still cannot duplicate the trusted dispatch.+ await service.reconcile()+ await service.reconcile()+ snapshot = await service.snapshot()+ assert snapshot.commands[0].command_id == created.command_id+ assert snapshot.commands[0].state is CommandState.COMPLETED+ assert snapshot.commands[0].result_ref == "fixture-result:one"+ assert executor.accepted == [created.command_id]+ await service.close()+ await service.start()+ assert (await service.snapshot()).commands[0].result_ref == "fixture-result:one"+ finally:+ await service.close()+++def test_station_state_vocabulary_matches_sql_and_no_graphics_imports():+ root = Path(__file__).parents[2] / "jarvis" / "society" / "mars"+ sql = (root / "schema.sql").read_text("utf-8")+ for state in CommandState:+ assert f"'{state.value}'" in sql+ for name in ("__init__.py", "models.py", "store.py", "service.py"):+ tree = ast.parse((root / name).read_text("utf-8"))+ modules = []+ for node in ast.walk(tree):+ if isinstance(node, ast.Import):+ modules.extend(alias.name for alias in node.names)+ elif isinstance(node, ast.ImportFrom) and node.module:+ modules.append(node.module)+ assert not any(+ module.startswith(("bpy", "OpenGL", "webview", "pygame", "three")) for module in modules+ )+++def test_state_contract_matches_all_five_layers_and_localized_ui():+ from jarvis.ui.web.mars_routes import router++ root = Path(__file__).parents[2]+ states = {state.value for state in CommandState}+ sql = (root / "jarvis/society/mars/schema.sql").read_text("utf-8")+ checks = re.findall(r"CHECK\s*\(\s*state\s+IN\s*\(([^)]+)\)", sql, re.I)+ assert checks+ assert all(set(re.findall(r"'([^']+)'", check)) == states for check in checks)+ app = FastAPI()+ app.include_router(router)+ schemas = app.openapi()["components"]["schemas"]+ assert set(schemas["CommandState"]["enum"]) == states+ assert "draft" not in schemas["CommandRecord"]["properties"]+ frontend = root / "jarvis/ui/web/frontend/src"+ source = (frontend / "components/society/mars/api.ts").read_text("utf-8")+ block = re.search(r"COMMAND_STATES\s*=\s*\[([^]]+)\]", source)+ assert block and set(re.findall(r'"([^"]+)"', block[1])) == states+ for locale in ("en", "de", "es"):+ labels = json.loads((frontend / f"i18n/locales/society/{locale}.json").read_text("utf-8"))+ assert all(labels["society"]["mars"].get(f"state_{state}") for state in states)diff --git a/tests/contract/test_routine_chats.py b/tests/contract/test_routine_chats.pynew file mode 100644index 0000000000..df60ec3271--- /dev/null+++ b/tests/contract/test_routine_chats.py@@ -0,0 +1,146 @@+"""Background runs keep identity, persistence and cancellation separate from chat."""++import asyncio++import pytest++from jarvis.agent_chat.store import AgentChatStore+from jarvis.society.routine_runner import run_owned_routine+from jarvis.society.routines import build_task_spec+from jarvis.tasks.runner import _owner_blocks_fallback+from jarvis.tasks.store import TaskStore+from tests.contract.test_society_continuity import world as world+++async def test_persisted_run_links_survive_reopening_without_loading_main_chat(world, tmp_path):+ runtime, service, main, _ = world+ store = TaskStore(tmp_path / "tasks.db")+ await store.init()+ runtime.task_services = lambda: (store, None)+ agent = await runtime.roster.get("mailbox")+ spec = build_task_spec(agent, title="Inbox", prompt="Read mail", schedule={"kind": "every"})+ task_id = str(await store.insert(spec))+ try:+ await run_owned_routine(runtime, task_id, spec.tags, spec.action.prompt)+ await run_owned_routine(runtime, task_id, spec.tags, spec.action.prompt)+ row = await store.get(task_id)+ links = [step["payload"]["session_id"] for step in row["steps"]]+ assert len(set(links)) == 2+ reopened = AgentChatStore(tmp_path / "chat.db")+ try:+ for sid in links:+ session = reopened.get_session(sid)+ assert session.permission_mode == "bypass"+ assert session.provider == main.provider+ assert session.cwd == main.cwd+ assert reopened.list_events(sid)[-1]["kind"] == "turn_finished"+ assert reopened.list_events(main.session_id) == []+ assert reopened.get_session(main.session_id).permission_mode == main.permission_mode+ finally:+ reopened.close()+ finally:+ await store.close()+++async def test_busy_main_chat_queues_routine_without_mixing_transcripts(world, monkeypatch):+ runtime, service, main, brain = world+ started = asyncio.Event()+ release = asyncio.Event()+ generate = brain.generate++ async def respond(text, **kwargs):+ if text == "Main conversation":+ started.set()+ await release.wait()+ return await generate(text, **kwargs)++ monkeypatch.setattr(brain, "generate", respond)+ await service.send(main.session_id, "Main conversation")+ await asyncio.wait_for(started.wait(), 2)+ created = asyncio.Event()+ create_session = service.store.create_session++ def record_session(**kwargs):+ session = create_session(**kwargs)+ created.set()+ return session++ monkeypatch.setattr(service.store, "create_session", record_session)+ routine = asyncio.create_task(+ run_owned_routine(runtime, "digest", ("society", "agent:mailbox"), "Read mail")+ )+ try:+ await asyncio.wait_for(created.wait(), 2)+ assert service.is_running(main.session_id)+ release.set()+ assert await asyncio.wait_for(routine, 3) == brain.reply+ messages = [+ e for e in service.store.list_events(main.session_id) if e["kind"] == "user_message"+ ]+ assert [e["payload"]["text"] for e in messages] == ["Main conversation"]+ finally:+ release.set()+ if not routine.done():+ routine.cancel()+ await asyncio.gather(routine, return_exceptions=True)+ await service.cancel(main.session_id)+++async def test_failed_run_stays_in_its_chat_and_cannot_fall_back(world, monkeypatch):+ runtime, service, main, brain = world++ async def fail(*args, **kwargs):+ raise RuntimeError("Synthetic provider outage")++ monkeypatch.setattr(brain, "generate", fail)+ with pytest.raises(RuntimeError, match="The routine chat failed") as failure:+ await run_owned_routine(runtime, "digest", ("society", "agent:mailbox"), "Read mail")+ assert _owner_blocks_fallback(failure.value)+ runs = [+ s for s in service.store.list_sessions(surface="society") if ":routine:" in s.session_id+ ]+ assert len(runs) == 1+ assert service.store.list_events(runs[0].session_id)[-1]["payload"]["status"] == "error"+ assert service.store.list_events(main.session_id) == []++[email protected]("via_chat", [False, True])+async def test_cancelling_routine_preserves_main_chat(world, monkeypatch, via_chat):+ runtime, service, main, brain = world+ started = asyncio.Event()+ release = asyncio.Event()++ async def hold(*args, **kwargs):+ started.set()+ await release.wait()+ return "Finished"++ monkeypatch.setattr(brain, "generate", hold)+ routine = asyncio.create_task(+ run_owned_routine(runtime, "digest", ("society", "agent:mailbox"), "Read mail")+ )+ try:+ await asyncio.wait_for(started.wait(), 2)+ if via_chat:+ session = next(+ s+ for s in service.store.list_sessions(surface="society")+ if ":routine:" in s.session_id+ )+ await service.cancel(session.session_id)+ else:+ routine.cancel()+ with pytest.raises(asyncio.CancelledError):+ await routine+ runs = [+ s for s in service.store.list_sessions(surface="society") if ":routine:" in s.session_id+ ]+ assert len(runs) == 1+ assert not service.is_running(runs[0].session_id)+ assert service.store.list_events(runs[0].session_id)[-1]["payload"]["status"] == "cancelled"+ assert service.store.list_events(main.session_id) == []+ finally:+ release.set()+ if not routine.done():+ routine.cancel()+ await asyncio.gather(routine, return_exceptions=True)diff --git a/tests/contract/test_society_communication.py b/tests/contract/test_society_communication.pynew file mode 100644index 0000000000..4db94dd743--- /dev/null+++ b/tests/contract/test_society_communication.py@@ -0,0 +1,391 @@+"""End-to-end communication contracts using SQLite and the real scheduler.++No provider, native API, microphone or display is needed on any supported OS.+"""++from __future__ import annotations++import asyncio+import json+from types import SimpleNamespace+from uuid import uuid4++import pytest++from jarvis.agent_chat.service import AgentChatService+from jarvis.agent_chat.store import AgentChatStore+from jarvis.plugins.tool.delegate_to_agent import DelegateToAgentTool+from jarvis.plugins.tool.message_agent import LeadMessageAgentTool+from jarvis.society.agent_tools import MessageAgentTool+from jarvis.society.chat_binding import frame_assignment, frame_incoming, make_deliver_hook+from jarvis.society.communication import reply_policy+from jarvis.society.delivery import IncomingMessage, incoming_context+from jarvis.society.events import MsgType, SocietyEnvelope+from jarvis.society.runtime import SocietyRuntime+++class Chat:+ receive_message = AgentChatService.receive_message+ message_status = AgentChatService.message_status++ def __init__(self, path):+ self.store = AgentChatStore(path)+ self.queues = {}+ self.sent = []+ self.notices = []+ self.contexts = []++ async def _emit(self, session_id, event):+ self.store.append_event(session_id, event)++ def is_running(self, session_id):+ return False++ def subscribe(self, session_id):+ queue = asyncio.Queue()+ self.queues[session_id] = queue+ return queue++ def unsubscribe(self, session_id, queue):+ self.queues.pop(session_id, None)++ async def send(self, session_id, text, **kwargs):+ self.sent.append((session_id, text))+ self.contexts.append(incoming_context.get())+ return f"turn-{len(self.sent)}"++ async def post_notice(self, session_id, payload):+ self.notices.append(payload)+++async def world(tmp_path):+ chat = Chat(tmp_path / "chat.db")+ cfg = SimpleNamespace(memory=SimpleNamespace(data_dir=str(tmp_path)))+ published = []+ runtime = SocietyRuntime(+ tmp_path,+ chat_service=lambda: chat,+ cfg=lambda: cfg,+ event_publish=lambda event: (+ published.append(event) if type(event).__name__ == "AnnouncementRequested" else None+ ),+ )+ await runtime.ensure_started()+ await runtime.roster.create(name="Scout", provider="openai")+ await runtime.roster.create(name="Archivist", provider="gemini")+ chat.store.create_session(+ provider="openai",+ model="",+ effort="",+ cwd=str(tmp_path),+ surface="jarvis",+ )+ runtime.set_deliver(make_deliver_hook(lambda: chat, lambda: cfg))+ try:+ yield runtime, chat, published+ finally:+ await runtime.close()+ chat.store.close()+++def ctx():+ return SimpleNamespace(trace_id=uuid4(), config={"output_language": "en"})+++async def send(rt, sender="jarvis", target="scout", **args):+ tool = MessageAgentTool(rt, sender)+ result = await tool.execute({"target": target, "text": "Known test context.", **args}, ctx())+ assert result.success, result.error+ return await rt.store.get_event(result.output["message_id"])+++def completion(text="Measured result.", status="completed", direct_user=False):+ events = [+ {"kind": "assistant_text", "payload": {"text": text}},+ {"kind": "turn_finished", "payload": {"status": status}},+ ]+ return SimpleNamespace(+ turn=SimpleNamespace(direct_user=direct_user, turn_id="t"),+ events_json=json.dumps(events),+ ), events+++async def finish_message(rt, chat, request, **kwargs):+ origin = IncomingMessage(+ message_id=request.event_id,+ sender_id=request.from_agent,+ sender_name=request.from_agent,+ sender_kind="jarvis",+ text=request.text,+ prompt=frame_incoming(request, request.from_agent),+ trace_id=request.trace_id,+ )+ token = incoming_context.set(origin)+ try:+ done, events = completion(**kwargs)+ await rt._complete_message_reply(+ chat.store.get_session(f"society:{request.to_agent}"),+ done,+ events,+ )+ finally:+ incoming_context.reset(token)+++async def test_question_returns_once_and_answer_ends_exchange(world):+ rt, chat, published = world+ request = await send(rt, kind="query")+ assert reply_policy(request) == "always"+ assert "Known test context." in chat.sent[0][1]+ assert "kind 'answer'" in chat.sent[0][1]+ await finish_message(rt, chat, request, text="Navigation and reading succeeded.")+ await finish_message(rt, chat, request, text="Duplicate callback.")+ answers = [+ e for e in await rt.store.events_for_trace(request.trace_id) if e.msg_type is MsgType.ANSWER+ ]+ assert len(answers) == 1+ assert answers[0].parent_event_id == request.event_id+ assert answers[0].text == "Navigation and reading succeeded."+ assert reply_policy(answers[0]) == "none"+ assert "No reply is requested" in frame_incoming(answers[0], "Scout")+ assert len(chat.notices) == len(published) == 1+ refused = await MessageAgentTool(rt, "jarvis").execute(+ {+ "target": "scout",+ "text": "Thanks.",+ "kind": "answer",+ "in_reply_to": answers[0].event_id,+ },+ ctx(),+ )+ assert not refused.success+++async def test_delayed_reply_uses_durable_parent_and_no_duplicate_fallback(world):+ rt, chat, _ = world+ request = await send(rt, kind="query")+ assert incoming_context.get() is None+ result = await MessageAgentTool(rt, "scout").execute(+ {+ "target": "jarvis",+ "text": "Here are the findings.",+ "kind": "answer",+ "in_reply_to": request.event_id,+ },+ ctx(),+ )+ assert result.success+ assert result.output["trace_id"] == request.trace_id+ await finish_message(rt, chat, request)+ answers = [+ e for e in await rt.store.events_for_trace(request.trace_id) if e.msg_type is MsgType.ANSWER+ ]+ assert len(answers) == 1+ wrong = await MessageAgentTool(rt, "archivist").execute(+ {+ "target": "jarvis",+ "text": "Forged reply.",+ "kind": "answer",+ "in_reply_to": request.event_id,+ },+ ctx(),+ )+ assert not wrong.success+++ "policy,status,expected",+ [+ ("none", "completed", 0),+ ("none", "error", 0),+ ("on_error", "completed", 0),+ ("on_error", "error", 1),+ ("always", "completed", 1),+ ("always", "error", 1),+ ],+)+async def test_message_reporting_matrix(world, policy, status, expected):+ rt, chat, published = world+ request = await send(rt, reply_policy=policy)+ await finish_message(rt, chat, request, status=status)+ assert len(chat.notices) == len(published) == expected+ if expected and status == "error":+ replies = await rt.store.events_for_trace(request.trace_id)+ assert replies[-1].payload["reply_status"] == "blocked"+++async def test_direct_user_turn_and_unrelated_parent_never_auto_forward(world):+ rt, chat, published = world+ request = await send(rt, kind="query")+ await finish_message(rt, chat, request, direct_user=True)+ await rt.say(+ from_agent="scout",+ to_agent="jarvis",+ text="Unrelated private conversation.",+ msg_type=MsgType.ANSWER,+ trace_id=request.trace_id,+ parent_event_id="not-the-request",+ )+ assert not published and not chat.notices+++ "policy,status,expected",+ [+ ("none", "done", 0),+ ("none", "blocked", 0),+ ("on_error", "done", 0),+ ("on_error", "blocked", 1),+ ("always", "done", 1),+ ("always", "blocked", 1),+ ],+)+async def test_assignment_reporting_preserves_result_and_releases_slot(+ world, policy, status, expected+):+ rt, chat, published = world+ result = await DelegateToAgentTool(runtime_resolver=lambda: rt).execute(+ {+ "agent": "scout",+ "task": "Verify browser navigation.",+ "context": "Use the agent-owned browser.",+ "completion_criteria": "Record the actual URL and observed navigation result.",+ "reply_policy": policy,+ },+ ctx(),+ )+ assert result.success+ request = await rt.store.get_event(result.output["assignment_id"])+ assert request.payload["reply_policy"] == policy+ assert "agent-owned browser" in request.text+ assert "observed navigation" in frame_assignment(request)+ assert chat.contexts[-1].message_id == request.event_id+ if policy != "always":+ assert "I will let you know" not in result.output["acknowledgement"]+ if status == "blocked":+ reported = await MessageAgentTool(rt, "scout").execute(+ {+ "target": "jarvis",+ "text": "Browser access is unavailable.",+ "kind": "answer",+ "reply_status": "blocked",+ "in_reply_to": request.event_id,+ },+ ctx(),+ )+ assert reported.success+ assert not published # The watcher owns the single completion announcement.+ assert not any(+ chat.store.incoming_message(session.session_id, reported.output["message_id"])+ for session in chat.store.list_sessions(surface="jarvis")+ )+ queue = chat.queues["society:scout"]+ await queue.put({"kind": "assistant_text", "payload": {"text": "Recorded outcome."}})+ await queue.put({"kind": "turn_finished", "payload": {"status": "completed"}})+ watchers = list(rt._watchers)+ await asyncio.wait_for(asyncio.gather(*watchers), timeout=5)+ results = [+ e for e in await rt.store.events_for_trace(request.trace_id) if e.msg_type is MsgType.RESULT+ ]+ assert len(results) == 1 and results[0].payload["status"] == status+ assert rt.scheduler.active_runs("scout") == 0+ assert len(chat.notices) == len(published) == expected+++ "args",+ [+ {"kind": "query", "reply_policy": "none"},+ {"reply_policy": "unknown"},+ {"reply_policy": []},+ {"reply_status": "imagined"},+ {"text": "x" * 8001},+ {"kind": "answer"},+ ],+)+async def test_invalid_contract_does_not_queue_a_message(world, args):+ rt, chat, _ = world+ result = await LeadMessageAgentTool(runtime_resolver=lambda: rt).execute(+ {"target": "scout", "text": "Question.", **args},+ ctx(),+ )+ assert not result.success+ assert not chat.sent+++def test_legacy_defaults_and_serialization():+ assignment = SocietyEnvelope(+ msg_type=MsgType.ASSIGN,+ from_agent="jarvis",+ to_agent="scout",+ trace_id="old",+ )+ assert reply_policy(assignment) == "always"+ query = assignment.model_copy(update={"msg_type": MsgType.QUERY})+ assert reply_policy(query) == "always"+ for policy in ("none", "on_error", "always"):+ original = assignment.model_copy(update={"payload": {"reply_policy": policy}})+ assert (+ reply_policy(SocietyEnvelope.model_validate_json(original.model_dump_json())) == policy+ )+++async def test_real_chat_completion_hook_returns_final_answer(tmp_path, monkeypatch):+ from jarvis.agent_chat import service as service_module+ from jarvis.agent_chat.events import make_event++ async def receiver(handle, prompt, **kwargs):+ await handle.emit(+ make_event(+ "assistant_text",+ {+ "turn_id": handle.turn_id,+ "text": "The measured answer is 42.",+ },+ )+ )+ await handle.emit(+ make_event(+ "turn_finished",+ {+ "turn_id": handle.turn_id,+ "status": "completed",+ },+ )+ )++ async def no_review(runtime):+ # Learning is independent of returning the requested answer.+ return None++ monkeypatch.setattr(service_module, "run_brain_turn", receiver)+ monkeypatch.setattr(SocietyRuntime, "recover_reviews", no_review)+ chat = AgentChatService(AgentChatStore(tmp_path / "chat.db"))+ cfg = SimpleNamespace(memory=SimpleNamespace(data_dir=str(tmp_path)))+ rt = SocietyRuntime(tmp_path, chat_service=lambda: chat, cfg=lambda: cfg)+ await rt.ensure_started()+ await rt.roster.create(name="Scout", provider="openai")+ chat.store.create_session(+ provider="openai",+ model="",+ effort="",+ cwd=str(tmp_path),+ surface="jarvis",+ )+ rt.set_deliver(make_deliver_hook(lambda: chat, lambda: cfg))+ try:+ request = await send(rt, kind="query")+ for _ in range(100):+ rows = await rt.store.events_for_trace(request.trace_id)+ answers = [row for row in rows if row.msg_type is MsgType.ANSWER]+ if answers:+ break+ await asyncio.sleep(0.01)+ assert len(answers) == 1+ assert answers[0].text == "The measured answer is 42."+ assert answers[0].parent_event_id == request.event_id+ finally:+ await chat.cancel_all()+ await rt.close()+ chat.store.close()diff --git a/tests/contract/test_society_continuity.py b/tests/contract/test_society_continuity.pyindex 0db1987f79..3f767350ae 100644--- a/tests/contract/test_society_continuity.py+++ b/tests/contract/test_society_continuity.py@@ -251,7 +251,16 @@ async def test_routine_uses_current_rules_and_memory(world):briefing = kwargs["turn_override"].system_extraassert "Use plain text and never send mail." in briefing and "Cedar" in briefingassert "Prepare drafts only." not in prompt- assert kwargs["conversation_id"] == session.session_id+ routine_session_id = kwargs["conversation_id"]+ assert routine_session_id.startswith(f"{session.session_id}:routine:{spec.id}:")+ assert svc.store.get_session(routine_session_id).permission_mode == "bypass"+ assert all(event["kind"] == "notice" and event["payload"].get("kind") == "memory_updated"+ for event in svc.store.list_events(session.session_id))++ await run_owned_routine(rt, str(spec.id), spec.tags, spec.action.prompt)+ assert brain.calls[-1][1]["conversation_id"] != routine_session_id+ assert all(event["kind"] == "notice" and event["payload"].get("kind") == "memory_updated"+ for event in svc.store.list_events(session.session_id))async def test_routine_update_preserves_id_and_pause_state(tmp_path):diff --git a/tests/fakes/fake_realtime.py b/tests/fakes/fake_realtime.pyindex 2f6efafaf3..d791c3149a 100644--- a/tests/fakes/fake_realtime.py+++ b/tests/fakes/fake_realtime.py@@ -126,6 +126,10 @@ class FakeRealtimeToolBridge:self.transcripts: list[str] = []self.closed = False+ @property+ def has_pending_confirmation(self) -> bool:+ return False+def set_language(self, language: str) -> None:self.languages.append(language)diff --git a/tests/fakes/fake_society_shutdown.py b/tests/fakes/fake_society_shutdown.pynew file mode 100644index 0000000000..d3f17acf55--- /dev/null+++ b/tests/fakes/fake_society_shutdown.py@@ -0,0 +1,62 @@+"""Unrelated server resources for exercising the real Society shutdown path."""++from types import SimpleNamespace++from fastapi import FastAPI++from jarvis.ui.web.server import WebServer+++class RecordingProcessTree:+ """Record containment release while a real child is reaped independently."""++ def __init__(self):+ self.closes = 0++ def close(self):+ self.closes += 1+++def society_shutdown_server(runtime):+ """Skip boot composition, preserving the entire production stop method."""+ cleaned = []++ def sync_cleanup(name):+ return lambda *_args, **_kwargs: cleaned.append(name)++ def async_cleanup(name):+ async def action(*_args, **_kwargs):+ cleaned.append(name)++ return action++ server = WebServer.__new__(WebServer)+ server.app = FastAPI()+ server.app.state.society = runtime+ server.app.state.agent_chat = SimpleNamespace(cancel_all=async_cleanup("chat"))+ for name in (+ "_browser_prepare_task",+ "_board_aggregator_task",+ "_realtime_warm_task",+ "_bio_scheduler",+ "_board_evaluator",+ "_board_aggregator",+ "_task_scheduler",+ "_task_cancel_token",+ "_task_scheduler_task",+ "_task_store",+ "_skill_registry",+ "_doc_registry",+ "_plugin_registry",+ "_server",+ "_serve_task",+ ):+ setattr(server, name, None)+ server._mic_level_sessions = set()+ server._stop_mic_level_bridge = sync_cleanup("mic-bridge")+ server._stop_marketplace_refresh_scheduler = async_cleanup("marketplace-refresh")+ server._stop_local_models_health_monitor = async_cleanup("model-health")+ server._stop_local_models_autostart = async_cleanup("model-autostart")+ server._pty = SimpleNamespace(close_all=sync_cleanup("pty"))+ server._mission_tool_approvals = SimpleNamespace(deny_all=async_cleanup("mission-approvals"))+ return server, cleaneddiff --git a/tests/fakes/voice_surface.py b/tests/fakes/voice_surface.pynew file mode 100644index 0000000000..9b896fa8f4--- /dev/null+++ b/tests/fakes/voice_surface.py@@ -0,0 +1,33 @@+"""A native-surface sink that records the state and level actually rendered."""+++class VoiceSurface:+ def __init__(self):+ self.mode = "idle"+ self.level = 0.0+ self.shown = []++ def show(self, mode="listen"):+ self.mode = mode+ self.shown.append(mode)++ def hide(self):+ self.mode = "hidden"++ def set_level(self, level):+ self.level = level++ def play_animation(self, name):+ pass++ def stop_animation(self, name):+ pass++ def hide_comment(self):+ pass++ def show_comment(self, text, duration_ms=3500):+ pass++ def show_listening_transcript(self, text="", duration_ms=30000):+ passdiff --git a/tests/integration/test_coding_supervision_routine.py b/tests/integration/test_coding_supervision_routine.pyindex 7f2b71c19b..04164b40bf 100644--- a/tests/integration/test_coding_supervision_routine.py+++ b/tests/integration/test_coding_supervision_routine.py@@ -100,8 +100,10 @@ async def test_routine_question_and_result_stay_in_real_owner_chat(rig, tmp_pathmonkeypatch.setattr(runner_brain, "brain_manager", lambda: brain)monkeypatch.setattr(runner_brain, "_agent_secret", lambda *args: "synthetic-test-key")+ routine_session_id = ""+async def idle():- running = service._running.get(owner.session_id)+ running = service._running.get(routine_session_id)if running is not None and running.task is not None:await asyncio.wait_for(asyncio.shield(running.task), timeout=5)@@ -109,6 +111,8 @@ async def test_routine_question_and_result_stay_in_real_owner_chat(rig, tmp_pathanswer = await run_owned_routine(runtime, "routine-proof", ("society", agent_tag(owner.agent_id)), "Inspect the branch")+ routine_session_id = identities[0][0]+ assert routine_session_id.startswith(f"{owner.session_id}:routine:")assert answer == "Assignment started under supervision."await idle()key = runtime.coding_supervision.key(opened)@@ -120,11 +124,12 @@ async def test_routine_question_and_result_stay_in_real_owner_chat(rig, tmp_pathawait runtime.coding_supervision.tick(key)await idle()assert runtime.coding_supervision.rows[key]["state"] == "finished"- assert identities == [(owner.session_id, False)] * 3- events = service.store.list_events(owner.session_id)+ assert identities == [(routine_session_id, False)] * 3+ assert service.store.list_events(owner.session_id) == []+ events = service.store.list_events(routine_session_id)assert len([e for e in events if e["kind"] == "agent_message"]) == 2assert len([e for e in events if e["kind"] == "turn_started"]) == 3finally:- await service.cancel(owner.session_id)+ await service.cancel(routine_session_id)await idle()service.store.close()diff --git a/tests/unit/agent_chat/test_agent_chat_core.py b/tests/unit/agent_chat/test_agent_chat_core.pyindex 6b5bb8e8c5..c0267dc800 100644--- a/tests/unit/agent_chat/test_agent_chat_core.py+++ b/tests/unit/agent_chat/test_agent_chat_core.py@@ -526,7 +526,7 @@ def test_codex_reasoning_start_is_announced():def test_resolve_runner_per_surface(monkeypatch):- """The Jarvis surface is API endpoints only; the agent surface keeps its CLIs."""+ """Jarvis runs API seats through its brain and preserves coding CLI seats."""from jarvis.agent_chat import service as svc_modmonkeypatch.setattr(svc_mod, "_claude_cli_installed", lambda: False)@@ -535,54 +535,63 @@ def test_resolve_runner_per_surface(monkeypatch):assert svc_mod.resolve_runner("ollama", surface="jarvis") == "brain"assert svc_mod.resolve_runner("claude-api") == "api"assert svc_mod.resolve_runner("claude-api", surface="jarvis") == "brain"- # A CLI-only row has no API path, so the surface that dropped its CLI- # seats has no runner for it at all — and never offers it (see- # test_the_jarvis_surface_offers_api_seats_only).- assert svc_mod.resolve_runner("openai-codex", surface="jarvis") == "unknown"- assert svc_mod.resolve_runner("antigravity", surface="jarvis") == "unknown"+ assert svc_mod.resolve_runner("openai-codex", surface="jarvis") == "codex-cli"+ assert svc_mod.resolve_runner("antigravity", surface="jarvis") == "agy-cli"assert svc_mod.resolve_runner("openai-codex", surface="agent") == "codex-cli"assert svc_mod.resolve_runner("antigravity", surface="agent") == "agy-cli"monkeypatch.setattr(svc_mod, "_claude_cli_installed", lambda: True)assert svc_mod.resolve_runner("claude-api") == "claude-cli"- # Even with Claude Code installed: the front page's chat runs the- # Anthropic endpoint, not the subscription seat (maintainer 2026-08-26).- assert svc_mod.resolve_runner("claude-api", surface="jarvis") == "brain"+ assert svc_mod.resolve_runner("claude-api", surface="jarvis") == "claude-cli"+ # API-only surfaces still resolve Claude to the brain with its CLI installed.+ assert svc_mod.resolve_runner("claude-api", surface="local-models") == "brain"+ assert svc_mod.resolve_runner("openai-codex", surface="local-models") == "unknown"assert svc_mod.resolve_runner("no-such-provider", surface="jarvis") == "unknown"-def test_the_jarvis_surface_offers_api_seats_only():- """Every row the front page's chat lists has a brain plugin behind it."""+def test_the_jarvis_surface_offers_api_and_cli_seats():+ """Jarvis shares the IDE's provider seats; API-only surfaces remain filtered."""from jarvis.agent_chat.catalog import PROVIDER_ROWS, offers, rows_forfrom jarvis.agent_chat.runner_api import supports_api_runnerjarvis_ids = [row.id for row in rows_for("jarvis")]- assert jarvis_ids and all(supports_api_runner(pid) for pid in jarvis_ids)- # The CLI-only rows are gone from it and still there for the IDE's chat.+ assert jarvis_ids == [row.id for row in rows_for("agent")]for cli_row in ("openai-codex", "antigravity", "grok-build"):- assert not offers("jarvis", cli_row)+ assert offers("jarvis", cli_row)assert offers("agent", cli_row)+ assert not offers("local-models", cli_row)+ api_ids = [row.id for row in rows_for("local-models")]+ assert api_ids and all(supports_api_runner(pid) for pid in api_ids)assert [row.id for row in rows_for("agent")] == [row.id for row in PROVIDER_ROWS]-def test_a_cli_seat_cannot_be_created_or_patched_onto_the_jarvis_chat(tmp_path):- """The picker does not list them, and the routes refuse them either way."""- import pytest-+def test_cli_seat_creation_follows_the_surface_capability(tmp_path):+ """CLI seats can be created on Jarvis and the IDE, but not API-only surfaces."""from jarvis.agent_chat.service import AgentChatServicefrom jarvis.agent_chat.store import AgentChatStoresvc = AgentChatService(AgentChatStore(":memory:"), default_cwd=lambda: str(tmp_path))+ for surface in ("jarvis", "agent"):+ session = svc.create_session(provider="openai-codex", surface=surface, cwd=str(tmp_path))+ assert (session.provider, session.surface) == ("openai-codex", surface)with pytest.raises(ValueError, match="not offered"):- svc.create_session(provider="openai-codex", surface="jarvis")- # The same row is fine on the surface that has CLI seats.- assert svc.create_session(provider="openai-codex", surface="agent").provider == "openai-codex"+ svc.create_session(provider="openai-codex", surface="local-models")+[email protected]("cli_seats", [True, False])+def test_cli_seat_retirement_follows_the_surface_capability(tmp_path, monkeypatch, cli_seats):+ """Keep supported CLI seats; retain migration coverage for an API-only kit."""+ from dataclasses import replace-def test_an_old_cli_seated_jarvis_chat_moves_to_its_api_twin(tmp_path):- """A chat from before the change keeps its history and gains a working seat."""+ from jarvis.agent_chat import surface_kitsfrom jarvis.agent_chat.service import AgentChatServicefrom jarvis.agent_chat.store import AgentChatStore+ if not cli_seats:+ monkeypatch.setitem(+ surface_kits._KITS,+ "jarvis",+ replace(surface_kits.kit_for("jarvis"), cli_seats=False),+ )store = AgentChatStore(":memory:")# ``gpt-5.2`` is in Codex's own catalog and not in OpenAI's, so it goes.codex = store.create_session(@@ -598,24 +607,28 @@ def test_an_old_cli_seated_jarvis_chat_moves_to_its_api_twin(tmp_path):kept = store.create_session(provider="claude-api", model="claude-opus-5", effort="high", cwd=".", surface="agent")+ history = store.append_event(codex.session_id, make_event("user_message", {"text": "hi"}))before = store.get_session(codex.session_id).updated_msAgentChatService(store, default_cwd=lambda: str(tmp_path))moved = store.get_session(codex.session_id)- assert (moved.provider, moved.model) == ("openai", "")+ assert (moved.provider, moved.model) == (+ ("openai-codex", "gpt-5.2") if cli_seats else ("openai", "")+ )assert (store.get_session(shared.session_id).provider,store.get_session(shared.session_id).model,) == (- "openai",+ "openai-codex" if cli_seats else "openai","gpt-5.5",)# The list order is by updated_ms; a migration must not reshuffle it.assert moved.updated_ms == before- # Claude keeps its row and loses only the model id the API cannot take.+ assert store.list_events(codex.session_id) == [history]+ # Only an API-only kit retires Claude's CLI-specific model id.assert store.get_session(claude.session_id).provider == "claude-api"- assert store.get_session(claude.session_id).model == ""+ assert store.get_session(claude.session_id).model == ("opusplan" if cli_seats else "")# The IDE's chat is untouched.assert store.get_session(kept.session_id).provider == "claude-api"assert store.get_session(kept.session_id).model == "claude-opus-5"diff --git a/tests/unit/agent_chat/test_agent_chat_ladders.py b/tests/unit/agent_chat/test_agent_chat_ladders.pyindex 8e4b54f3ac..4ad70ddf1a 100644--- a/tests/unit/agent_chat/test_agent_chat_ladders.py+++ b/tests/unit/agent_chat/test_agent_chat_ladders.py@@ -9,7 +9,7 @@ from types import SimpleNamespaceimport pytestfrom jarvis.agent_chat import permissions, runner_cli-from jarvis.agent_chat.catalog import CODEX_FALLBACK_MODELS, provider_row+from jarvis.agent_chat.catalog import provider_rowfrom jarvis.agent_chat.runner_cli import (_AgyState,agy_model_args,@@ -27,7 +27,7 @@ from jarvis.plugins.brain._anthropic_base import _is_reasoning_model, reasoning_async def test_agy_cold_chat_resolves_catalog_before_building_command(tmp_path, monkeypatch):seen = []- def catalog():+ def catalog(**kwargs):seen.append("catalog")return []@@ -53,6 +53,50 @@ async def test_agy_cold_chat_resolves_catalog_before_building_command(tmp_path,assert result.error == "stop before process launch"+def test_agy_refreshes_a_cached_fallback_missing_the_scheduled_model(monkeypatch):+ import subprocess+ import time++ monkeypatch.setattr(+ runner_cli,+ "_AGY_CATALOG",+ {+ "at": time.monotonic(),+ "rows": [{"id": "old-model", "efforts": []}],+ },+ )+ monkeypatch.setattr(runner_cli, "agy_argv_prefix", lambda: ["agy"])+ calls = []++ def models(*args, **kwargs):+ calls.append(args)+ return SimpleNamespace(+ stdout=json.dumps(+ {+ "command": {+ "data": {+ "models": [+ {"id": "current-model-low"},+ {"id": "current-model-high"},+ ]+ }+ }+ }+ ).encode()+ )++ monkeypatch.setattr(subprocess, "run", models)+ rows = runner_cli.read_agy_models(required_model="current-model")+ assert agy_model_args("current-model", "high", rows) == [+ "--model",+ "current-model",+ "--effort",+ "high",+ ]+ runner_cli.read_agy_models(required_model="current-model")+ assert len(calls) == 1++def test_every_runner_has_a_ladder_with_its_default_on_it():for runner in ("claude-cli", "codex-cli", "agy-cli", "grok-cli", "api", "jarvis"):ids = permissions.permission_ids(runner)@@ -419,55 +463,27 @@ def test_translate_agy_line_reads_failure_from_result_status():# ------------------------------------------------------------ codex catalog-def test_read_codex_models_reads_the_account_cache(monkeypatch, tmp_path: Path):+def test_read_codex_models_uses_the_executing_cli_not_a_foreign_cache(monkeypatch, tmp_path: Path):home = tmp_path / "codex-home"home.mkdir()(home / "models_cache.json").write_text(- json.dumps(- {- "models": [- {- "slug": "gpt-5.5",- "display_name": "GPT-5.5",- "visibility": "list",- "priority": 3,- "supported_reasoning_levels": [{"effort": "low"}, {"effort": "high"}],- },- {- "slug": "gpt-5.6-terra",- "display_name": "GPT-5.6-Terra",- "visibility": "list",- "priority": 2,- "supported_reasoning_levels": [{"effort": "medium"}, {"effort": "ultra"}],- "upgrade": None,- },- {"slug": "codex-auto-review", "visibility": "hide", "priority": 1},- {- "slug": "gpt-5.4-mini",- "display_name": "GPT-5.4-Mini",- "visibility": "list",- "priority": 9,- "supported_reasoning_levels": [],- "upgrade": {- "model": "gpt-5.6-luna",- "retirement_at": "2026-08-31T19:00:00Z",- },- },- ]- }- ),+ json.dumps({"client_version": "future", "models": [{"slug": "unavailable"}]}),encoding="utf-8",)monkeypatch.setattr(runner_cli, "_account_env", lambda platform: {"CODEX_HOME": str(home)})+ monkeypatch.setattr(runner_cli, "codex_argv_prefix", lambda: ["codex-test"])+ calls = []++ def discover(argv, env, cwd):+ calls.append((argv, env))+ return [{"id": "future-supported-model", "label": "Future", "efforts": ["high"]}]++ monkeypatch.setattr(runner_cli, "discover_codex_models", discover)rows = runner_cli.read_codex_models()- assert rows is not None- assert [r["id"] for r in rows] == ["gpt-5.6-terra", "gpt-5.5", "gpt-5.4-mini"]- assert rows[0]["efforts"] == ["medium", "ultra"]- assert rows[2]["note"] == "retires 2026-08-31"- # No cache -> None, and the catalog's fallback carries the picker.- monkeypatch.setattr(runner_cli, "_account_env", lambda platform: {"CODEX_HOME": str(tmp_path)})- assert runner_cli.read_codex_models() is None- assert CODEX_FALLBACK_MODELS[0].id == "gpt-5.6-sol"+ assert [row["id"] for row in rows] == ["future-supported-model"]+ assert calls == [(["codex-test"], {"CODEX_HOME": str(home)})]+ assert runner_cli.read_codex_models() == rows+ assert len(calls) == 1def test_read_grok_models_reads_the_account_cache(monkeypatch, tmp_path: Path):diff --git a/tests/unit/agent_chat/test_agent_chat_service.py b/tests/unit/agent_chat/test_agent_chat_service.pyindex eda5beb9e8..717967e348 100644--- a/tests/unit/agent_chat/test_agent_chat_service.py+++ b/tests/unit/agent_chat/test_agent_chat_service.py@@ -174,9 +174,11 @@ def test_cancel_ends_the_turn(tmp_path: Path, scripted):svc = AgentChatService(AgentChatStore(":memory:"))session = svc.create_session(provider="fakeprov", cwd=str(tmp_path))q = svc.subscribe(session.session_id)- await svc.send(session.session_id, "go")+ turn_id = await svc.send(session.session_id, "go")await _drain(q, "approval_required")- assert await svc.cancel(session.session_id)+ assert not await svc.cancel(session.session_id, expected_turn_id="previous-turn")+ assert svc.is_running(session.session_id)+ assert await svc.cancel(session.session_id, expected_turn_id=turn_id)events = await _drain(q, "turn_finished")assert events[-1]["payload"]["status"] == "cancelled"assert not (tmp_path / "a").exists()@@ -232,6 +234,11 @@ def test_provider_health_reports_each_row_and_caches_the_sweep(tmp_path: Path, mimport jarvis.ui.web.agent_chat_routes as routescalls: list[str] = []+ cli_calls: list[str] = []++ def _fake_cli(runner):+ cli_calls.append(runner)+ return "ok", "ok", f"{runner}: signed in"async def _fake(cfg, provider_id, *, probe=True):calls.append(provider_id)@@ -247,6 +254,8 @@ def test_provider_health_reports_each_row_and_caches_the_sweep(tmp_path: Path, mreturn SimpleNamespace(status=status, reason=reason, detail=detail)monkeypatch.setattr("jarvis.ui.web.provider_routes.provider_health", _fake, raising=False)+ monkeypatch.setattr("jarvis.agent_chat.service._claude_cli_installed", lambda: False)+ monkeypatch.setattr(routes, "_cli_login_snapshot", _fake_cli)monkeypatch.setattr(routes, "_health_cache", {})with TestClient(_app(tmp_path)) as client:@@ -257,6 +266,8 @@ def test_provider_health_reports_each_row_and_caches_the_sweep(tmp_path: Path, massert set(rows) == {p.id for p in rows_for("jarvis")}assert rows["claude-api"]["status"] == "error"assert rows["claude-api"]["reason"] == "bad_key"+ assert rows["openai-codex"]["status"] == "ok"+ assert "codex-cli" in cli_calls and "claude-cli" not in cli_callsassert rows["openrouter"]["reason"] == "no_credits"assert rows["grok"]["status"] == "ok"assert rows["nvidia"]["status"] == "needs_setup"@@ -265,13 +276,14 @@ def test_provider_health_reports_each_row_and_caches_the_sweep(tmp_path: Path, massert rows["gemini"]["status"] == "unknown"assert rows["gemini"]["reason"] == "check_failed"- # Second call is served from the sweep, not from nine more requests.- swept = len(calls)+ # The cache covers both API probes and CLI login snapshots.+ swept = (len(calls), len(cli_calls))again = client.get("/api/agent-chat/provider-health?surface=jarvis").json()- assert again["cached"] is True and len(calls) == swept+ assert again["cached"] is True+ assert (len(calls), len(cli_calls)) == swept# …unless the caller asks for a fresh one.client.get("/api/agent-chat/provider-health?surface=jarvis&refresh=true")- assert len(calls) > swept+ assert len(calls) > swept[0] and len(cli_calls) > swept[1]class _CliStatus:@@ -332,8 +344,9 @@ def test_cli_login_snapshot_codex_and_antigravity_use_the_cli_login(monkeypatch)assert reason == "not_configured"-def test_agent_surface_cli_health_does_not_probe_the_api_key(tmp_path: Path, monkeypatch):- """The IDE picker lists Claude Code under Coding CLIs.[email protected]("surface", ["agent", "jarvis"])+def test_cli_surface_health_does_not_probe_the_api_key(tmp_path: Path, monkeypatch, surface):+ """Both chat pickers offer Claude Code as a coding CLI.Its catalog id is still ``claude-api``, so the API-Keys one-token probewould report a revoked Anthropic key as "Key rejected" on that CLI row.@@ -358,7 +371,7 @@ def test_agent_surface_cli_health_does_not_probe_the_api_key(tmp_path: Path, monmonkeypatch.setattr(routes, "_health_cache", {})with TestClient(_app(tmp_path)) as client:- body = client.get("/api/agent-chat/provider-health?surface=agent").json()+ body = client.get(f"/api/agent-chat/provider-health?surface={surface}").json()rows = {r["provider"]: r for r in body["providers"]}assert rows["claude-api"]["status"] == "ok"assert rows["claude-api"]["reason"] == "ok"@@ -371,23 +384,26 @@ def test_agent_surface_cli_health_does_not_probe_the_api_key(tmp_path: Path, monassert rows["openai"]["reason"] == "bad_key"-def test_jarvis_surface_still_probes_the_claude_api_key(tmp_path: Path, monkeypatch):- """The front page has no CLI seats: Claude there is the Anthropic key."""+def test_jarvis_surface_probes_the_claude_api_key_when_cli_is_uninstalled(+ tmp_path: Path, monkeypatch+):+ """Without Claude Code, its dual row uses the API while other CLIs keep their logins."""import jarvis.ui.web.agent_chat_routes as routesapi_calls: list[str] = []+ cli_calls: list[str] = []async def _fake_api(cfg, provider_id, *, probe=True):api_calls.append(provider_id)return SimpleNamespace(status="error", reason="bad_key", detail="401")+ def _fake_cli(runner):+ cli_calls.append(runner)+ return "ok", "ok", f"{runner}: signed in"+monkeypatch.setattr("jarvis.ui.web.provider_routes.provider_health", _fake_api, raising=False)- monkeypatch.setattr(- routes,- "_cli_login_snapshot",- lambda runner: pytest.fail(f"CLI login checked on jarvis surface: {runner}"),- )- monkeypatch.setattr("jarvis.agent_chat.service._claude_cli_installed", lambda: True)+ monkeypatch.setattr(routes, "_cli_login_snapshot", _fake_cli)+ monkeypatch.setattr("jarvis.agent_chat.service._claude_cli_installed", lambda: False)monkeypatch.setattr(routes, "_health_cache", {})with TestClient(_app(tmp_path)) as client:@@ -395,36 +411,53 @@ def test_jarvis_surface_still_probes_the_claude_api_key(tmp_path: Path, monkeyparows = {r["provider"]: r for r in body["providers"]}assert "claude-api" in api_callsassert rows["claude-api"]["reason"] == "bad_key"+ assert "claude-cli" not in cli_calls+ assert "codex-cli" in cli_calls-def test_the_jarvis_catalog_is_api_seats_only(tmp_path: Path):- """What the front page's composer is handed: endpoints behind a key.[email protected]("claude_installed", [True, False])+def test_the_jarvis_catalog_offers_api_and_cli_seats(tmp_path: Path, monkeypatch, claude_installed):+ """Jarvis offers coding CLIs and API seats, with Claude's installed-state fallback."""+ import jarvis.ui.web.agent_chat_routes as routes- No CLI row, and the dual Claude row resolved to the brain runner with a- live model list — whether or not Claude Code is on this machine, which is- exactly what the previous behaviour turned on.- """+ async def _fake_live_models():+ return {}++ monkeypatch.setattr("jarvis.agent_chat.service._claude_cli_installed", lambda: claude_installed)+ monkeypatch.setattr(routes, "_live_cli_models", _fake_live_models)+ monkeypatch.setattr(+ routes, "_cli_installed", lambda runner: runner == "claude-cli" and claude_installed+ )with TestClient(_app(tmp_path)) as client:cat = client.get("/api/agent-chat/catalog?surface=jarvis").json()rows = {p["id"]: p for p in cat["providers"]}- assert not ({"openai-codex", "antigravity", "grok-build"} & set(rows))+ assert {"openai-codex", "antigravity", "grok-build"} <= set(rows)assert {"claude-api", "openai", "gemini", "ollama"} <= set(rows)- assert all(p["runner"] == "brain" for p in rows.values()), rows- assert rows["claude-api"]["models_source"] == "live"- # No row claims a CLI either way, so the picker greys nothing for a- # missing binary here.- assert all(p["cli_installed"] is None for p in rows.values())+ for provider in ("openai", "gemini", "ollama"):+ assert rows[provider]["runner"] == "brain"+ assert rows[provider]["cli_installed"] is None+ for provider, runner in (+ ("openai-codex", "codex-cli"),+ ("antigravity", "agy-cli"),+ ("grok-build", "grok-cli"),+ ):+ assert rows[provider]["runner"] == runner+ assert rows[provider]["cli_installed"] is False+ assert rows["claude-api"]["runner"] == ("claude-cli" if claude_installed else "brain")+ assert rows["claude-api"]["models_source"] == ("curated" if claude_installed else "live")+ assert rows["claude-api"]["cli_installed"] is (True if claude_installed else None)# The IDE's chat is untouched: its CLI rows are still there.agent_catalog = client.get("/api/agent-chat/catalog?surface=agent").json()agent_rows = {p["id"]: p for p in agent_catalog["providers"]}assert {"openai-codex", "antigravity", "grok-build"} <= set(agent_rows)- # And a CLI seat cannot be talked onto the front page by hand.- refused = client.post(+ # Catalog availability agrees with both session creation and provider changes.+ created = client.post("/api/agent-chat/sessions", json={"provider": "openai-codex", "surface": "jarvis"})- assert refused.status_code == 400, refused.text+ assert created.status_code == 201, created.text+ assert created.json()["provider"] == "openai-codex"made = client.post("/api/agent-chat/sessions", json={"provider": "openai", "surface": "jarvis"})@@ -433,7 +466,8 @@ def test_the_jarvis_catalog_is_api_seats_only(tmp_path: Path):f"/api/agent-chat/sessions/{made.json()['session_id']}",json={"provider": "antigravity"},)- assert moved.status_code == 400, moved.text+ assert moved.status_code == 200, moved.text+ assert moved.json()["provider"] == "antigravity"def test_routes_catalog_sessions_and_websocket_snapshot(tmp_path: Path, scripted):diff --git a/tests/unit/agent_chat/test_cli_catalog_isolation.py b/tests/unit/agent_chat/test_cli_catalog_isolation.pynew file mode 100644index 0000000000..15d17a2add--- /dev/null+++ b/tests/unit/agent_chat/test_cli_catalog_isolation.py@@ -0,0 +1,295 @@+"""Model discovery must follow the actual CLI, account, and current settings."""++from __future__ import annotations++import asyncio+import json+from pathlib import Path+from types import SimpleNamespace++import pytest++from jarvis.agent_chat import cli_catalog as catalog+from jarvis.agent_chat import runner_cli as rc+++def test_catalog_identity_changes_on_update_login_config_and_workspace(tmp_path):+ cli = tmp_path / "codex"+ cli.write_text("old", encoding="utf-8")+ env = {"CODEX_HOME": str(tmp_path), "PRIVATE_TOKEN": "never-log-this"}+ old = catalog.catalog_key([str(cli)], env, tmp_path)+ cli.write_text("updated-cli", encoding="utf-8")+ updated = catalog.catalog_key([str(cli)], env, tmp_path)+ assert old != updated+ for filename in ("auth.json", "config.toml"):+ (tmp_path / filename).write_text("changed", encoding="utf-8")+ new = catalog.catalog_key([str(cli)], env, tmp_path)+ assert new != updated+ updated = new+ assert updated != catalog.catalog_key([str(cli)], {**env, "CODEX_HOME": "other"}, tmp_path)+ assert updated != catalog.catalog_key([str(cli)], env, tmp_path / "other-project")+ assert "never-log-this" not in updated+++def test_cache_separates_accounts_refreshes_unknown_models_and_bounds_failures(monkeypatch):+ now = [100.0]+ monkeypatch.setattr(catalog.time, "monotonic", lambda: now[0])+ cache = catalog.CatalogCache()+ rows = [{"id": "old", "efforts": ["high"]}]+ calls = []++ def load():+ calls.append(True)+ return rows++ first = cache.read("account-a", load)+ first[0]["efforts"].append("bogus")+ assert cache.read("account-a", load)[0]["efforts"] == ["high"]+ cache.read("account-b", load)+ assert len(calls) == 2+ rows = [{"id": "new", "efforts": []}]+ now[0] += 11+ assert cache.read("account-a", load, required_model="new") == rows+ assert len(calls) == 3++ # Repeated rejected selections do not start a probe for every click.+ cache.read("account-a", load, required_model="missing")+ assert len(calls) == 3+ assert cache.read("failed", lambda: None) is None+ assert cache.read("failed", load) is None+ now[0] += 11+ assert cache.read("failed", load) == rows+++async def test_catalog_route_uses_session_seat_and_keeps_empty_results(monkeypatch, tmp_path):+ from jarvis import agent_accounts+ from jarvis.ui.web import agent_chat_routes as routes++ session = SimpleNamespace(surface="agent", account_id="seat-two", cwd=str(tmp_path))+ service = SimpleNamespace(+ store=SimpleNamespace(get_session=lambda sid: session),+ default_cwd=lambda surface: str(tmp_path),+ )+ monkeypatch.setattr(agent_accounts, "resolve", lambda account: SimpleNamespace(id=account))+ monkeypatch.setattr(routes, "_service", lambda request: service)+ monkeypatch.setattr(routes, "_cli_installed", lambda runner: True)+ seen = []++ async def live():+ seen.append((rc.ACCOUNT_OVERRIDE.get(), rc._catalog_cwd()))+ return {"codex-cli": []}++ monkeypatch.setattr(routes, "_live_cli_models", live)+ before = rc.ACCOUNT_OVERRIDE.get()+ result = await routes.get_catalog(None, session_id="chat", account_id="wrong-seat")+ assert seen == [("seat-two", tmp_path)]+ assert rc.ACCOUNT_OVERRIDE.get() == before+ codex = next(row for row in result["providers"] if row["id"] == "openai-codex")+ assert codex["curated_models"] == []+++def test_empty_live_catalog_never_reintroduces_bundled_models():+ from jarvis.workspace.launch_picks import offered_models++ assert offered_models("codex", {"codex-cli": []}) == []+++async def test_future_codex_effort_is_kept(monkeypatch, tmp_path):+ seen = []+ monkeypatch.setattr(+ rc, "read_codex_models", lambda **kwargs: [{"id": "future", "efforts": ["future-effort"]}]+ )++ def planner(**kwargs):+ seen.append(kwargs["effort"])+ raise rc.CliUnavailable("stop before process launch")++ monkeypatch.setitem(rc._PLANNERS, "codex-cli", planner)+ handle = SimpleNamespace(+ session=SimpleNamespace(+ session_id="test",+ cwd=str(tmp_path),+ provider="openai-codex",+ model="future",+ effort="future-effort",+ permission_mode="plan",+ )+ )+ await rc._run_cli_once(handle, "hello", "codex-cli", None)+ assert seen == ["future-effort"]+++def test_removed_pinned_account_never_falls_back_to_another_subscription(monkeypatch):+ from jarvis import agent_accounts++ monkeypatch.setattr(agent_accounts, "resolve", lambda account: None)+ with rc.cli_catalog_scope(account_id="removed"):+ with pytest.raises(rc.CliUnavailable, match="no longer exists"):+ rc._account_env("codex")+++def test_account_environment_is_frozen_for_discovery_and_spawn(monkeypatch):+ from jarvis import agent_accounts++ selected = ["one"]+ monkeypatch.setattr(agent_accounts, "resolve", lambda account_id: None)+ monkeypatch.setattr(+ agent_accounts, "active_account", lambda platform: SimpleNamespace(id=selected[0])+ )+ monkeypatch.setattr(+ agent_accounts, "spawn_env", lambda platform, account_id, base: {"CODEX_HOME": account_id}+ )+ with rc.cli_catalog_scope():+ assert rc._account_env("codex")["CODEX_HOME"] == "one"+ selected[0] = "two"+ assert rc._account_env("codex")["CODEX_HOME"] == "one"+ assert rc._account_env("codex")["CODEX_HOME"] == "two"+++class FakeCodex:+ def __init__(self, *, hanging=False, malformed=False):+ self.stdout = asyncio.StreamReader()+ self.stdin = self+ self.returncode = None+ self.requests = []+ self.killed = False+ self.hanging = hanging+ self.malformed = malformed++ def write(self, data):+ request = json.loads(data)+ self.requests.append(request)+ if self.hanging or "id" not in request:+ return+ result = {}+ if request["method"] == "model/list":+ cursor = request["params"]["cursor"]+ result = {+ "data": [+ {+ "model": "future-model" if cursor is None else "second-model",+ "supportedReasoningEfforts": [{"reasoningEffort": "future-effort"}],+ }+ ],+ "nextCursor": "page-2" if cursor is None else None,+ }+ reply = {"id": request["id"], "result": result}+ if self.malformed:+ reply = {"id": request["id"], "error": {"message": "PRIVATE_PROVIDER_BODY"}}+ self.stdout.feed_data((json.dumps(reply) + "\n").encode())++ async def drain(self):+ pass++ def kill(self):+ self.killed = True+ self.returncode = -1++ async def wait(self):+ return self.returncode+++async def test_codex_discovery_uses_same_environment_paginates_and_reaps(monkeypatch, tmp_path):+ proc = FakeCodex()+ spawned = []++ async def spawn(*argv, **kwargs):+ spawned.append((argv, kwargs))+ return proc++ monkeypatch.setattr(asyncio, "create_subprocess_exec", spawn)+ env = {"CODEX_HOME": "pinned-seat"}+ rows = await catalog._codex_models(["actual-codex"], env, tmp_path)+ assert [row["id"] for row in rows] == ["future-model", "second-model"]+ assert rows[0]["efforts"] == ["future-effort"]+ assert spawned[0][0] == ("actual-codex", "app-server")+ assert spawned[0][1]["env"] == env+ assert spawned[0][1]["cwd"] == str(tmp_path)+ assert proc.killed+ assert not any(request["method"].startswith(("thread/", "turn/")) for request in proc.requests)++[email protected]("hanging", [False, True])+async def test_codex_discovery_reaps_on_error_or_timeout(monkeypatch, tmp_path, hanging):+ proc = FakeCodex(hanging=hanging, malformed=not hanging)++ async def spawn(*args, **kwargs):+ return proc++ monkeypatch.setattr(asyncio, "create_subprocess_exec", spawn)+ with pytest.raises((ValueError, TimeoutError)) as failure:+ await asyncio.wait_for(catalog._codex_models(["codex"], {}, tmp_path), 0.02)+ assert "PRIVATE_PROVIDER_BODY" not in str(failure.value)+ assert proc.killed+++def test_retired_hidden_and_no_effort_models(monkeypatch):+ monkeypatch.setattr(catalog.time, "time", lambda: 100)+ rows = catalog.parse_codex_models(+ [+ {"id": "retired", "supportedReasoningEfforts": [], "upgradeInfo": {"retirementAt": 99}},+ {"id": "hidden", "hidden": True},+ {"id": "new", "supportedReasoningEfforts": []},+ ]+ )+ assert rows == [{"id": "new", "label": "new", "efforts": [], "note": ""}]+++async def test_unavailable_codex_model_is_stopped_before_inference(monkeypatch, tmp_path):+ monkeypatch.setattr(rc, "read_codex_models", lambda **kwargs: [{"id": "supported"}])++ def planner(**kwargs):+ pytest.fail("An unavailable model must not start a turn")++ monkeypatch.setitem(rc._PLANNERS, "codex-cli", planner)+ handle = SimpleNamespace(+ session=SimpleNamespace(+ session_id="test",+ cwd=str(tmp_path),+ provider="openai-codex",+ model="unsupported",+ effort="high",+ permission_mode="plan",+ )+ )+ result = await rc._run_cli_once(handle, "hello", "codex-cli", "existing-conversation")+ assert result.status == "error"+ assert "update Codex" in result.error++[email protected]("family", ["agy", "opencode"])+def test_cli_catalog_reloads_on_account_and_config_change(monkeypatch, tmp_path, family):+ import subprocess++ seat = [str(tmp_path / "one")]+ calls = []+ monkeypatch.setattr(rc, "_account_env", lambda platform: {"AGENT_CONFIG_DIR": seat[0]})+ monkeypatch.setattr(rc, "_registry_env", lambda agent, env: env)+ monkeypatch.setattr(rc, f"{family}_argv_prefix", lambda: [family])+ monkeypatch.setattr(+ rc, "_AGY_CATALOG" if family == "agy" else "_OPENCODE_CATALOG", {"at": 0.0, "rows": None}+ )++ def run(*args, **kwargs):+ calls.append(kwargs["env"]["AGENT_CONFIG_DIR"])+ return SimpleNamespace(+ returncode=0,+ stdout=(+ b'{"command":{"data":{"models":[{"id":"new-high"}]}}}'+ if family == "agy"+ else b"vendor/new\n"+ ),+ )++ monkeypatch.setattr(subprocess, "run", run)+ read = rc.read_agy_models if family == "agy" else rc.read_opencode_models+ read()+ read()+ assert len(calls) == 1+ seat[0] = str(tmp_path / "two")+ read()+ assert len(calls) == 2+ Path(seat[0]).mkdir()+ (Path(seat[0]) / "auth.json").write_text("changed", encoding="utf-8")+ read()+ assert len(calls) == 3diff --git a/tests/unit/agent_chat/test_ide_cli_seats.py b/tests/unit/agent_chat/test_ide_cli_seats.pyindex aac92f4487..1a37c9aa33 100644--- a/tests/unit/agent_chat/test_ide_cli_seats.py+++ b/tests/unit/agent_chat/test_ide_cli_seats.py@@ -61,15 +61,12 @@ def test_every_chat_cli_seat_names_a_registered_ide_entry_in_the_ide_order() ->assert [row.agent for row in catalog.cli_rows()] == _ide_coding_clis()-def test_the_agent_surface_offers_every_cli_seat_and_the_front_page_none() -> None:+def test_the_agent_and_jarvis_surfaces_offer_every_cli_seat() -> None:agent_ids = {row.id for row in catalog.rows_for("agent")}jarvis_ids = {row.id for row in catalog.rows_for("jarvis")}for row in catalog.cli_rows():assert row.id in agent_ids, row.id- # The dual Claude row is the Anthropic API on the front page; every- # other CLI seat has no API twin there and stays out.- if row.id != "claude-api":- assert row.id not in jarvis_ids, row.id+ assert row.id in jarvis_ids, row.iddef test_a_cli_the_ide_dropped_leaves_the_picker(monkeypatch: pytest.MonkeyPatch) -> None:@@ -79,16 +76,15 @@ def test_a_cli_the_ide_dropped_leaves_the_picker(monkeypatch: pytest.MonkeyPatchassert "opencode" in ids and "openai" in ids-def test_resolve_runner_names_each_clis_own_runner() -> None:[email protected]("surface", ["agent", "jarvis"])+def test_resolve_runner_names_each_clis_own_runner(surface: str) -> None:from jarvis.agent_chat.service import resolve_runner- assert resolve_runner("opencode") == "opencode-cli"- assert resolve_runner("kimi") == "kimi-cli"- assert resolve_runner("glm") == "glm-cli"- assert resolve_runner("deepseek-harness") == "dsh-cli"- assert resolve_runner("cursor") == "cursor-cli"- for pid in ("opencode", "kimi", "glm", "deepseek-harness", "cursor"):- assert resolve_runner(pid, surface="jarvis") == "unknown"+ assert resolve_runner("opencode", surface=surface) == "opencode-cli"+ assert resolve_runner("kimi", surface=surface) == "kimi-cli"+ assert resolve_runner("glm", surface=surface) == "glm-cli"+ assert resolve_runner("deepseek-harness", surface=surface) == "dsh-cli"+ assert resolve_runner("cursor", surface=surface) == "cursor-cli"def test_the_row_dict_carries_the_registry_key() -> None:diff --git a/tests/unit/agent_chat/test_mars_turn_terminal.py b/tests/unit/agent_chat/test_mars_turn_terminal.pynew file mode 100644index 0000000000..88a54c64f0--- /dev/null+++ b/tests/unit/agent_chat/test_mars_turn_terminal.py@@ -0,0 +1,95 @@+"""Exact durable terminal lookups for Mars cancellation/result reconciliation."""++from __future__ import annotations++import pytest++from jarvis.agent_chat.events import make_event+from jarvis.agent_chat.store import AgentChatStore+++class NoHistoryScanStore(AgentChatStore):+ """The exact lookup must not load a chat's private history into the caller."""++ def list_events(self, session_id, *, after_seq=0):+ raise AssertionError("turn_terminal must not load complete session history")+++def store():+ store = NoHistoryScanStore()+ for session in ("society:one", "society:two"):+ store.create_session(+ provider="openai",+ model="",+ effort="",+ cwd=".",+ session_id=session,+ surface="society",+ )+ try:+ yield store+ finally:+ store.close()+++def _terminal(store, session, turn, status):+ return store.append_event(+ session, make_event("turn_finished", {"turn_id": turn, "status": status})+ )+++def test_terminal_lookup_is_exactly_session_and_turn_scoped(store):+ wanted = _terminal(store, "society:one", "shared-turn", "done")+ _terminal(store, "society:two", "shared-turn", "cancelled")+ _terminal(store, "society:one", "newer-turn", "error")+ actual = store.turn_terminal("society:one", "shared-turn")+ assert actual["payload"] == {"turn_id": "shared-turn", "status": "done"}+ assert actual["seq"] == wanted["seq"]+ assert store.turn_terminal("society:two", "shared-turn")["payload"]["status"] == "cancelled"+ assert store.turn_terminal("society:missing", "shared-turn") is None+ assert store.turn_terminal("society:one", "missing-turn") is None+++def test_latest_durable_terminal_wins_without_reading_other_event_kinds(store):+ _terminal(store, "society:one", "target", "done")+ latest = _terminal(store, "society:one", "target", "cancelled")+ store.append_event(+ "society:one",+ make_event(+ "assistant_text",+ {"turn_id": "target", "text": "Not a terminal receipt."},+ ),+ )+ record = store.turn_terminal("society:one", "target")+ assert record["seq"] == latest["seq"]+ assert record["kind"] == "turn_finished"+ assert record["payload"]["status"] == "cancelled"+++def test_turn_reference_is_a_bound_sql_value(store):+ _terminal(store, "society:one", "actual-turn", "done")+ assert store.turn_terminal("society:one", "' OR 1=1 --") is None+ assert store.turn_terminal("society:one' OR 1=1 --", "actual-turn") is None+++def test_terminal_lookup_survives_connection_and_process_style_reopen(tmp_path):+ path = tmp_path / "chat.db"+ original = NoHistoryScanStore(path)+ original.create_session(+ provider="openai",+ model="",+ effort="",+ cwd=".",+ session_id="society:one",+ surface="society",+ )+ saved = _terminal(original, "society:one", "durable-turn", "done")+ original.close()+ reopened = NoHistoryScanStore(path)+ try:+ result = reopened.turn_terminal("society:one", "durable-turn")+ assert result["seq"] == saved["seq"]+ assert result["payload"] == saved["payload"]+ finally:+ reopened.close()diff --git a/tests/unit/agent_chat/test_runner_brain.py b/tests/unit/agent_chat/test_runner_brain.pyindex 329899597a..95f19b9604 100644--- a/tests/unit/agent_chat/test_runner_brain.py+++ b/tests/unit/agent_chat/test_runner_brain.py@@ -205,6 +205,43 @@ async def test_a_brain_error_ends_the_turn_honestly(assert finished["status"] == "error" and "provider down" in (finished["error"] or "")[email protected]("reason", ["mandated_tool_unfulfilled", "unbacked_action_claim"])+async def test_guarded_reply_is_visible_but_never_finishes_as_done(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, no_cli, reason+):+ safe_reply = "The requested action has not been completed."+ fake = FakeBrainManager(reply=safe_reply, chunks=())+ original_generate = fake.generate++ async def guarded_generate(text, **kwargs):+ reply = await original_generate(text, **kwargs)+ kwargs["turn_override"].receipt.mark_guard_failure(reason)+ return reply++ monkeypatch.setattr(fake, "generate", guarded_generate)+ monkeypatch.setattr(runner_brain, "brain_manager", lambda: fake)+ svc = _service(None)+ session = _jarvis_session(svc, tmp_path)+ queue = svc.subscribe(session.session_id)+ try:+ await svc.send(session.session_id, "Create a folder named drafts.")+ events = await _drain(queue, "turn_finished")+ final = next(event["payload"] for event in events if event["kind"] == "assistant_text")+ assert final["text"] == safe_reply+ terminal = events[-1]["payload"]+ assert terminal["status"] == "error" and terminal["error"] == reason+ assert terminal["usage"] == {"input_tokens": 12, "output_tokens": 4, "cost_usd": 0.002}+ saved = svc.store.list_events(session.session_id)+ saved_terminal = next(+ event["payload"] for event in saved if event["kind"] == "turn_finished"+ )+ assert saved_terminal["status"] == "error"+ finally:+ svc.unsubscribe(session.session_id, queue)+ await svc.wait_turn(session.session_id)+ svc.store.close()++async def test_no_brain_yet_is_a_clear_error_not_a_hang(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, no_cli):diff --git a/tests/unit/brain/test_artifact_gate.py b/tests/unit/brain/test_artifact_gate.pyindex 6bdcd5588d..c1cd3fa2a4 100644--- a/tests/unit/brain/test_artifact_gate.py+++ b/tests/unit/brain/test_artifact_gate.py@@ -2,63 +2,38 @@The contract is asymmetric on purpose. A missed request costs one extra turn —the user repeats themselves and gets their artifact. An unasked-for artifact-is the failure this gate exists to prevent (maintainer mandate 2026-08-11:-"only when someone says they want to understand it visually"; 2026-08-23: an-artifact is asked for by name), so the negative list is the important half of-this file and carries the real regressions:-+is the failure this gate exists to prevent, so the negative list is the+important half of this file and carries the real regressions:++* only the literal word builds — "Artefakt"/"Artifact"/"Artefacto" said to+ Jarvis or its agents, or pinned via the Add menu (which bypasses this gate+ through the turn override's extra hands);+* visual verbs and page shapes alone ("visualisier", "Dashboard",+ "Diagramm", "Seite", "Bericht") never build;* the utterance that opens the EXISTING section must never build a new page- (that is ``navigate``'s job, and both share the words "Visualisierung" and- "Artefakt"),-* a question about the word is not a request for the thing,-* an ordinary turn that merely mentions a chart is not a request either.+ (that is ``navigate``'s job, and both share the word "Artefakt"),+* a question about the word is not a request for the thing.Every German/Spanish literal here is speech-input vocabulary under test."""+from __future__ import annotationsimport pytestfrom jarvis.brain.artifact_gate import wants_artifact-# Turns that ask, in the user's own words, to be shown something as a picture.+# Turns that ask, literally, for an artifact — the only words that build._WANTS = [- # explicit drawing verb — enough on its own- "visualisier mir das mal", # i18n-allow: German speech-input test vocabulary- "visualisiere das bitte", # i18n-allow: German speech-input test vocabulary- "kannst du mir das visualisieren", # i18n-allow: German speech-input test vocabulary- "visualize this for me",- "visualise it",- "veranschaulich mir den ablauf", # i18n-allow: German speech-input test vocabulary- "skizzier mir kurz die architektur", # i18n-allow: German speech-input test vocabulary- "mach eine mindmap daraus", # i18n-allow: German speech-input test vocabulary- "draw me a flowchart of the deploy",- "ein flussdiagramm dazu waere super", # i18n-allow: German speech-input test vocabulary- "visualízamelo por favor", # i18n-allow: Spanish speech-input test vocabulary- # build/show verb + visual noun — a request only in combination- "erklär mir das bildlich", # i18n-allow: German speech-input test vocabulary- "zeig mir das grafisch", # i18n-allow: German speech-input test vocabulary- "stell das mal visuell dar", # i18n-allow: German speech-input test vocabulary- "mach mir ein diagramm von den schritten", # i18n-allow: German speech-input test vocabulary- "gib mir eine grafik dazu", # i18n-allow: German speech-input test vocabulary- "show me that visually",- "can you explain this as a diagram",- "turn this into a timeline",- "hazme un diagrama de esto", # i18n-allow: Spanish speech-input test vocabulary- # a nav verb followed by "of/for" is still a request for a NEW picture- "zeig mir eine visualisierung von den zahlen", # i18n-allow: DE test vocabulary- "show me a visualization of the results",- # the artifact by name, and the page shapes that are artifacts"mach mir ein artefakt daraus", # i18n-allow: German speech-input test vocabulary"ich möchte ein artefakt davon", # i18n-allow: German speech-input test vocabulary+ "ein artefakt bitte", # i18n-allow: German speech-input test vocabulary"build me an artifact for this","turn that into an artifact",- "bau mir ein dashboard mit den zahlen", # i18n-allow: German speech-input test vocabulary- "make an infographic of the results",- "mach mir eine html-seite dazu", # i18n-allow: German speech-input test vocabulary- "erstell mir einen bericht als seite", # i18n-allow: German speech-input test vocabulary- "build me a report page on this",- "hazme una página con eso", # i18n-allow: Spanish speech-input test vocabulary+ "create an artifact from this",+ "hazme un artefacto con esto", # i18n-allow: Spanish speech-input test vocabulary+ "visualisier mir das als artefakt", # i18n-allow: German speech-input test vocabulary+ "mach mir ein dashboard als artefakt", # i18n-allow: German speech-input test vocabulary]# Turns that must leave the tool out of the set entirely.@@ -80,7 +55,27 @@ _DOES_NOT_WANT = ["what is a flowchart","explain what a mindmap is","was ist ein artefakt", # i18n-allow: German speech-input test vocabulary- "what is an artifact"+ "what is an artifact",+ # visual verbs and page shapes alone never build — literal word or Add pin only+ "visualisier mir das mal", # i18n-allow: German speech-input test vocabulary+ "visualisiere das bitte", # i18n-allow: German speech-input test vocabulary+ "kannst du mir das visualisieren", # i18n-allow: German speech-input test vocabulary+ "visualize this for me",+ "veranschaulich mir den ablauf", # i18n-allow: German speech-input test vocabulary+ "skizzier mir kurz die architektur", # i18n-allow: German speech-input test vocabulary+ "mach eine mindmap daraus", # i18n-allow: German speech-input test vocabulary+ "draw me a flowchart of the deploy",+ "mach mir ein diagramm von den schritten", # i18n-allow: German speech-input test vocabulary+ "gib mir eine grafik dazu", # i18n-allow: German speech-input test vocabulary+ "show me that visually",+ "turn this into a timeline",+ "zeig mir eine visualisierung von den zahlen", # i18n-allow: DE test vocabulary+ "show me a visualization of the results",+ "bau mir ein dashboard mit den zahlen", # i18n-allow: German speech-input test vocabulary+ "make an infographic of the results",+ "mach mir eine html-seite dazu", # i18n-allow: German speech-input test vocabulary+ "erstell mir einen bericht als seite", # i18n-allow: German speech-input test vocabulary+ "build me a report page on this",# ordinary turns that merely mention something chart-shaped"der chart ist heute rot", # i18n-allow: German speech-input test vocabulary"wie ist der bitcoin chart gerade", # i18n-allow: German speech-input test vocabulary@@ -111,21 +106,23 @@ def test_everything_else_keeps_the_gate_shut(text: str) -> None:assert wants_artifact(text) is False, text-def test_navigation_beats_the_drawing_verb() -> None:+def test_navigation_beats_the_literal_word() -> None:"""The shared word must resolve to navigation, not to a new page.- "Visualisierung" and "Artefakt" are both the section name and the thing- being asked for. Rule order (navigation first) is what keeps ``navigate``- reachable, so it is pinned here rather than left to the parametrized lists.+ "Artefakt" is both the section name and the thing being asked for. Rule+ order (navigation first) is what keeps ``navigate`` reachable, so it is+ pinned here rather than left to the parametrized lists."""assert wants_artifact("zeig mir die visualisierungen") is False # i18n-allow: input vocabassert wants_artifact("zeig mir die artefakte") is False # i18n-allow: input vocab- assert wants_artifact("visualisier mir die zahlen") is True # i18n-allow: input vocab+ assert wants_artifact("visualisier mir die zahlen") is False # i18n-allow: input vocabassert wants_artifact("zeig mir ein artefakt von den zahlen") is True # i18n-allow: input vocabdef test_a_visual_noun_alone_is_not_a_request() -> None:- """Without a producing verb, "diagram" or "page" is just a word in a sentence."""+ """Visual words without the literal word never build."""assert wants_artifact("das diagramm") is False # i18n-allow: input vocabassert wants_artifact("timeline") is Falseassert wants_artifact("die webseite") is False # i18n-allow: input vocab+ assert wants_artifact("visualisier mir das") is False # i18n-allow: input vocab+ assert wants_artifact("mach mir ein dashboard") is False # i18n-allow: input vocabdiff --git a/tests/unit/brain/test_artifact_tool_hide.py b/tests/unit/brain/test_artifact_tool_hide.pyindex 848985053a..327cfc5560 100644--- a/tests/unit/brain/test_artifact_tool_hide.py+++ b/tests/unit/brain/test_artifact_tool_hide.py@@ -1,17 +1,19 @@"""The ``create_artifact`` tool is offered only on a turn that asked for one.-Maintainer mandate (2026-08-11, artifacts 2026-08-23): an artifact is-something the user asks for — "visualisier mir das", "mach ein Artefakt-draus" — never something the assistant decides an answer would benefit from.-Prompt wording does not hold that line reliably, so the enforcement is-structural: on any other turn the tool is removed from the surface and the-model cannot call what it cannot see.+Maintainer mandate (2026-08-11, artifacts 2026-08-23, narrowed: literal word+or Add pin only): an artifact is built when the user literally says the word+("mach ein Artefakt draus", "build me an artifact") or pins the capability+via the Add menu — never because the assistant judges an answer would look+nicer as a page. Prompt wording does not hold that line reliably, so the+enforcement is structural: on any other turn the tool is removed from the+surface and the model cannot call what it cannot see.This pins the gate's placement in ``BrainManager``. The vocabulary itself istested in ``test_artifact_gate.py``; here the questions are narrower — doesthe manager actually strip it, does it leave every other tool alone, and does afault in the gate fail OPEN (tools unchanged) rather than blinding the brain."""+from __future__ import annotationsfrom jarvis.brain.manager import BrainManager@@ -33,14 +35,24 @@ def _surface() -> dict:def test_an_explicit_request_keeps_the_tool():out = _mgr()._hide_artifact_tool_without_request(- _surface(), "visualisier mir das mal" # i18n-allow: DE test vocabulary+ _surface(),+ "mach mir ein Artefakt draus", # i18n-allow: DE test vocabulary)assert "create_artifact" in out+def test_a_visual_verb_alone_loses_it():+ out = _mgr()._hide_artifact_tool_without_request(+ _surface(),+ "visualisier mir das mal", # i18n-allow: DE test vocabulary+ )+ assert "create_artifact" not in out++def test_an_ordinary_turn_loses_it():out = _mgr()._hide_artifact_tool_without_request(- _surface(), "was haben wir gerade besprochen" # i18n-allow: DE test vocabulary+ _surface(),+ "was haben wir gerade besprochen", # i18n-allow: DE test vocabulary)assert "create_artifact" not in out@@ -52,14 +64,15 @@ def test_nothing_else_is_touched():def test_opening_the_gallery_does_not_draw_a_new_picture():- """"Zeig mir die Visualisierungen" is navigate's turn, not create_artifact's.+ """ "Zeig mir die Visualisierungen" is navigate's turn, not create_artifact's.The regression that makes this worth its own test: both features answer tothe same word, and an artifact tool left on the surface here would start abackground build instead of showing the pages already there."""out = _mgr()._hide_artifact_tool_without_request(- _surface(), "zeig mir die visualisierungen" # i18n-allow: DE test vocabulary+ _surface(),+ "zeig mir die visualisierungen", # i18n-allow: DE test vocabulary)assert "create_artifact" not in outassert "navigate" in out@@ -84,4 +97,4 @@ def test_a_gate_fault_fails_open(monkeypatch):def test_a_non_dict_surface_is_passed_through():sentinel = ["not", "a", "dict"]- assert _mgr()._hide_artifact_tool_without_request(sentinel, "visualisier das") is sentinel+ assert _mgr()._hide_artifact_tool_without_request(sentinel, "mach ein Artefakt") is sentineldiff --git a/tests/unit/brain/test_local_outcome_gate.py b/tests/unit/brain/test_local_outcome_gate.pyindex efb8477a22..278fa4e716 100644--- a/tests/unit/brain/test_local_outcome_gate.py+++ b/tests/unit/brain/test_local_outcome_gate.py@@ -132,3 +132,66 @@ def test_directive_names_the_tool_and_forbids_the_refusal() -> None:# explicitly outlaw the "no tool" refusal the live bug produced.assert "run_shell" in RUN_SHELL_OUTCOME_DIRECTIVEassert "NEVER claim you lack a tool" in RUN_SHELL_OUTCOME_DIRECTIVE+++FICTIONAL_DRAFT_ASSIGNMENT = (+ "[assignment from the user]\n"+ "Prepare a communication draft for review. Do not send or publish it.\n\n"+ "Draft a 450-word internal update for an imaginary Mars research team about "+ "preparing a communications outpost for its first test. Include a subject, "+ "purpose, five practical checks, risks still to verify, and a clear next action. "+ "This is a fictional draft for review only. Do not send, publish, browse, "+ "run commands, or change files.\n"+ "When you are done, end with a handoff: what is done, where the output is, "+ "what evidence you used, what remains open, who should own the next step."+)+++ "utterance",+ [+ FICTIONAL_DRAFT_ASSIGNMENT,+ "Do not run commands or change files. When done explain what remains open.",+ "Write a fictional report. Don't send, publish, run commands, or change files.",+ "Write a short report without running shell commands or changing files.",+ "Do not create a folder, copy files, or run a script.",+ "Never run commands or create files.",+ "Do not run `python script.py`.",+ "Explain `python script.py` without running it.",+ "The subject is files. List the remaining questions.",+ "Erstelle keinen Ordner und kopiere keine Dateien.", # i18n-allow+ "Die Datei nicht loeschen.", # i18n-allow+ "Loesch die Datei nicht.", # i18n-allow+ "How do I create a folder? Show the commands, do not run them.",+ "Use the mouse. Create a folder named drafts on my desktop.",+ "How do I create a folder? Please list the commands and explain them.",+ ],+)+def test_prohibited_actions_and_unrelated_clauses_do_not_mandate(utterance: str) -> None:+ assert resolve_local_outcome_mandate(utterance) is None+++ "utterance",+ [+ "Create a folder named drafts on my desktop. Do not publish it.",+ "Do not delete the file; copy it to a backup folder instead.",+ "Do not delete files, but create a folder named backup.",+ "Create a folder and do not delete existing files.",+ "Create a folder without deleting existing files.",+ "Do not send an email. Create a folder named drafts on the desktop.",+ "Do not rename the file. Copy the file notes.txt to a backup folder.",+ "Loesch die Datei nicht; kopier die Datei in einen anderen Ordner.", # i18n-allow+ "List all files not ending in .tmp.",+ 'Create a folder named "not needed" on my desktop.',+ "Create a folder named 'not needed' on my desktop.",+ "Create a folder named `do not delete` on my desktop.",+ "Do not delete anything, and create a folder named backup.",+ "How do I create a folder? Now actually create a folder named drafts.",+ "Do not use the mouse. Create a folder named drafts on my desktop.",+ "Run `python script.py`",+ 'Execute "python script.py"',+ ],+)+def test_positive_actions_survive_a_separate_prohibition(utterance: str) -> None:+ assert resolve_local_outcome_mandate(utterance) == ("run_shell", RUN_SHELL_OUTCOME_DIRECTIVE)diff --git a/tests/unit/brain/test_manager_pointer.py b/tests/unit/brain/test_manager_pointer.pyindex f0913da2ff..2cb233c3af 100644--- a/tests/unit/brain/test_manager_pointer.py+++ b/tests/unit/brain/test_manager_pointer.py@@ -18,6 +18,15 @@ from jarvis.pointer import turn as pturnfrom jarvis.pointer.context import PointerContextfrom jarvis.screen_context.turn import TurnScreenContextfrom jarvis.vision.pointer_types import PointerElement+from tests.fakes.fake_capabilities import fake_headless_capabilities++_DRAFT_FOR_REVIEW = (+ "Write an English internal announcement draft, at most 80 words total including any handoff. "+ "Use only these fictional facts: Aurora station runs a simulation on Tuesday at 14:00; "+ "the simulation tests a greenhouse alarm; no real systems or people are involved. "+ "Return the draft text here for human review. "+ "Do not use tools, research, send, publish, or change anything."+)class _FakeNamed:@@ -109,6 +118,52 @@ async def test_unrelated_utterance_skips_pointer(monkeypatch) -> None:assert resolved["called"] is False # gate vetoed — no cursor work+ ("text", "pointing"),+ [+ (_DRAFT_FOR_REVIEW, False),+ (+ "Prepare a communication draft for review. Do not send or publish it.\n\n"+ + _DRAFT_FOR_REVIEW,+ False,+ ),+ ("What is written here?", True),+ ("What is written\nhere?", True),+ ("Was steht\nhier?", True),+ ("Kannst du lesen,\nwas hier steht?", True),+ ("What did I write here?", True),+ ],+ ids=[+ "draft",+ "station-assignment",+ "visual-question",+ "wrapped-english-question",+ "wrapped-german-question",+ "wrapped-embedded-question",+ "observational-writing-question",+ ],+)+async def test_headless_pointer_instruction_requires_a_visual_request(+ monkeypatch, text: str, pointing: bool+) -> None:+ """A draft must not acquire the missing-cursor refusal on a headless host."""+ monkeypatch.setattr(+ "jarvis.platform.capabilities.detect_capabilities", fake_headless_capabilities+ )+ manager, rec = _manager()+ assert manager._config.pointer.enabled++ await manager.generate(text, use_history=False)++ assert len(rec.calls) == 1+ call = rec.calls[0]+ assert call["user_text"] == text+ assert ("[AI Pointer]" in call["turn_context"]) is pointing+ assert ("cannot tell what is under the cursor" in call["turn_context"]) is pointing+ assert call["images"] == ()++@pytest.mark.asyncioasync def test_push_turn_suppresses_inspect_pointer_tool(monkeypatch) -> None:"""When the deictic push fires, the redundant inspect-pointer PULL tool isdiff --git a/tests/unit/brain/test_provider_test_live.py b/tests/unit/brain/test_provider_test_live.pynew file mode 100644index 0000000000..005c168860--- /dev/null+++ b/tests/unit/brain/test_provider_test_live.py@@ -0,0 +1,137 @@+"""The saved-key Test button must use the continuous voice protocol for Live."""++import asyncio+from types import SimpleNamespace++import pytest++from jarvis.brain.provider_test import _default_realtime_probe+from jarvis.core import config, registry+from jarvis.core.protocols import ContinuousVoiceStart+from jarvis.live import recovery+from jarvis.live.config import LiveConfig+from jarvis.realtime.protocol import RealtimeSessionConfig+++def probe(monkeypatch):+ opened, sent = [], []+ receiving = asyncio.Event()++ class Connection:+ terminal = "session.started"+ closed = False++ async def receive(self):+ receiving.set()+ if self.terminal == "wait":+ await asyncio.Event().wait()+ return {"type": self.terminal, "error": {"message": "private provider body"}}++ async def send(self, event):+ sent.append(event)++ async def close(self):+ self.closed = True++ connection = Connection()++ class Provider:+ continuous_conversation = True+ credential_candidates = (("synthetic_slot", "SYNTHETIC_ENV"),)++ def __init__(self, *, api_key):+ assert api_key == "synthetic"++ async def open_session(self, start):+ opened.append(start)+ return connection++ async def permit():+ return None++ monkeypatch.setattr(registry, "load", lambda *args, **kwargs: Provider)+ monkeypatch.setattr(config, "get_secret_any", lambda *args: "synthetic")+ monkeypatch.setattr(recovery, "connection_permit", permit)+ cfg = SimpleNamespace(+ live=LiveConfig(configured=True, backend_model="chosen-model", voice="gleam"),+ brain=SimpleNamespace(providers={}),+ )+ return SimpleNamespace(+ cfg=cfg, provider=Provider, connection=connection, opened=opened,+ sent=sent, receiving=receiving, spec=SimpleNamespace(id="continuous-test"),+ )+++async def test_live_key_probe_uses_saved_selection_and_closes(probe):+ before = probe.cfg.live.model_dump()+ elapsed = await _default_realtime_probe(probe.spec, probe.cfg, timeout_s=1)+ assert elapsed >= 0+ assert len(probe.opened) == 1+ start = probe.opened[0]+ assert isinstance(start, ContinuousVoiceStart)+ assert start.session["model"] == "gpt-live-1"+ assert start.session["audio"]["output"]["voice"] == "gleam"+ assert start.session["delegation"]["responses"]["model"] == "chosen-model"+ assert start.session["store"] is False+ assert probe.sent == [{"type": "session.close"}]+ assert probe.connection.closed+ assert probe.cfg.live.model_dump() == before++[email protected]("terminal", ["error", "session.closed"])+async def test_rejected_live_probe_closes_without_exposing_provider_body(probe, terminal):+ probe.connection.terminal = terminal+ with pytest.raises(RuntimeError, match="selected session") as caught:+ await _default_realtime_probe(probe.spec, probe.cfg, timeout_s=1)+ assert "private provider body" not in str(caught.value)+ assert probe.connection.closed+++async def test_live_probe_timeout_releases_connection(probe):+ probe.connection.terminal = "wait"+ with pytest.raises(TimeoutError):+ await _default_realtime_probe(probe.spec, probe.cfg, timeout_s=0.01)+ assert probe.connection.closed+++async def test_live_probe_cancellation_releases_connection(probe):+ probe.connection.terminal = "wait"+ task = asyncio.create_task(_default_realtime_probe(probe.spec, probe.cfg, timeout_s=1))+ await probe.receiving.wait()+ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await task+ assert probe.connection.closed+++async def test_probe_budget_includes_waiting_for_a_connection_permit(probe, monkeypatch):+ async def busy_budget():+ await asyncio.Event().wait()++ monkeypatch.setattr(recovery, "connection_permit", busy_budget)+ with pytest.raises(TimeoutError):+ await _default_realtime_probe(probe.spec, probe.cfg, timeout_s=0.01)+ assert not probe.opened+++async def test_missing_selection_does_not_silently_choose_a_model(probe):+ probe.cfg.live = LiveConfig()+ with pytest.raises(ValueError, match="Choose"):+ await _default_realtime_probe(probe.spec, probe.cfg, timeout_s=1)+ assert not probe.opened+++async def test_existing_realtime_adapters_keep_their_contract(probe):+ probe.provider.continuous_conversation = False+ await _default_realtime_probe(probe.spec, probe.cfg, timeout_s=1)+ assert isinstance(probe.opened[0], RealtimeSessionConfig)+ assert probe.connection.closed+ assert not probe.receiving.is_set()diff --git a/tests/unit/brain/test_provider_test_service.py b/tests/unit/brain/test_provider_test_service.pyindex fd5ba62186..a4d21e761b 100644--- a/tests/unit/brain/test_provider_test_service.py+++ b/tests/unit/brain/test_provider_test_service.py@@ -242,14 +242,14 @@ def test_realtime_test_opens_the_exact_duplex_provider() -> None:res = _run(run_provider_test(- get_spec("openai-realtime"),+ get_spec("openai-live"),_cfg(),present=True,realtime_probe=probe,))assert res.status == "ok"- assert probed == ["openai-realtime"]+ assert probed == ["openai-live"]assert res.latency_ms == pytest.approx(42.0)assert "handshake accepted" in res.detail.lower()diff --git a/tests/unit/brain/test_turn_override.py b/tests/unit/brain/test_turn_override.pyindex 89cc502244..d9f1d472a3 100644--- a/tests/unit/brain/test_turn_override.py+++ b/tests/unit/brain/test_turn_override.py@@ -49,6 +49,7 @@ def _seed(class _Tool:+ description = "Test-only tool; no tool execution is expected."def __init__(self, name: str, risk_tier: str = "safe") -> None:self.name = nameself.risk_tier = risk_tier@@ -264,6 +265,96 @@ def test_receipt_usage_is_the_agent_chat_shape() -> None:assert receipt.usage() == {"input_tokens": 10, "output_tokens": 3, "cost_usd": 0.5}+def test_guard_failure_is_separate_from_provider_finish_and_usage() -> None:+ receipt = TurnReceipt()+ receipt.record(+ provider=PICK, model=PICK_MODEL, tokens_in=10, tokens_out=3,+ cost_usd=0.5, finish_reason="stop",+ )+ receipt.mark_guard_failure("mandated_tool_unfulfilled")+ receipt.mark_guard_failure("unbacked_action_claim")+ assert receipt.guard_failure and receipt.failure_reason == "mandated_tool_unfulfilled"+ assert receipt.finish_reason == "stop"+ assert receipt.usage() == {"input_tokens": 10, "output_tokens": 3, "cost_usd": 0.5}+ receipt.record(+ provider=PICK, model=PICK_MODEL, tokens_in=2, tokens_out=1,+ cost_usd=0, finish_reason="stop",+ )+ assert not receipt.guard_failure and receipt.failure_reason == ""+++async def test_missing_mandated_action_marks_the_typed_turn_failed() -> None:+ mgr = _manager()+ mgr._tools["run_shell"] = _Tool("run_shell", "ask")+ scoped, _ = _seed(mgr, scoped_text="The requested folder is ready.")+ override = TurnOverride(provider=PICK, model=PICK_MODEL)+ reply = await mgr.generate(+ "Create a folder named drafts on my desktop.",+ use_history=False,+ turn_override=override,+ )+ assert scoped.calls+ assert reply != "The requested folder is ready."+ assert override.receipt.guard_failure+ assert override.receipt.failure_reason == "mandated_tool_unfulfilled"+++ ("answer", "failure"),+ [+ ("One moment, I'll check that and get back to you.", True),+ ("I have sent the report.", True),+ ("Let me check. The research station has three antennas.", False),+ ],+)+async def test_full_action_fallback_differs_from_trimming_a_delivered_answer(+ answer, failure+) -> None:+ mgr = _manager()+ scoped, _ = _seed(mgr, scoped_text=answer)+ override = TurnOverride(provider=PICK, model=PICK_MODEL)+ reply = await mgr.generate(+ "Tell me something interesting.", use_history=False, turn_override=override+ )+ assert scoped.calls+ assert reply != answer+ assert override.receipt.guard_failure is failure+ if failure:+ assert override.receipt.failure_reason == "unbacked_action_claim"+ else:+ assert "three antennas" in reply+ assert override.receipt.failure_reason == ""+++async def test_fictional_draft_with_prohibited_actions_needs_no_shell_call() -> None:+ # Exact bounded synthetic prompt from the Outpost reproduction. No "chat",+ # "email" or "message" vocabulary can accidentally bypass the local gate.+ prompt = (+ "[assignment from the user]\n"+ "Prepare a communication draft for review. Do not send or publish it.\n\n"+ "Draft a 450-word internal update for an imaginary Mars research team about "+ "preparing a communications outpost for its first test. Include a subject, "+ "purpose, five practical checks, risks still to verify, and a clear next action. "+ "This is a fictional draft for review only. Do not send, publish, browse, "+ "run commands, or change files.\n"+ "When you are done, end with a handoff: what is done, where the output is, "+ "what evidence you used, what remains open, who should own the next step."+ )+ answer = "Subject: Fictional Outpost readiness. Purpose: prepare a cautious test plan."+ mgr = _manager()+ mgr._tools["run_shell"] = _Tool("run_shell", "ask")+ scoped, _ = _seed(mgr, scoped_text=answer)+ override = TurnOverride(provider=PICK, model=PICK_MODEL, tool_filter=lambda tools: {})+ reply = await mgr.generate(prompt, use_history=False, turn_override=override)+ assert scoped.calls+ assert reply == answer+ assert not override.receipt.guard_failure+ assert not mgr._evidence_required_tool++# ------------------------------------------------------------ system_extradiff --git a/tests/unit/browser_voice/test_route.py b/tests/unit/browser_voice/test_route.pyindex 2a1823e502..8fe1e176fa 100644--- a/tests/unit/browser_voice/test_route.py+++ b/tests/unit/browser_voice/test_route.py@@ -724,7 +724,8 @@ async def test_realtime_socket_drop_flushes_pending_turn_to_session_store(if self._incoming:return self._incoming.pop(0)assert provider.session is not None- await asyncio.wait_for(provider.session.events_drained.wait(), timeout=1.0)+ # This checks archive flush, not cold-start language-guard latency.+ await asyncio.wait_for(provider.session.events_drained.wait(), timeout=5.0)raise WebSocketDisconnect()ws = _DropAfterProviderEvents(diff --git a/tests/unit/cli_ctl/test_dynamic_graft.py b/tests/unit/cli_ctl/test_dynamic_graft.pyindex c541e1ead1..782eaf3afe 100644--- a/tests/unit/cli_ctl/test_dynamic_graft.py+++ b/tests/unit/cli_ctl/test_dynamic_graft.py@@ -1,21 +1,38 @@import jsonimport time+import clickimport httpx+import pytestfrom click.testing import CliRunnerimport jarvis.cli_ctl.__main__ as entry-from jarvis.cli_ctl import openapi_cache, paths+from jarvis.cli_ctl import openapi_cacheSPEC = {- "openapi": "3.1.0", "info": {"version": "1"},- "paths": {"/api/ping": {"get": {"tags": ["diag"], "operationId": "ping",- "summary": "Ping"}}},+ "openapi": "3.1.0",+ "info": {"version": "1"},+ "paths": {"/api/ping": {"get": {"tags": ["diag"], "operationId": "ping", "summary": "Ping"}}},+}++MARS_SPEC = {+ "openapi": "3.1.0",+ "info": {"version": "mars"},+ "paths": {+ "/api/society/mars/definition": {+ "get": {+ "tags": ["mars"],+ "operationId": "definition",+ "summary": "Read Mars definition",+ }+ }+ },}def _mock_transport(monkeypatch, handler) -> None:import jarvis.cli_ctl.client as client_mod+real_init = client_mod.JarvisClient.__init__def patched_init(self, base_url, control_key, **kw):@@ -25,11 +42,15 @@ def _mock_transport(monkeypatch, handler) -> None:monkeypatch.setattr(client_mod.JarvisClient, "__init__", patched_init)-def _no_network(monkeypatch) -> None:+def _no_network(monkeypatch) -> list[str]:+ calls = []+def handler(req): # any request on this path is a regression+ calls.append(str(req.url))raise AssertionError(f"unexpected network call: {req.url}")_mock_transport(monkeypatch, handler)+ return callsdef test_grafted_root_has_api_group(monkeypatch, tmp_path):@@ -54,10 +75,11 @@ def test_completion_marker_skips_network(monkeypatch, tmp_path):monkeypatch.setenv("JARVISCTL_CACHE_HOME", str(tmp_path))monkeypatch.setenv("_JARVISCTL_COMPLETE", "complete_bash") # completion in flight- _no_network(monkeypatch)+ network = _no_network(monkeypatch)# Even an `api` invocation stays cache-only while completing.root = entry.build_root_command(["api"])assert root is not None+ assert not networkdef test_non_api_command_never_fetches(monkeypatch, tmp_path):@@ -65,26 +87,30 @@ def test_non_api_command_never_fetches(monkeypatch, tmp_path):monkeypatch.setenv("JARVISCTL_CACHE_HOME", str(tmp_path))monkeypatch.setenv("JARVISCTL_CONTROL_KEY", "jctl_x")- _no_network(monkeypatch)+ network = _no_network(monkeypatch)root = entry.build_root_command(["version"])assert "api" not in root.commands # no cache, no fetch -> no dynamic grouproot = entry.build_root_command(["--json", "version"])assert root is not None+ assert not networkdef test_non_api_command_grafts_from_stale_cache(monkeypatch, tmp_path):"""A stale cache still lists the `api` group for help — without a refetch."""monkeypatch.setenv("JARVISCTL_CACHE_HOME", str(tmp_path))monkeypatch.setenv("JARVISCTL_CONTROL_KEY", "jctl_x")- openapi_cache._write_cache(SPEC)- paths.openapi_meta_file().write_text(- json.dumps({"fetched_at": time.time() - 10 * 24 * 3600}), encoding="utf-8"- )+ url = entry._config.DEFAULT_BASE_URL+ openapi_cache._write_cache(SPEC, base_url=url)+ path = openapi_cache._cache_path(url)+ cached = json.loads(path.read_text(encoding="utf-8"))+ cached["fetched_at"] = time.time() - 10 * 24 * 3600+ path.write_text(json.dumps(cached), encoding="utf-8")- _no_network(monkeypatch)+ network = _no_network(monkeypatch)root = entry.build_root_command(["version"])assert "api" in root.commands+ assert not networkdef test_url_option_value_is_not_mistaken_for_subcommand(monkeypatch, tmp_path):@@ -92,10 +118,148 @@ def test_url_option_value_is_not_mistaken_for_subcommand(monkeypatch, tmp_path):monkeypatch.setenv("JARVISCTL_CACHE_HOME", str(tmp_path))monkeypatch.setenv("JARVISCTL_CONTROL_KEY", "jctl_x")- _no_network(monkeypatch)+ network = _no_network(monkeypatch)# "api" here is the --url VALUE, not the subcommand -> must stay cache-only.root = entry.build_root_command(["--url", "api", "version"])assert root is not Noneassert entry._first_subcommand(["--url", "api", "version"]) == "version"assert entry._first_subcommand(["--json", "api"]) == "api"assert entry._first_subcommand([]) is None+ assert not network+++ "options",+ [+ ["--url", "http://127.0.0.1:47869", "--key", "fixture-selected-key"],+ ["--url=http://127.0.0.1:47869", "--key=fixture-selected-key"],+ ],+)+def test_dynamic_schema_honors_root_url_and_key_before_callback(monkeypatch, tmp_path, options):+ monkeypatch.setenv("JARVISCTL_CACHE_HOME", str(tmp_path))+ monkeypatch.setenv("JARVISCTL_BASE_URL", "http://127.0.0.1:47821")+ monkeypatch.setenv("JARVISCTL_CONTROL_KEY", "fixture-profile-key")+ # Embedded invocations must not inherit the preceding callback's profile.+ monkeypatch.setitem(entry.STATE, "url", "http://127.0.0.1:47999")+ monkeypatch.setitem(entry.STATE, "key", "fixture-stale-key")+ before = dict(entry.STATE)+ requests = []++ def handler(request):+ requests.append((request.url.port, request.url.path, request.headers.get("Authorization")))+ return httpx.Response(200, json=MARS_SPEC if request.url.port == 47869 else SPEC)++ _mock_transport(monkeypatch, handler)+ argv = [*options, "api", "mars", "--help"]+ root = entry.build_root_command(argv)+ assert entry.STATE == before # Building the tree did not invoke the root callback.+ assert requests == [(47869, "/api/openapi.json", "Bearer fixture-selected-key")]+ result = CliRunner().invoke(root, argv)+ assert result.exit_code == 0 and "definition" in result.output+ assert "fixture-selected-key" not in result.output+ assert "fixture-selected-key" not in "".join(+ path.read_text(encoding="utf-8") for path in tmp_path.glob("openapi-*.json")+ )+++def test_next_invocation_without_overrides_uses_profile_instead_of_old_state(monkeypatch, tmp_path):+ monkeypatch.setenv("JARVISCTL_CACHE_HOME", str(tmp_path))+ monkeypatch.setenv("JARVISCTL_BASE_URL", "http://127.0.0.1:47821")+ monkeypatch.setenv("JARVISCTL_CONTROL_KEY", "fixture-profile-key")+ monkeypatch.setitem(entry.STATE, "url", "http://127.0.0.1:47869")+ monkeypatch.setitem(entry.STATE, "key", "fixture-old-key")+ observed = []++ def handler(request):+ observed.append((request.url.port, request.headers.get("Authorization")))+ return httpx.Response(200, json=SPEC)++ _mock_transport(monkeypatch, handler)+ root = entry.build_root_command(["api", "diag", "--help"])+ assert "api" in root.commands+ assert observed == [(47821, "Bearer fixture-profile-key")]+++ "argv",+ [+ ["--url", "http://127.0.0.1:47869", "--key", "fixture-key", "version"],+ ["--url=http://127.0.0.1:47869", "--help"],+ ["--help", "api"],+ ],+)+def test_static_commands_and_root_help_remain_network_free(monkeypatch, tmp_path, argv):+ monkeypatch.setenv("JARVISCTL_CACHE_HOME", str(tmp_path))+ network = _no_network(monkeypatch)+ assert entry.build_root_command(argv) is not None+ assert not network+++def test_cache_only_graft_uses_selected_origin_for_help_and_completion(monkeypatch, tmp_path):+ monkeypatch.setenv("JARVISCTL_CACHE_HOME", str(tmp_path))+ monkeypatch.setenv("JARVISCTL_BASE_URL", "http://127.0.0.1:47821")+ openapi_cache._write_cache(SPEC, base_url="http://127.0.0.1:47821")+ openapi_cache._write_cache(MARS_SPEC, base_url="http://127.0.0.1:47869")+ network = _no_network(monkeypatch)+ selected = entry.build_root_command(["--url", "http://127.0.0.1:47869", "--help"])+ assert "mars" in selected.commands["api"].commands+ assert "diag" not in selected.commands["api"].commands+ monkeypatch.setenv("_JARVISCTL_COMPLETE", "complete_bash")+ completed = entry.build_root_command(["--url=http://127.0.0.1:47869", "api", "mars"])+ assert "mars" in completed.commands["api"].commands+ foreign = entry.build_root_command(["--url", "http://127.0.0.1:47999", "--help"])+ assert "api" not in foreign.commands+ assert not network+++def test_structured_option_parse_never_calls_parameter_or_command_callbacks():+ def forbidden(*args, **kwargs):+ raise AssertionError("schema construction must not invoke callbacks")++ root = click.Group(+ callback=forbidden,+ params=[+ click.Option(["--url"], callback=forbidden),+ click.Option(["--key"], callback=forbidden),+ ],+ )+ values, command = entry._root_options(+ root,+ ["--url=http://127.0.0.1:47869", "--key", "fixture-key", "api", "--url=ignored"],+ )+ assert values == {"url": "http://127.0.0.1:47869", "key": "fixture-key"}+ assert command == "api"+++def test_dynamic_build_diagnostics_do_not_log_credentials(monkeypatch, tmp_path, caplog):+ monkeypatch.setenv("JARVISCTL_CACHE_HOME", str(tmp_path))+ caplog.set_level("DEBUG", logger=entry.__name__)+ credential = "fixture-private-key"++ def handler(_request):+ raise RuntimeError("transport diagnostic contains " + credential)++ _mock_transport(monkeypatch, handler)+ root = entry.build_root_command(["--key", credential, "api"])+ assert "api" not in root.commands+ assert credential not in caplog.text+ assert "RuntimeError" in caplog.text+++def test_dynamic_click_usage_error_uses_cli_exit_semantics(monkeypatch, tmp_path):+ monkeypatch.setenv("JARVISCTL_CACHE_HOME", str(tmp_path))+ _mock_transport(monkeypatch, lambda _request: httpx.Response(200, json=MARS_SPEC))+ root = entry.build_root_command(["api", "mars", "missing-command"])+ result = CliRunner().invoke(root, ["api", "mars", "missing-command"])+ assert result.exit_code == 2+ assert "No such command" in result.output+ assert "Traceback" not in result.output+++def test_dynamic_help_returns_success_in_nonstandalone_mode(monkeypatch, tmp_path):+ monkeypatch.setenv("JARVISCTL_CACHE_HOME", str(tmp_path))+ _mock_transport(monkeypatch, lambda _request: httpx.Response(200, json=MARS_SPEC))+ root = entry.build_root_command(["api", "mars", "--help"])+ result = CliRunner().invoke(root, ["api", "mars", "--help"], standalone_mode=False)+ assert result.exit_code == 0+ assert "definition" in result.outputdiff --git a/tests/unit/cli_ctl/test_module_entry_target.py b/tests/unit/cli_ctl/test_module_entry_target.pynew file mode 100644index 0000000000..d677cb729e--- /dev/null+++ b/tests/unit/cli_ctl/test_module_entry_target.py@@ -0,0 +1,123 @@+"""The real module entry point must never discard an explicit request target."""++from __future__ import annotations++import json+import runpy+import sys+from types import SimpleNamespace++import httpx+import pytest++from jarvis.cli_ctl import __main__ as canonical+from jarvis.cli_ctl import config+from jarvis.cli_ctl.client import JarvisClient++pytestmark = pytest.mark.filterwarnings(+ "ignore:.*jarvis.cli_ctl.__main__.*found in sys.modules.*:RuntimeWarning"+)++DEFAULT = "http://fallback.invalid:47900/default"+EXPLICIT = "http://127.0.0.1:47999/proxy"+LOCAL = "http://127.0.0.1:47998/local"+++def targets(monkeypatch):+ calls: list[tuple[str, str | None]] = []+ response = {"status": 200, "unreachable": False}++ def handler(request):+ calls.append((str(request.url), request.headers.get("Authorization")))+ if response["unreachable"]:+ raise httpx.ConnectError("fixture target unavailable", request=request)+ return httpx.Response(response["status"], json={"ok": response["status"] == 200})++ original = JarvisClient.__init__++ def initialize(self, base_url, control_key, **kwargs):+ original(+ self, base_url, control_key, **{**kwargs, "transport": httpx.MockTransport(handler)}+ )++ monkeypatch.setattr(JarvisClient, "__init__", initialize)+ monkeypatch.setattr(+ config,+ "resolve_profile",+ lambda: SimpleNamespace(base_url=DEFAULT, control_key="fixture-default"),+ )+ return calls, response+++def invoke_module(monkeypatch, args):+ monkeypatch.setattr(sys, "argv", ["jarvis.cli_ctl", *args])+ with pytest.raises(SystemExit) as outcome:+ runpy.run_module("jarvis.cli_ctl", run_name="__main__")+ return outcome.value.code++[email protected]("command", [["system", "status"], ["auth", "status"]])[email protected]("equals", [False, True])+def test_module_entry_uses_explicit_base_path_key_and_json(+ monkeypatch, targets, capsys, command, equals+):+ calls, _ = targets+ flags = (+ [f"--url={EXPLICIT}", "--key=fixture-explicit"]+ if equals+ else ["--url", EXPLICIT, "--key", "fixture-explicit"]+ )+ assert invoke_module(monkeypatch, [*flags, "--json", *command]) == 0+ assert calls == [(EXPLICIT + "/api/control/auth/probe", "Bearer fixture-explicit")]+ assert canonical.as_json() is True+ assert json.loads(capsys.readouterr().out)["reachable"] is True++[email protected]("failure", ["unreachable", "unauthorized"])[email protected]("command", [["system", "status"], ["auth", "status"]])+def test_explicit_target_failure_never_probes_a_discovered_server(+ monkeypatch, targets, capsys, failure, command+):+ calls, response = targets+ response.update(unreachable=failure == "unreachable", status=401)+ assert (+ invoke_module(+ monkeypatch, ["--url", EXPLICIT, "--key", "fixture-explicit", "--json", *command]+ )+ == 1+ )+ assert calls == [(EXPLICIT + "/api/control/auth/probe", "Bearer fixture-explicit")]+ assert json.loads(capsys.readouterr().out)["reachable"] is False+++def test_auth_local_options_override_root_without_default_target(monkeypatch, targets, capsys):+ calls, _ = targets+ assert (+ invoke_module(+ monkeypatch,+ [+ "--url",+ EXPLICIT,+ "--key",+ "fixture-explicit",+ "--json",+ "auth",+ "status",+ "--url",+ LOCAL,+ "--key",+ "fixture-local",+ ],+ )+ == 0+ )+ assert calls == [(LOCAL + "/api/control/auth/probe", "Bearer fixture-local")]+ assert json.loads(capsys.readouterr().out)["base_url"] == LOCAL+++def test_missing_explicit_target_retains_discovery(monkeypatch, targets, capsys):+ calls, _ = targets+ assert invoke_module(monkeypatch, ["--json", "system", "status"]) == 0+ assert calls == [(DEFAULT + "/api/control/auth/probe", "Bearer fixture-default")]+ assert json.loads(capsys.readouterr().out)["reachable"] is Truediff --git a/tests/unit/cli_ctl/test_openapi_cache.py b/tests/unit/cli_ctl/test_openapi_cache.pyindex 0b0b836265..b2e96a63eb 100644--- a/tests/unit/cli_ctl/test_openapi_cache.py+++ b/tests/unit/cli_ctl/test_openapi_cache.py@@ -1,16 +1,26 @@import json+import timeimport httpx+import pytestfrom jarvis.cli_ctl import openapi_cache as ocSPEC = {"openapi": "3.1.0", "info": {"version": "1"}, "paths": {}}-def _client(handler):+def _client(handler, *, base_url="http://t", control_key="jctl_k"):from jarvis.cli_ctl.client import JarvisClient- return JarvisClient("http://t", "jctl_k", transport=httpx.MockTransport(handler))+ return JarvisClient(base_url, control_key, transport=httpx.MockTransport(handler))+++def _cached(spec=SPEC, *, base_url="http://t", fetched_at=0):+ oc._write_cache(spec, base_url=base_url)+ path = oc._cache_path(base_url)+ entry = json.loads(path.read_text(encoding="utf-8"))+ entry["fetched_at"] = fetched_at+ path.write_text(json.dumps(entry), encoding="utf-8")def test_fetches_and_caches(tmp_path, monkeypatch):@@ -32,11 +42,7 @@ def test_fetches_and_caches(tmp_path, monkeypatch):def test_unreachable_falls_back_to_stale_cache(tmp_path, monkeypatch):monkeypatch.setenv("JARVISCTL_CACHE_HOME", str(tmp_path))- (tmp_path / "openapi.json").write_text(json.dumps(SPEC), encoding="utf-8")- (tmp_path / "openapi.meta.json").write_text(- json.dumps({"fetched_at": 0}),- encoding="utf-8",- )+ _cached()def handler(req):raise httpx.ConnectError("down")@@ -47,13 +53,7 @@ def test_unreachable_falls_back_to_stale_cache(tmp_path, monkeypatch):def test_stale_cache_refetches_when_reachable(tmp_path, monkeypatch):monkeypatch.setenv("JARVISCTL_CACHE_HOME", str(tmp_path))- (tmp_path / "openapi.json").write_text(- json.dumps({"openapi": "3.1.0", "info": {"version": "old"}, "paths": {}}),- encoding="utf-8",- )- (tmp_path / "openapi.meta.json").write_text(- json.dumps({"fetched_at": 0}), encoding="utf-8"- )+ _cached({"openapi": "3.1.0", "info": {"version": "old"}, "paths": {}})calls = {"n": 0}def handler(req):@@ -77,15 +77,10 @@ def test_no_cache_and_unreachable_returns_none(tmp_path, monkeypatch):def test_future_fetched_at_is_treated_as_stale(tmp_path, monkeypatch):"""Backward clock skew (VM restore) must not pin the cache 'fresh' forever."""- import time-monkeypatch.setenv("JARVISCTL_CACHE_HOME", str(tmp_path))- (tmp_path / "openapi.json").write_text(- json.dumps({"openapi": "3.1.0", "info": {"version": "old"}, "paths": {}}),- encoding="utf-8",- )- (tmp_path / "openapi.meta.json").write_text(- json.dumps({"fetched_at": time.time() + 10 * 24 * 3600}), encoding="utf-8"+ _cached(+ {"openapi": "3.1.0", "info": {"version": "old"}, "paths": {}},+ fetched_at=time.time() + 10 * 24 * 3600,)calls = {"n": 0}@@ -102,6 +97,195 @@ def test_refresh_clears_cache(tmp_path, monkeypatch):monkeypatch.setenv("JARVISCTL_CACHE_HOME", str(tmp_path))(tmp_path / "openapi.json").write_text("{}", encoding="utf-8")(tmp_path / "openapi.meta.json").write_text("{}", encoding="utf-8")+ oc._write_cache(SPEC, base_url="http://127.0.0.1:47821")+ oc._write_cache(SPEC, base_url="http://127.0.0.1:47869")+ (tmp_path / "unrelated.json").write_text("{}", encoding="utf-8")oc.clear_cache()assert not (tmp_path / "openapi.json").exists()assert not (tmp_path / "openapi.meta.json").exists()+ assert not list(tmp_path.glob("openapi-*.json"))+ assert (tmp_path / "unrelated.json").exists()+++def test_two_server_origins_keep_separate_fresh_and_offline_schemas(tmp_path, monkeypatch):+ monkeypatch.setenv("JARVISCTL_CACHE_HOME", str(tmp_path))+ first_url, second_url = "http://127.0.0.1:47821", "http://127.0.0.1:47869"+ second_spec = {**SPEC, "info": {"version": "mars"}}+ calls = []++ def handler(request):+ calls.append(request.url.port)+ return httpx.Response(200, json=SPEC if request.url.port == 47821 else second_spec)++ with (+ _client(handler, base_url=first_url) as first,+ _client(handler, base_url=second_url) as second,+ ):+ assert oc.load_spec(first) == SPEC+ assert oc.load_spec(second) == second_spec+ assert oc.load_spec(first) == SPEC+ assert oc.load_spec(second) == second_spec+ assert calls == [47821, 47869]++ def offline(_request):+ raise httpx.ConnectError("fixture offline")++ with (+ _client(offline, base_url=first_url) as first,+ _client(offline, base_url=second_url) as second,+ ):+ assert oc.load_spec(first, ttl_seconds=0) == SPEC+ assert oc.load_spec(second, ttl_seconds=0) == second_spec+++def test_an_unseen_offline_origin_never_receives_another_servers_schema(tmp_path, monkeypatch):+ monkeypatch.setenv("JARVISCTL_CACHE_HOME", str(tmp_path))+ oc._write_cache(SPEC, base_url="http://127.0.0.1:47821")++ def offline(_request):+ raise httpx.ConnectError("fixture offline")++ with _client(offline, base_url="http://127.0.0.1:47869") as other:+ assert oc.load_spec(other) is None+++def test_legacy_unbound_cache_is_not_trusted_for_offline_commands(tmp_path, monkeypatch):+ monkeypatch.setenv("JARVISCTL_CACHE_HOME", str(tmp_path))+ (tmp_path / "openapi.json").write_text(json.dumps(SPEC), encoding="utf-8")+ (tmp_path / "openapi.meta.json").write_text(+ json.dumps({"fetched_at": time.time()}), encoding="utf-8"+ )++ def offline(_request):+ raise httpx.ConnectError("fixture offline")++ with _client(offline) as client:+ assert oc.load_spec(client) is None+++def test_origin_metadata_and_cache_filenames_never_contain_credentials(tmp_path, monkeypatch):+ monkeypatch.setenv("JARVISCTL_CACHE_HOME", str(tmp_path))+ url = (+ "https://fixture-user:[email protected]:443/?key=fixture-query#fixture-fragment"+ )+ with _client(+ lambda _request: httpx.Response(200, json=SPEC),+ base_url=url,+ control_key="fixture-control-key",+ ) as client:+ assert oc.load_spec(client) == SPEC+ stored = "".join(path.name + path.read_text(encoding="utf-8") for path in tmp_path.iterdir())+ for private in (+ "fixture-user",+ "fixture-password",+ "fixture-query",+ "fixture-fragment",+ "fixture-control-key",+ ):+ assert private not in stored+ spec, meta = oc._read_cache(base_url="https://example.test")+ assert spec == SPEC and meta["origin"] == "https://example.test"+++def test_mismatched_origin_metadata_is_rejected_even_in_matching_filename(tmp_path, monkeypatch):+ monkeypatch.setenv("JARVISCTL_CACHE_HOME", str(tmp_path))+ _cached()+ path = oc._cache_path("http://t")+ entry = json.loads(path.read_text(encoding="utf-8"))+ entry["origin"] = "http://other"+ path.write_text(json.dumps(entry), encoding="utf-8")+ assert oc._read_cache(base_url="http://t") == (None, {})+++def test_http_credential_refusal_is_not_offline_cache_fallback(tmp_path, monkeypatch):+ monkeypatch.setenv("JARVISCTL_CACHE_HOME", str(tmp_path))+ _cached()+ with _client(lambda _request: httpx.Response(401, json={"detail": "unauthorized"})) as client:+ assert oc.load_spec(client, ttl_seconds=0) is None+++def test_two_base_paths_on_one_origin_keep_separate_schemas(tmp_path, monkeypatch):+ monkeypatch.setenv("JARVISCTL_CACHE_HOME", str(tmp_path))+ primary_url, mars_url = "http://127.0.0.1:47869/primary", "http://127.0.0.1:47869/mars"+ mars_spec = {**SPEC, "info": {"version": "mars"}}+ requests = []++ def handler(request):+ requests.append(request.url.path)+ return httpx.Response(+ 200, json=SPEC if request.url.path.startswith("/primary/") else mars_spec+ )++ with (+ _client(handler, base_url=primary_url) as primary,+ _client(handler, base_url=mars_url) as mars,+ ):+ assert oc.load_spec(primary) == SPEC+ assert oc.load_spec(mars) == mars_spec+ assert oc.load_spec(primary) == SPEC+ assert oc.load_spec(mars) == mars_spec+ assert requests == ["/primary/api/openapi.json", "/mars/api/openapi.json"]+ assert oc._cache_path(primary_url) != oc._cache_path(mars_url)++ def offline(_request):+ raise httpx.ConnectError("fixture offline")++ with (+ _client(offline, base_url=primary_url + "/") as primary,+ _client(offline, base_url=mars_url) as mars,+ ):+ assert oc.load_spec(primary, ttl_seconds=0) == SPEC+ assert oc.load_spec(mars, ttl_seconds=0) == mars_spec+ with _client(offline, base_url="http://127.0.0.1:47869/another") as unseen:+ assert oc.load_spec(unseen) is None+++def test_base_path_normalization_preserves_httpx_request_boundaries():+ assert oc._cache_path("https://example.test/mars") == oc._cache_path(+ "https://EXAMPLE.test:443/mars/"+ )+ assert oc._cache_path("https://example.test/mars/") != oc._cache_path(+ "https://example.test/mars//"+ )+ assert oc._cache_path("https://example.test/a%2Fb") != oc._cache_path(+ "https://example.test/a/b"+ )+++ "status,payload",+ [+ (200, {"detail": "login required"}),+ (200, []),+ (200, "<html>Login</html>"),+ (200, {"openapi": "3.1.0", "info": {}, "paths": []}),+ (302, "<html>Redirecting to login</html>"),+ ],+)+def test_reachable_invalid_schema_never_uses_or_caches_stale_commands(+ tmp_path, monkeypatch, status, payload+):+ monkeypatch.setenv("JARVISCTL_CACHE_HOME", str(tmp_path))+ _cached()++ def handler(_request):+ if isinstance(payload, str):+ return httpx.Response(status, text=payload, headers={"Location": "/login"})+ return httpx.Response(status, json=payload)++ with _client(handler) as client:+ assert oc.load_spec(client, ttl_seconds=0) is None+ # The invalid response did not replace the known schema in the offline cache.+ assert oc._read_cache(base_url="http://t")[0] == SPEC+++def test_invalid_cache_payload_and_direct_invalid_write_are_rejected(tmp_path, monkeypatch):+ monkeypatch.setenv("JARVISCTL_CACHE_HOME", str(tmp_path))+ _cached()+ path = oc._cache_path("http://t")+ entry = json.loads(path.read_text(encoding="utf-8"))+ entry["spec"] = {"detail": "login required"}+ path.write_text(json.dumps(entry), encoding="utf-8")+ assert oc._read_cache(base_url="http://t") == (None, {})+ with pytest.raises(ValueError, match="invalid OpenAPI schema"):+ oc._write_cache({"detail": "login required"}, base_url="http://t")diff --git a/tests/unit/plugins/brain/test_tool_output_efficiency.py b/tests/unit/plugins/brain/test_tool_output_efficiency.pynew file mode 100644index 0000000000..be310fdb18--- /dev/null+++ b/tests/unit/plugins/brain/test_tool_output_efficiency.py@@ -0,0 +1,154 @@+"""Lossless tool-output transport: fewer tokens without limiting model evidence."""++import json+from types import SimpleNamespace++import pytest++from jarvis.brain.tool_use_loop import ToolUseLoop+from jarvis.core.protocols import BrainDelta, BrainMessage, ToolResult+from jarvis.live.session import LiveVoiceSession+from jarvis.plugins.brain._openai_base import (+ _chat_messages_to_responses_input,+ _to_openai_messages,+)+++def _message(content, call_id="call_1"):+ return BrainMessage(role="tool", content=content, tool_call_id=call_id)+++def _envelope(content):+ return [{"type": "tool_result", "tool_use_id": "call_1", "content": content}]+++ "content",+ ["", " first\n\nsecond ", "repeat " * 40_000],+ ids=["empty", "whitespace", "large-result"],+)+def test_canonical_output_is_verbatim_without_a_new_size_limit(content):+ wire = _to_openai_messages((_message(_envelope(content)),), None)+ assert wire == [{"role": "tool", "content": content, "tool_call_id": "call_1"}]+ _, responses = _chat_messages_to_responses_input(wire)+ assert responses == [{"type": "function_call_output", "call_id": "call_1", "output": content}]+++def test_json_result_is_not_encoded_twice_or_stripped_of_failure_evidence():+ payload = {+ "success": False,+ "output": {"items": [1, 1, None], "text": '日本語 • "quoted"\n indentation'},+ "error": "denied",+ "confirmation_required": True,+ }+ original = json.dumps(payload, ensure_ascii=False)+ wire = _to_openai_messages((_message(_envelope(original)),), None)[0]+ assert wire["content"] == original+ assert json.loads(wire["content"]) == payload+ assert len(wire["content"]) < len(json.dumps(_envelope(original)))+++ "content,call_id",+ [+ (_envelope("a") + _envelope("b"), "call_1"),+ (_envelope("do not discard mismatched evidence"), "different_call"),+ (_envelope("no outer call id"), None),+ ([{"type": "text", "text": "keep every block"}], "call_1"),+ ([{**_envelope("failed")[0], "is_error": True}], "call_1"),+ ([{**_envelope("keep metadata")[0], "annotations": {"source": "original"}}], "call_1"),+ ],+)+def test_noncanonical_blocks_and_metadata_round_trip_in_full(content, call_id):+ wire = _to_openai_messages((_message(content, call_id),), None)[0]+ assert json.loads(wire["content"]) == content+ assert wire["tool_call_id"] == (call_id or "")+++def test_user_and_assistant_text_and_tool_arguments_are_not_rewritten():+ args = {"text": ' café\n日本語 "value" ', "repeat": [1, 1, 2]}+ original = (+ BrainMessage(role="user", content=" Keep my exact wording.\n"),+ BrainMessage(role="assistant", content=" Same here.\n"),+ BrainMessage(+ role="assistant",+ content=[+ {+ "type": "tool_use",+ "id": "call_1",+ "name": "read_data",+ "input": args,+ }+ ],+ ),+ )+ wire = _to_openai_messages(original, "Keep every fact.")+ assert wire[1]["content"] == original[0].content+ assert wire[2]["content"] == original[1].content+ assert json.loads(wire[3]["tool_calls"][0]["function"]["arguments"]) == args+++def test_plain_tool_strings_remain_opaque():+ content = '[{"type":"tool_result","content":"literal user document"}]'+ wire = _to_openai_messages((_message(content),), None)+ assert wire[0]["content"] == content++[email protected]("success", [True, False])+async def test_tool_loop_compacts_structure_but_preserves_all_evidence(success):+ payload = {"items": [{"text": " café\n日本語 ", "index": i} for i in range(40)]}++ class Brain:+ requests = []++ async def complete(self, request):+ self.requests.append(request)+ if len(self.requests) == 1:+ yield BrainDelta(tool_call={"id": "call_1", "name": "read_data", "input": {}})+ yield BrainDelta(finish_reason="tool_use")+ else:+ yield BrainDelta(content="Verified response.")+ yield BrainDelta(finish_reason="stop")++ class Executor:+ async def execute(self, *args, **kwargs):+ return ToolResult(success=success, output=payload, error=None if success else "denied")++ brain = Brain()+ loop = ToolUseLoop(+ brain, {"read_data": SimpleNamespace(name="read_data", schema={})}, Executor()+ )+ await loop.run([], user_utterance="Read the dataset.")+ messages = brain.requests[-1].messages+ wire = next(m for m in _to_openai_messages(messages, None) if m["role"] == "tool")+ expected = {"success": success, "output": payload, "error": None if success else "denied"}+ assert json.loads(wire["content"]) == expected+ assert len(wire["content"]) < len(json.dumps(expected, ensure_ascii=False))+++async def test_live_result_keeps_unicode_and_every_list_item():+ sent = []+ payload = {"success": True, "output": [" 日本語\n café " for _ in range(400)]}++ async def execute(*args):+ return dict(payload)++ async def send(event):+ sent.append(event)++ session = LiveVoiceSession(+ session_id="s",+ send_binary=send,+ send_json=send,+ providers=[SimpleNamespace(name="test")],+ config=SimpleNamespace(brain=SimpleNamespace(reply_language="en")),+ )+ session._tools = SimpleNamespace(execute=execute, end_requested=False)+ session._connection = SimpleNamespace(send=send)+ await session._run_calls([{"call_id": "call_1", "name": "read_data", "arguments": "{}"}], 0)+ output = sent[0]["item"]["output"]+ assert json.loads(output) == {**payload, "artifacts": []}+ assert "日本語" in output+ assert sent[-1] == {"type": "response.create"}diff --git a/tests/unit/pointer/test_intent.py b/tests/unit/pointer/test_intent.pyindex d49913a6ce..e2f93441e0 100644--- a/tests/unit/pointer/test_intent.py+++ b/tests/unit/pointer/test_intent.py@@ -8,6 +8,8 @@ noun ("was ist das fuer ein Wetter?"). See docs/plans/ai-pointer/DESIGN.md sec 5from __future__ import annotations+from time import perf_counter+import pytestfrom jarvis.pointer.intent import is_pointing_intent@@ -33,6 +35,14 @@ from jarvis.pointer.intent import is_pointing_intent"What's this thing?","Explain this, right here","What am I pointing at?",+ "What is written here?",+ "What is written\nhere?",+ "Was steht\nhier?",+ "Kannst du lesen,\nwas hier steht?",+ "What did I write here?",+ "Who wrote the text here?",+ "Please pause. What is written here?",+ "Read the label here, please.",],)def test_fires_on_deictic_pointing(text: str) -> None:@@ -63,6 +73,42 @@ def test_does_not_fire_on_non_deictic(text: str) -> None:assert is_pointing_intent(text) is False+ "text",+ [+ "Write an internal announcement. Return the draft text here for human review.",+ "Write an internal announcement here for human review.",+ "She writes an internal announcement here for human review.",+ "I wrote an internal announcement here for human review.",+ (+ "[assignment from the user]\n"+ "Prepare a communication draft for review. Do not send or publish it.\n\n"+ "Write an internal announcement. Return the draft text here for human review."+ ),+ "Lies den Bericht. Antworte hier im Chat.",+ ],+)+def test_composition_and_reply_location_are_not_pointing(text: str) -> None:+ assert is_pointing_intent(text) is False++[email protected]("separator", [". ", "! ", "? ", "; ", "\n", "\r\n"])[email protected]("lead", ["Read the report", "What did I write"])+def test_weak_visual_reference_does_not_borrow_another_sentences_location(+ separator: str, lead: str+) -> None:+ text = f"{lead}{separator}Return the summary here for review."+ assert is_pointing_intent(text) is False+++def test_long_whitespace_without_a_location_does_not_stall_the_gate() -> None:+ # Overlapping optional whitespace runs previously took many seconds here.+ text = "read" + " " * 32768 + "end"+ started = perf_counter()+ assert is_pointing_intent(text) is False+ assert perf_counter() - started < 2.0++def test_strong_phrase_beats_veto() -> None:# A genuine pointing question can still contain a "das fuer ein" fragment.text = "Was ist das fuer ein schoenes Bild, worauf ich zeige?"diff --git a/tests/unit/realtime/test_session.py b/tests/unit/realtime/test_session.pyindex bab9281c73..ac5c04d1c6 100644--- a/tests/unit/realtime/test_session.py+++ b/tests/unit/realtime/test_session.py@@ -314,6 +314,10 @@ class FakeToolBridge:self.calls = []self.closed = False+ @property+ def has_pending_confirmation(self) -> bool:+ return False+def set_language(self, language):self.languages.append(language)diff --git a/tests/unit/society/test_browser_shutdown.py b/tests/unit/society/test_browser_shutdown.pynew file mode 100644index 0000000000..72262d2599--- /dev/null+++ b/tests/unit/society/test_browser_shutdown.py@@ -0,0 +1,150 @@+"""Cancellation must release real owned children without a browser installation."""++from __future__ import annotations++import asyncio+import sys++import pytest++from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS+from jarvis.society.browser.live import LiveSession, LiveUpdates+from jarvis.society.runtime import SocietyRuntime, current_runtime+from tests.fakes.fake_society_shutdown import RecordingProcessTree, society_shutdown_server+++async def owned_child(*, respond=True):+ script = """+import json+import sys+import time+print('READY', flush=True)+for line in sys.stdin:+ message = json.loads(line)+ print(json.dumps({'kind': 'state', 'phase': 'shutdown-request'}), flush=True)+ if sys.argv[1] == 'respond':+ print(json.dumps({'kind': 'response', 'id': message['id'], 'ok': True}), flush=True)+ time.sleep(60)+"""+ proc = await asyncio.create_subprocess_exec(+ sys.executable,+ "-u",+ "-c",+ script,+ "respond" if respond else "stall",+ stdin=asyncio.subprocess.PIPE,+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.PIPE,+ creationflags=NO_WINDOW_CREATIONFLAGS,+ )+ try:+ assert (await asyncio.wait_for(proc.stdout.readline(), timeout=3)).strip() == b"READY"+ except BaseException:+ await reap(proc)+ raise+ return proc+++async def live_session(*, respond=True):+ proc = await owned_child(respond=respond)+ tree = RecordingProcessTree()+ session = LiveSession("fixture", proc, tree)+ updates = LiveUpdates()+ session.subscribers.add(updates)+ session.readers = [+ asyncio.create_task(session.read()),+ asyncio.create_task(session.drain_stderr()),+ ]+ return session, updates+++async def reap(proc):+ if proc.returncode is None:+ proc.kill()+ await asyncio.wait_for(proc.wait(), timeout=3)+++async def test_cancel_during_shutdown_command_reaps_owned_process():+ session, updates = await live_session(respond=False)+ closing = asyncio.create_task(session.close())+ try:+ assert (await asyncio.wait_for(updates.get(), timeout=2))["phase"] == "shutdown-request"+ closing.cancel()+ with pytest.raises(asyncio.CancelledError):+ await asyncio.wait_for(closing, timeout=3)+ assert session.proc.returncode is not None+ assert session.tree.closes >= 1+ assert session.closed+ assert all(task.done() for task in session.readers)+ finally:+ await reap(session.proc)+ await asyncio.gather(closing, *session.readers, return_exceptions=True)+++async def test_server_deadline_reaps_live_and_one_shot_browser_children(tmp_path):+ runtime = SocietyRuntime(tmp_path)+ await runtime.ensure_started()+ server, cleaned = society_shutdown_server(runtime)+ session = None+ job = None+ try:+ session, _updates = await live_session()+ runtime.browser.live.sessions[session.agent_id] = session+ job = await owned_child()+ runtime.browser._procs["one-shot"] = job+ # The child acknowledges shutdown but never exits voluntarily. Exercise+ # the production five-second server deadline, not a replaced close call.+ with pytest.raises(RuntimeError, match="society_runtime_shutdown_incomplete"):+ await asyncio.wait_for(server.stop(), timeout=10)+ assert session.proc.returncode is not None and job.returncode is not None+ assert session.tree.closes >= 1+ assert session.closed and all(task.done() for task in session.readers)+ assert not runtime.browser.live.sessions+ assert not runtime.browser._procs+ assert runtime.store._conn is None+ assert current_runtime() is None+ assert {"chat", "pty", "mission-approvals"} <= set(cleaned)+ finally:+ if session is not None:+ await reap(session.proc)+ if job is not None:+ await reap(job)+ await runtime.close()+++async def test_lingering_rpc_keeps_session_handle_for_cleanup_retry(tmp_path, monkeypatch):+ from jarvis.society.browser import live as live_module++ session, _updates = await live_session()+ await reap(session.proc)+ await asyncio.gather(*session.readers, return_exceptions=True)+ live = live_module.LiveSessions(tmp_path)+ live.sessions[session.agent_id] = session+ entered = asyncio.Event()+ release = asyncio.Event()++ async def reluctant_rpc():+ entered.set()+ while not release.is_set():+ try:+ await release.wait()+ except asyncio.CancelledError:+ continue # Deliberately resist cleanup until this fixture releases it.++ task = asyncio.create_task(reluctant_rpc())+ session.tasks.add(task)+ await entered.wait()+ monkeypatch.setattr(live_module, "_FORCED_CLOSE_TIMEOUT_S", 0.02)+ try:+ with pytest.raises(TimeoutError, match="browser process cleanup incomplete"):+ await live.close()+ assert not task.done()+ assert live.sessions[session.agent_id] is session+ release.set()+ await task+ await live.close()+ assert not live.sessions and not live._closing_tasks+ finally:+ release.set()+ await task+ await live.close()diff --git a/tests/unit/society/test_chat_binding.py b/tests/unit/society/test_chat_binding.pyindex e93adb6a49..37a8df501b 100644--- a/tests/unit/society/test_chat_binding.py+++ b/tests/unit/society/test_chat_binding.py@@ -123,8 +123,11 @@ async def test_deliver_hook_frames_and_sends(world):("society:scout","[query from Archivist]\nWhere is the VPS note?\nRefs: wiki:society/archivist/vps.md\n"+ f"Message id: {env.event_id}; sender id: archivist\n""Reply to the sender using society_message_agent with kind 'answer'. "- "This is internal communication; do not use an external messaging connector.",+ "Include the actual findings or decision; use reply_status=blocked if you "+ "cannot answer. This is internal communication; do not use an external "+ "messaging connector. No preliminary acknowledgement is needed.",)]svc.busy.add("society:scout")@@ -146,7 +149,7 @@ def test_result_frame_carries_the_handoff():},)text = frame_incoming(env, "Scout")- assert text.splitlines() == [+ assert text.splitlines()[:5] == ["[result from Scout]","Status: partial","Done: Found three providers.",diff --git a/tests/unit/society/test_creator_inherit.py b/tests/unit/society/test_creator_inherit.pynew file mode 100644index 0000000000..7e92f86a12--- /dev/null+++ b/tests/unit/society/test_creator_inherit.py@@ -0,0 +1,165 @@+"""A society agent that creates a teammate copies its seat and permissions."""++from __future__ import annotations++from pathlib import Path++from fastapi import FastAPI+from fastapi.testclient import TestClient++from jarvis.society.events import AgentState, GrantMode, PermissionCeiling+from jarvis.society.inherit import inherit_creator_fields+from jarvis.society.runtime import SocietyRuntime+from jarvis.ui.web.society_routes import router+++def _client(tmp_path: Path) -> tuple[TestClient, SocietyRuntime]:+ runtime = SocietyRuntime(tmp_path, seed_starter_team=False)+ app = FastAPI()+ app.include_router(router)+ app.state.society_factory = lambda: runtime+ return TestClient(app), runtime+++async def test_inherit_fills_blank_seat_and_permissions_and_caps_a_raise(tmp_path: Path) -> None:+ runtime = SocietyRuntime(tmp_path, seed_starter_team=False)+ await runtime.ensure_started()+ creator, _ = await runtime.roster.create(+ name="Bot Maker",+ provider="grok-build",+ model="grok-4.6",+ effort="high",+ account_id="acc-super",+ permission_ceiling="monitor",+ grant_mode="allowlist",+ grants=["plugin:gmail", "cli:gh"],+ denies=["core:run-shell"],+ )+ filled = inherit_creator_fields({}, creator)+ assert filled["provider"] == "grok-build"+ assert filled["model"] == "grok-4.6"+ assert filled["effort"] == "high"+ assert filled["account_id"] == "acc-super"+ assert filled["permission_ceiling"] == "monitor"+ assert filled["grant_mode"] == "allowlist"+ assert filled["grants"] == ["cli:gh", "plugin:gmail"] or filled["grants"] == [+ "plugin:gmail",+ "cli:gh",+ ]+ assert filled["denies"] == ["core:run-shell"]+ assert filled["parent_agent_id"] == creator.agent_id++ capped = inherit_creator_fields(+ {+ "provider": "openai",+ "model": "gpt-5",+ "permission_ceiling": "ask",+ "grant_mode": "all",+ "grants": ["plugin:gmail", "plugin:spotify"],+ "denies": ["core:search-web"],+ },+ creator,+ )+ assert capped["provider"] == "openai" and capped["model"] == "gpt-5"+ assert capped["permission_ceiling"] == "monitor"+ assert capped["grant_mode"] == "allowlist"+ assert capped["grants"] == ["plugin:gmail"]+ assert "core:run-shell" in capped["denies"] and "core:search-web" in capped["denies"]+++async def test_create_from_society_session_inherits_seat_and_permissions(tmp_path: Path) -> None:+ client, runtime = _client(tmp_path)+ await runtime.ensure_started()+ creator, _ = await runtime.roster.create(+ name="Bot Maker",+ provider="grok-build",+ model="grok-4.6",+ effort="high",+ account_id="acc-super",+ permission_ceiling="ask",+ grant_mode="allowlist",+ grants=["plugin:gmail", "cli:gh"],+ denies=["core:run-shell"],+ )+ with client as c:+ res = c.post(+ "/api/society/agents",+ json={+ "name": "Mail Helper",+ "title": "Mail assistant",+ "description": "Sort mail and draft replies.",+ },+ headers={"X-Jarvis-Chat-Session": creator.session_id},+ )+ assert res.status_code == 200, res.text+ body = res.json()["agent"]+ assert body["created"] is True if "created" in body else res.json()["created"] is True+ agent = res.json()["agent"]+ assert agent["provider"] == "grok-build"+ assert agent["model"] == "grok-4.6"+ assert agent["effort"] == "high"+ assert agent["account_id"] == "acc-super"+ assert agent["permission_ceiling"] == "ask"+ assert agent["grant_mode"] == "allowlist"+ assert agent["grants"] == ["cli:gh", "plugin:gmail"]+ assert agent["denies"] == ["core:run-shell"]+ assert agent["parent_agent_id"] == creator.agent_id+ assert agent["permission_ceiling"] == str(PermissionCeiling.ASK)+ assert GrantMode(agent["grant_mode"]) is GrantMode.ALLOWLIST+++async def test_ui_create_without_session_keeps_defaults_and_explicit_seat(tmp_path: Path) -> None:+ client, runtime = _client(tmp_path)+ await runtime.ensure_started()+ await runtime.roster.create(+ name="Bot Maker",+ provider="grok-build",+ model="grok-4.6",+ account_id="acc-super",+ permission_ceiling="ask",+ grant_mode="allowlist",+ grants=["plugin:gmail"],+ )+ with client as c:+ blank = c.post("/api/society/agents", json={"name": "Scout"}).json()["agent"]+ picked = c.post(+ "/api/society/agents",+ json={+ "name": "Keyed",+ "provider": "openai",+ "model": "gpt-5",+ "permission_ceiling": "safe",+ "grant_mode": "all",+ },+ ).json()["agent"]+ assert blank["provider"] == ""+ assert blank["model"] == ""+ assert blank["account_id"] == ""+ assert blank["permission_ceiling"] == "monitor"+ assert blank["grant_mode"] == "all"+ assert blank["parent_agent_id"] is None+ assert picked["provider"] == "openai"+ assert picked["model"] == "gpt-5"+ assert picked["permission_ceiling"] == "safe"+ assert picked["grant_mode"] == "all"+++async def test_paused_creator_session_does_not_inherit(tmp_path: Path) -> None:+ client, runtime = _client(tmp_path)+ await runtime.ensure_started()+ creator, _ = await runtime.roster.create(+ name="Bot Maker",+ provider="grok-build",+ model="grok-4.6",+ permission_ceiling="ask",+ )+ await runtime.roster.update(creator.agent_id, {"state": AgentState.PAUSED})+ with client as c:+ agent = c.post(+ "/api/society/agents",+ json={"name": "Kid"},+ headers={"X-Jarvis-Chat-Session": creator.session_id},+ ).json()["agent"]+ assert agent["provider"] == ""+ assert agent["permission_ceiling"] == "monitor"+ assert agent["parent_agent_id"] is Nonediff --git a/tests/unit/society/test_lead_card.py b/tests/unit/society/test_lead_card.pyindex a05d38c18a..b5ad1e289e 100644--- a/tests/unit/society/test_lead_card.py+++ b/tests/unit/society/test_lead_card.py@@ -177,6 +177,7 @@ def test_the_rule_block_names_the_tools_and_buries_the_old_system():assert "never from the retired sub-agent or mission-worker system" in cardassert "spawn_worker is only for heavy background work" in cardassert "Agentic IDE" in card and "are NOT agents of this society" in card+ assert "copies its own model seat and permission setup" in cardasync def test_society_agent_names_feed_the_realtime_path(rt: SocietyRuntime):diff --git a/tests/unit/society/test_mars_navigation.py b/tests/unit/society/test_mars_navigation.pynew file mode 100644index 0000000000..226daa87b3--- /dev/null+++ b/tests/unit/society/test_mars_navigation.py@@ -0,0 +1,488 @@+"""Real SQLite fixtures for bounded, renderer-independent logical travel."""++from __future__ import annotations++import asyncio++import pytest++from jarvis.society.mars.models import StationError+from jarvis.society.mars.navigation import NavigationGraph+from jarvis.society.mars.navigation_models import MoveCommand, NavigationState, TravelMode+from jarvis.society.mars.navigation_service import MarsNavigationService+from jarvis.society.mars.navigation_store import MarsNavigationStore+++class Clock:+ now = 100_000++ def __call__(self):+ return self.now+++class Authority:+ def __init__(self):+ self.calls = []+ self.allowed = True++ async def __call__(self, agent_id, station_id, mode):+ self.calls.append((agent_id, station_id, mode))+ return self.allowed+++def definition(*, alternate=False):+ nodes = [+ {"id": "a", "position": [0, 0, 0]},+ {"id": "b", "position": [4, 0, 0]},+ {"id": "c", "position": [8, 0, 0]},+ {"id": "d", "position": [4, 0, 4]},+ ]+ edges = [+ {"id": "ab", "from": "a", "to": "b", "width": 7, "modes": ["pedestrian", "rover"]},+ {"id": "bc", "from": "b", "to": "c", "width": 2.4, "modes": ["pedestrian"]},+ {"id": "cd", "from": "c", "to": "d", "width": 2.4, "modes": ["pedestrian"]},+ ]+ if alternate:+ edges.extend(+ [+ {"id": "bd", "from": "b", "to": "d", "width": 2.4, "modes": ["pedestrian"]},+ ]+ )+ return {+ "world_id": "mars:ordinary",+ "layout_version": 1,+ "spawn": {"position": [0, 0, 0]},+ "navigation": {"version": 1, "nodes": nodes, "edges": edges},+ "stations": [+ {"id": "destination", "anchor": "c", "capacity": 1},+ {"id": "middle", "anchor": "b", "capacity": 1},+ {"id": "origin", "anchor": "a", "capacity": 1},+ {"id": "parking", "anchor": "d", "capacity": 1},+ ],+ }+++def request(identity="visit", station="destination", mode=TravelMode.PEDESTRIAN):+ return MoveCommand(request_id=identity, station_id=station, mode=mode)+++async def runtime(tmp_path):+ clock, authority = Clock(), Authority()+ store = MarsNavigationStore(tmp_path / "navigation.db", clock_ms=clock)+ service = MarsNavigationService(store, definition(), authorize=authority)+ await service.start()+ try:+ yield service, clock, authority+ finally:+ await service.close()+++async def tick(service, clock, count=1, *, interval=1000, **kwargs):+ for _ in range(count):+ clock.now += interval+ await service.advance(**kwargs)+++async def test_duplicate_requests_authorize_once_and_keep_stable_identity(runtime):+ service, _, authority = runtime+ records = await asyncio.gather(*(service.submit("agent", request()) for _ in range(8)))+ assert len({record.command_id for record in records}) == 1+ assert len(authority.calls) == 1+ assert records[0].placement == "canonical_spawn"+ assert records[0].position == (0, 0, 0)+ with pytest.raises(StationError, match="idempotency_payload_mismatch"):+ await service.submit("agent", request(station="middle"))+++async def test_authorization_denial_and_nonboolean_fail_closed_without_persistence(runtime):+ service, _, authority = runtime+ for value in [False, None, {"allowed": True}]:+ authority.allowed = value+ with pytest.raises(StationError, match="navigation_not_authorized"):+ await service.submit("agent", request())+ assert (await service.snapshot()).commands == ()+++async def test_authorization_timeout_is_bounded_and_public(runtime):+ service, _, _ = runtime++ async def wait_forever(*args):+ await asyncio.Event().wait()++ service.authorize = wait_forever+ service.authorization_timeout_s = 0.001+ with pytest.raises(StationError, match="navigation_authorization_unavailable"):+ await service.submit("agent", request())+ assert (await service.snapshot()).commands == ()+++async def test_arrived_body_retains_station_after_lease_expiry_and_cancel(runtime):+ service, clock, _ = runtime+ first = await service.submit("first", request())+ second = await service.submit("second", request())+ await tick(service, clock, 5)+ assert (await service.store.get(first.command_id)).state is NavigationState.ARRIVED+ waiting = await service.store.get(second.command_id)+ assert waiting.state is NavigationState.QUEUEING+ assert waiting.position == (0, 0, 0)+ await tick(service, clock, 16)+ assert (await service.store.get(second.command_id)).state is NavigationState.QUEUEING+ assert all(lease.command_id != first.command_id for lease in (await service.snapshot()).leases)+ await service.cancel("first", first.command_id)+ await tick(service, clock, 3)+ assert (await service.store.get(second.command_id)).position == (0, 0, 0)+ occupancy = (await service.snapshot()).occupancies+ assert (+ next(body for body in occupancy if body.resource_id == "station:destination").agent_id+ == "first"+ )+ departure = await service.submit("first", request("depart", station="parking"))+ # Accepting departure does not itself free a physical station slot.+ assert (await service.snapshot()).occupancies[0].position == (8, 0, 0)+ await tick(service, clock, 9)+ assert (await service.store.get(departure.command_id)).state is NavigationState.ARRIVED+ assert (await service.store.get(second.command_id)).state is NavigationState.ARRIVED+ latest = {row.agent_id: row for row in (await service.snapshot()).commands}+ assert latest["first"].position != latest["second"].position+++async def test_cancel_releases_resources_and_preserves_mid_edge_for_new_request(runtime):+ service, clock, _ = runtime+ first = await service.submit("first", request())+ await tick(service, clock)+ moving = await service.store.get(first.command_id)+ assert 0 < moving.edge_progress < 1+ canceled = await service.cancel("first", first.command_id)+ assert canceled.position == moving.position+ assert (await service.snapshot()).leases == ()+ occupancy = (await service.snapshot()).occupancies+ assert len(occupancy) == 1 and occupancy[0].resource_id == "edge:ab"+ resumed = await service.submit("first", request("next"))+ assert resumed.placement == "persisted"+ assert resumed.position == canceled.position+ assert resumed.edge_progress == canceled.edge_progress+ await tick(service, clock)+ assert (await service.store.get(resumed.command_id)).position[0] > canceled.position[0]+++async def test_cancel_cannot_stop_another_agent_or_reset_its_position(runtime):+ service, clock, _ = runtime+ record = await service.submit("first", request())+ await tick(service, clock)+ before = await service.store.get(record.command_id)+ with pytest.raises(StationError, match="navigation_command_not_found"):+ await service.cancel("second", record.command_id)+ assert await service.store.get(record.command_id) == before+++async def test_agent_has_one_active_journey_and_queue_is_bounded(runtime):+ service, _, _ = runtime+ service.store.queue_limit = 2+ await service.submit("first", request())+ with pytest.raises(StationError, match="agent_already_moving"):+ await service.submit("first", request("second"))+ await service.submit("second", request())+ with pytest.raises(StationError, match="navigation_queue_full"):+ await service.submit("third", request())+++async def test_mid_edge_obstruction_stops_in_place_and_exhausts_retry_budget(runtime):+ service, clock, _ = runtime+ record = await service.submit("first", request())+ await tick(service, clock)+ moving = await service.store.get(record.command_id)+ await tick(service, clock, blocked_edges=["ab"])+ blocked = await service.store.get(record.command_id)+ assert blocked.state is NavigationState.TEMPORARILY_BLOCKED+ assert blocked.position == moving.position+ await tick(service, clock, 10, blocked_edges=["ab"])+ failed = await service.store.get(record.command_id)+ assert failed.state is NavigationState.UNREACHABLE+ assert failed.reason == "navigation_retry_exhausted"+ assert failed.position == moving.position+ assert (await service.snapshot()).leases == ()+++async def test_route_replans_at_safe_node_around_new_block(tmp_path):+ clock = Clock()+ service = MarsNavigationService(+ MarsNavigationStore(tmp_path / "alternate.db", clock_ms=clock),+ definition(alternate=True),+ authorize=Authority(),+ )+ await service.start()+ try:+ record = await service.submit("agent", request())+ await tick(service, clock)+ await tick(service, clock, blocked_edges=["bc"])+ rerouting = await service.store.get(record.command_id)+ assert rerouting.state is NavigationState.REROUTING+ assert "bc" not in rerouting.path+ await tick(service, clock, 10, blocked_edges=["bc"])+ assert (await service.store.get(record.command_id)).state is NavigationState.ARRIVED+ finally:+ await service.close()+++async def test_rover_cannot_reach_pedestrian_only_console(runtime):+ service, _, _ = runtime+ assert service.graph.path("a", "destination", TravelMode.ROVER) is None+ with pytest.raises(StationError, match="rover_ride_required"):+ await service.submit("first", request(mode=TravelMode.ROVER))+ assert (await service.snapshot()).commands == ()+++async def test_deadline_bounds_station_queue_and_no_progress(runtime):+ service, clock, _ = runtime+ service.deadline_ms = 1000+ record = await service.submit("first", request())+ await tick(service, clock)+ failed = await service.store.get(record.command_id)+ assert failed.state is NavigationState.UNREACHABLE+ assert failed.reason == "navigation_deadline_exceeded"+++async def test_unready_logical_destination_waits_and_recovers(runtime):+ service, clock, _ = runtime+ record = await service.submit("first", request())+ await tick(service, clock, 2, unavailable_stations=["destination"])+ assert (await service.store.get(record.command_id)).position == (0, 0, 0)+ await tick(service, clock, 5)+ assert (await service.store.get(record.command_id)).state is NavigationState.ARRIVED+++async def test_restart_releases_old_leases_resumes_exact_position_and_preserves_replay(runtime):+ service, clock, authority = runtime+ record = await service.submit("agent", request())+ await tick(service, clock)+ moving = await service.store.get(record.command_id)+ # Close the store only: emulate process loss without a service cleanup transaction.+ await service.store.close()+ recovered = MarsNavigationService(+ MarsNavigationStore(service.store.path, clock_ms=clock), definition(), authorize=authority+ )+ clock.now += 50_000+ await recovered.start()+ try:+ assert (await recovered.snapshot()).leases == ()+ replay = await recovered.submit("agent", request())+ assert replay.command_id == record.command_id+ assert replay.position == moving.position+ await recovered.advance()+ assert (await recovered.store.get(record.command_id)).position == moving.position+ await tick(recovered, clock)+ assert (await recovered.store.get(record.command_id)).position[0] > moving.position[0]+ assert len(authority.calls) >= 3+ finally:+ await recovered.close()+ service._started = False+++async def test_only_one_process_can_own_navigation_database(runtime):+ service, clock, _ = runtime+ second = MarsNavigationStore(service.store.path, clock_ms=clock)+ with pytest.raises(StationError, match="navigation_owned_by_another_process"):+ await second.open()+++async def test_graph_content_change_refuses_teleport_or_silent_reinterpretation(runtime):+ service, clock, authority = runtime+ record = await service.submit("agent", request())+ await tick(service, clock)+ await service.close()+ changed = definition()+ changed["navigation"]["nodes"][1]["position"][0] = 5+ recovered = MarsNavigationService(service.store, changed, authorize=authority)+ await recovered.start()+ try:+ await recovered.advance()+ assert (+ await recovered.store.get(record.command_id)+ ).reason == "navigation_location_graph_changed"+ with pytest.raises(StationError, match="navigation_location_graph_changed"):+ await recovered.submit("agent", request("new"))+ finally:+ await recovered.close()+++async def test_checked_catchup_is_bounded_and_never_crosses_a_block(runtime):+ service, clock, _ = runtime+ record = await service.submit("agent", request())+ await tick(service, clock, interval=50_000, blocked_edges=["bc"])+ current = await service.store.get(record.command_id)+ assert current.state is NavigationState.TEMPORARILY_BLOCKED+ assert current.position == (0, 0, 0)+ await service.cancel("agent", record.command_id)+ long_graph = definition()+ long_graph["navigation"]["nodes"][1]["position"][0] = 400+ graph = NavigationGraph(long_graph)+ assert graph.path("a", "middle", TravelMode.ROVER) == ("ab",)+++async def test_narrow_route_is_exclusive_between_independent_destinations(runtime):+ service, clock, _ = runtime+ first = await service.submit("first", request(station="middle"))+ second = await service.submit("second", request())+ await tick(service, clock)+ waiting = await service.store.get(second.command_id)+ assert waiting.state is NavigationState.QUEUEING+ assert waiting.reason == "physical_route_occupied"+ assert waiting.position == (0, 0, 0)+ leases = (await service.snapshot()).leases+ assert sum(lease.resource_id == "edge:ab" for lease in leases) == 1+ assert (+ next(lease for lease in leases if lease.resource_id == "edge:ab").command_id+ == first.command_id+ )+ await tick(service, clock, 8)+ assert (await service.store.get(second.command_id)).state is NavigationState.QUEUEING+ assert (await service.store.get(second.command_id)).position == (0, 0, 0)+ await service.submit("first", request("departure", station="parking"))+ await tick(service, clock, 10)+ assert (await service.store.get(second.command_id)).state is NavigationState.ARRIVED++[email protected]("interruption", ["cancel", "deadline", "restart"])+async def test_mid_edge_body_precedes_older_waiter_after_interruption(runtime, interruption):+ service, clock, _ = runtime+ older = await service.submit("older", request())+ if interruption == "deadline":+ service.deadline_ms = 2000+ younger = await service.submit("younger", request(station="middle"))+ service.deadline_ms = 600_000+ await tick(service, clock, unavailable_stations=["destination"])+ before = await service.store.get(younger.command_id)+ assert before.position == (1.8, 0, 0)+ if interruption == "cancel":+ await service.cancel("younger", younger.command_id)+ elif interruption == "deadline":+ await tick(service, clock, unavailable_stations=["destination"])+ assert (await service.store.get(younger.command_id)).state is NavigationState.UNREACHABLE+ else:+ await service.close()+ await service.start()+ # Intent leases may expire or disappear; the body must still win over FIFO admission.+ await tick(service, clock, interval=30_000)+ older_after = await service.store.get(older.command_id)+ younger_after = await service.store.get(younger.command_id)+ assert older_after.position == (0, 0, 0)+ assert older_after.state is NavigationState.QUEUEING+ assert younger_after.position != older_after.position+ if interruption != "restart":+ assert younger_after.position == before.position+ assert any(+ body.resource_id == "edge:ab" and body.agent_id == "younger"+ for body in (await service.snapshot()).occupancies+ )+++async def test_queued_request_reauthorizes_before_first_physical_movement(runtime):+ service, clock, authority = runtime+ record = await service.submit("agent", request())+ authority.allowed = False+ await tick(service, clock)+ denied = await service.store.get(record.command_id)+ assert denied.state is NavigationState.CANCELED+ assert denied.reason == "navigation_not_authorized"+ assert denied.position == record.position+ assert denied.presence == "spawn_queue"+ assert len(authority.calls) == 2+ assert (await service.snapshot()).occupancies == ()++[email protected]("restart", [False, True])+async def test_revoked_moving_actor_stops_but_remains_a_physical_obstacle(runtime, restart):+ service, clock, authority = runtime+ record = await service.submit("agent", request())+ await tick(service, clock)+ before = await service.store.get(record.command_id)+ if restart:+ await service.close()+ await service.start()+ authority.allowed = False+ await tick(service, clock)+ denied = await service.store.get(record.command_id)+ assert denied.state is NavigationState.CANCELED+ assert denied.reason == "navigation_not_authorized"+ assert denied.position == before.position+ assert (await service.snapshot()).leases == ()+ occupancy = (await service.snapshot()).occupancies+ assert len(occupancy) == 1 and occupancy[0].resource_id == "edge:ab"+ authority.allowed = True+ next_request = await service.submit("agent", request("resume"))+ await tick(service, clock)+ assert (await service.store.get(next_request.command_id)).position[0] > denied.position[0]+++async def test_physical_body_survives_snapshot_history_window(runtime):+ service, clock, _ = runtime+ parked = await service.submit("parked", request(station="middle"))+ await tick(service, clock, 3)+ assert (await service.store.get(parked.command_id)).state is NavigationState.ARRIVED+ for index in range(70):+ await service.submit("other", request(str(index), station="origin"))+ await tick(service, clock)+ snapshot = await service.snapshot()+ assert parked.command_id in {row.command_id for row in snapshot.commands}+ assert any(+ body.agent_id == "parked" and body.resource_id == "node:b" for body in snapshot.occupancies+ )+ departure = await service.submit("other", request("depart"))+ await tick(service, clock)+ assert (await service.store.get(departure.command_id)).position == (0, 0, 0)+++async def test_spawn_queue_is_explicit_and_actor_capacity_never_discards_a_body(runtime):+ service, clock, _ = runtime+ service.store.actor_limit = 2+ first = await service.submit("first", request(station="origin"))+ await tick(service, clock)+ second = await service.submit("second", request())+ await tick(service, clock)+ waiting = await service.store.get(second.command_id)+ assert waiting.reason == "physical_spawn_occupied"+ assert waiting.presence == "spawn_queue"+ assert (await service.store.get(first.command_id)).presence == "placed"+ with pytest.raises(StationError, match="navigation_actor_limit_reached"):+ await service.submit("third", request())+ assert {body.agent_id for body in (await service.snapshot()).occupancies} == {"first"}+++async def test_canceled_waiter_cannot_claim_rover_and_retains_pose_for_pedestrian_retry(runtime):+ service, clock, _ = runtime+ await service.submit("first", request(station="middle"))+ waiter = await service.submit("waiter", request())+ await tick(service, clock)+ waiting = await service.store.get(waiter.command_id)+ assert waiting.presence == "spawn_queue"+ assert waiting.edge_id == "ab" and waiting.edge_progress == 0+ await service.cancel("waiter", waiter.command_id)+ with pytest.raises(StationError, match="rover_ride_required"):+ await service.submit("waiter", request("rover", station="middle", mode=TravelMode.ROVER))+ changed = await service.submit("waiter", request("retry", station="middle"))+ assert changed.mode is TravelMode.PEDESTRIAN+ assert changed.position == waiting.position+ assert changed.current_node == waiting.current_node+ assert changed.edge_id is None and changed.next_node is None+ assert changed.edge_progress == 0+++async def test_canceled_waiter_targeting_current_node_does_not_traverse_unentered_edge(runtime):+ service, clock, _ = runtime+ await service.submit("first", request(station="middle"))+ waiter = await service.submit("waiter", request())+ await tick(service, clock)+ waiting = await service.store.get(waiter.command_id)+ assert waiting.edge_id == "ab" and waiting.edge_progress == 0+ await service.cancel("waiter", waiter.command_id)+ at_origin = await service.submit("waiter", request("stay", station="origin"))+ await tick(service, clock)+ arrived = await service.store.get(at_origin.command_id)+ assert arrived.state is NavigationState.ARRIVED+ assert arrived.position == waiting.position == (0, 0, 0)+ assert arrived.edge_id is None and arrived.next_node is None+ assert not any(+ body.agent_id == "waiter" and body.resource_id == "edge:ab"+ for body in (await service.snapshot()).occupancies+ )diff --git a/tests/unit/society/test_mars_navigation_migration.py b/tests/unit/society/test_mars_navigation_migration.pynew file mode 100644index 0000000000..89c9e0db81--- /dev/null+++ b/tests/unit/society/test_mars_navigation_migration.py@@ -0,0 +1,164 @@+"""Persisted graph updates prove exact geometry before remapping a placed body."""++from __future__ import annotations++import copy++import pytest++from jarvis.society.mars.models import StationError+from jarvis.society.mars.navigation import NavigationGraph+from jarvis.society.mars.navigation_models import MoveCommand, NavigationState+from jarvis.society.mars.navigation_service import MarsNavigationService+from jarvis.society.mars.navigation_store import MarsNavigationStore+++def source():+ return {+ "world_id": "mars:ordinary",+ "layout_version": 1,+ "spawn": {"position": [0, 0, 0]},+ "stations": [+ {"id": "finish", "anchor": "end", "capacity": 1},+ {"id": "origin", "anchor": "start", "capacity": 1},+ ],+ "navigation": {+ "version": 1,+ "nodes": [+ {"id": "start", "position": [0, 0, 0]},+ {"id": "end", "position": [20, 0, 0]},+ ],+ "edges": [+ {+ "id": "road",+ "from": "start",+ "to": "end",+ "width": 7,+ "modes": ["pedestrian", "rover"],+ }+ ],+ },+ }+++def replacement(old):+ data = copy.deepcopy(old)+ data["navigation"]["nodes"].extend(+ [{"id": "split-a", "position": [6, 0, 0]}, {"id": "split-b", "position": [14, 0, 0]}]+ )+ data["navigation"]["edges"] = [+ {"id": edge, "from": start, "to": end, "width": 7, "modes": ["pedestrian", "rover"]}+ for edge, start, end in [+ ("lead", "start", "split-a"),+ ("ride", "split-a", "split-b"),+ ("tail", "split-b", "end"),+ ]+ ]+ data["navigation"]["graph_migrations"] = [+ {+ "source_signature": NavigationGraph(old).signature,+ "source_descriptor": {+ key: copy.deepcopy(old[key]) for key in ("navigation", "stations", "spawn")+ },+ "edge_splits": {"road": ["lead", "ride", "tail"]},+ }+ ]+ return data+++async def allow(*args):+ return True++[email protected]("reverse", [False, True])+async def test_subdivision_recovers_saved_forward_and_reverse_pose_without_teleport(+ tmp_path, reverse+):+ now = [100_000]+ old = source()+ if reverse:+ old["spawn"]["position"] = [20, 0, 0]+ path = tmp_path / "navigation.db"+ service = MarsNavigationService(+ MarsNavigationStore(path, clock_ms=lambda: now[0]), old, authorize=allow+ )+ await service.start()+ command = await service.submit(+ "real-agent", MoveCommand(request_id="move", station_id="origin" if reverse else "finish")+ )+ now[0] += 5000+ await service.advance()+ before = await service.store.get(command.command_id)+ assert 0 < before.edge_progress < 1+ await service.close()+ now[0] += 30000+ updated = MarsNavigationService(+ MarsNavigationStore(path, clock_ms=lambda: now[0]), replacement(old), authorize=allow+ )+ await updated.start()+ try:+ recovered = await updated.store.get(command.command_id)+ assert recovered.position == before.position+ assert recovered.edge_id == "ride"+ assert recovered.current_node == ("split-b" if reverse else "split-a")+ assert recovered.graph_signature == updated.graph.signature+ await updated.advance()+ assert (await updated.store.get(command.command_id)).position == before.position+ now[0] += 1000+ await updated.advance()+ after = await updated.store.get(command.command_id)+ assert after.position[0] == pytest.approx(before.position[0] + (-1.8 if reverse else 1.8))+ finally:+ await updated.close()++[email protected]("tamper", ["descriptor", "curve", "width", "station"])+async def test_unproven_geometry_changes_freeze_exact_physical_body(tmp_path, tamper):+ now = [100_000]+ old = source()+ path = tmp_path / "navigation.db"+ service = MarsNavigationService(+ MarsNavigationStore(path, clock_ms=lambda: now[0]), old, authorize=allow+ )+ await service.start()+ record = await service.submit("agent", MoveCommand(request_id="move", station_id="finish"))+ now[0] += 5000+ await service.advance()+ before = await service.store.get(record.command_id)+ await service.close()+ new = replacement(old)+ if tamper == "descriptor":+ new["navigation"]["graph_migrations"][0]["source_descriptor"]["navigation"]["edges"][0][+ "width"+ ] = 8+ elif tamper == "curve":+ new["navigation"]["nodes"][-1]["position"][2] = 1+ elif tamper == "width":+ new["navigation"]["edges"][1]["width"] = 8+ else:+ new["stations"][0]["anchor"] = "split-b"+ updated = MarsNavigationService(+ MarsNavigationStore(path, clock_ms=lambda: now[0]), new, authorize=allow+ )+ await updated.start()+ try:+ now[0] += 1000+ await updated.advance()+ after = await updated.store.get(record.command_id)+ assert after.position == before.position and after.graph_signature == before.graph_signature+ assert after.state is NavigationState.UNREACHABLE+ assert after.reason == "navigation_location_graph_changed"+ assert (await updated.snapshot()).occupancies[0].position == before.position+ # A new edge ID must not let a second body drive through the unmapped+ # placement just because its old resource name no longer exists.+ with pytest.raises(StationError, match="navigation_location_graph_changed"):+ await updated.submit(+ "other-agent", MoveCommand(request_id="new-move", station_id="finish")+ )+ now[0] += 5000+ await updated.advance()+ snapshot = await updated.snapshot()+ assert {command.agent_id for command in snapshot.commands} == {"agent"}+ assert snapshot.occupancies[0].position == before.position+ finally:+ await updated.close()diff --git a/tests/unit/society/test_mars_rover.py b/tests/unit/society/test_mars_rover.pynew file mode 100644index 0000000000..eb82694ee3--- /dev/null+++ b/tests/unit/society/test_mars_rover.py@@ -0,0 +1,349 @@+"""Real SQLite rover contracts: exclusive seats, authoritative motion and safe exits."""++from __future__ import annotations++import asyncio++import pytest++from jarvis.society.mars.models import StationError+from jarvis.society.mars.navigation_models import (+ MoveCommand,+ NavigationState,+ RideState,+ RoverActionCommand,+ RoverReserveCommand,+ RoverTravelCommand,+)+from jarvis.society.mars.navigation_service import MarsNavigationService+from jarvis.society.mars.navigation_store import MarsNavigationStore+++class Clock:+ now = 100_000++ def __call__(self):+ return self.now+++class Authority:+ allowed = True++ async def __call__(self, agent_id, destination, mode):+ return self.allowed+++def definition():+ positions = {+ "spawn": [-5, 0, 2.8],+ "a": [5, 0, 0],+ "b": [15, 0, 0],+ "a-board": [5, 0, 2.8],+ "b-board": [15, 0, 2.8],+ "a-exit": [5, 0, -2.8],+ "b-exit": [15, 0, -2.8],+ "a-alt": [5, 0, 3.4],+ "b-alt": [15, 0, 3.4],+ }+ edges = [{"id": "road", "from": "a", "to": "b", "width": 7, "modes": ["pedestrian", "rover"]}]+ for edge_id, start, end in [+ ("approach", "spawn", "a-board"),+ ("shoulder", "a-board", "b-board"),+ ("a-exit-path", "a-exit", "spawn"),+ ("b-exit-path", "b-exit", "spawn"),+ ("a-alt-path", "a-alt", "spawn"),+ ("b-alt-path", "b-alt", "spawn"),+ ]:+ edges.append(+ {"id": edge_id, "from": start, "to": end, "width": 2.4, "modes": ["pedestrian"]}+ )+ stations = [+ {"id": key, "anchor": key, "capacity": 1} for key in positions if key not in {"a", "b"}+ ]+ return {+ "world_id": "mars:ordinary",+ "layout_version": 1,+ "spawn": {"position": positions["spawn"]},+ "stations": stations,+ "navigation": {+ "version": 1,+ "nodes": [{"id": key, "position": value} for key, value in positions.items()],+ "edges": edges,+ "rover_docks": [+ {+ "id": dock,+ "node_id": dock,+ "boarding_station_id": dock + "-board",+ "exit_station_ids": [dock + "-exit", dock + "-alt"],+ "yaw": 1.5707963267948966,+ }+ for dock in ("a", "b")+ ],+ "rovers": [+ {+ "id": "rover",+ "home_dock_id": "a",+ "seat_capacity": 1,+ "width_m": 3.4,+ "length_m": 4.8,+ "height_m": 2.6,+ "speed_m_s": 4,+ }+ ],+ "collision": {+ "version": 1,+ "source_sha256": "0" * 64,+ "solid_boxes": [{"id": "far-solid", "min": [45, 0, 45], "max": [46, 10, 46]}],+ "support_surfaces": [+ {+ "id": "floor",+ "polygon": [[-50, -50], [50, -50], [50, 50], [-50, 50]],+ "plane": [0, 0, 0],+ }+ ],+ },+ },+ }+++async def runtime(tmp_path):+ clock, authority = Clock(), Authority()+ service = MarsNavigationService(+ MarsNavigationStore(tmp_path / "navigation.db", clock_ms=clock),+ definition(),+ authorize=authority,+ authorize_rover=authority,+ )+ await service.start()+ try:+ yield service, clock, authority+ finally:+ await service.close()+++async def tick(service, clock, count=1, **kwargs):+ for _ in range(count):+ clock.now += 1000+ await service.advance(**kwargs)+++async def ready(service, clock, agent="agent", request="reserve"):+ ride = await service.reserve_ride(+ agent, RoverReserveCommand(request_id=request, vehicle_id="rover")+ )+ await tick(service, clock, 7)+ ride = await service.store.get_ride(ride.ride_id)+ assert ride.state is RideState.READY_TO_BOARD+ return ride+++async def boarded(service, clock):+ ride = await ready(service, clock)+ return await service.board_ride("agent", ride.ride_id, RoverActionCommand(request_id="board"))+++async def test_exclusive_reservation_is_atomic_and_idempotent(runtime):+ service, _, _ = runtime+ command = RoverReserveCommand(request_id="reserve", vehicle_id="rover")+ results = await asyncio.gather(*(service.reserve_ride("agent", command) for _ in range(8)))+ assert len({ride.ride_id for ride in results}) == 1+ with pytest.raises(StationError, match="rover_seat_reserved"):+ await service.reserve_ride("other", command)+ with pytest.raises(StationError, match="idempotency_payload_mismatch"):+ await service.board_ride(+ "agent", results[0].ride_id, RoverActionCommand(request_id="reserve")+ )+ snapshot = await service.snapshot()+ assert len(snapshot.rides) == len(snapshot.commands) == 1+ assert snapshot.commands[0].agent_id == "agent"+ assert snapshot.vehicles[0].vehicle_id == "rover"+++async def test_pedestrian_authority_does_not_implicitly_authorize_a_ride(runtime):+ service, _, _ = runtime+ service.authorize_rover = None+ with pytest.raises(StationError, match="navigation_not_authorized"):+ await service.reserve_ride(+ "agent", RoverReserveCommand(request_id="reserve", vehicle_id="rover")+ )+ assert (await service.snapshot()).rides == ()+++async def test_explicit_boarding_and_complete_route_do_not_duplicate_rider_body(runtime):+ service, clock, _ = runtime+ ride = await service.reserve_ride(+ "agent", RoverReserveCommand(request_id="reserve", vehicle_id="rover")+ )+ with pytest.raises(StationError, match="rover_rider_not_ready"):+ await service.board_ride(+ "agent", ride.ride_id, RoverActionCommand(request_id="board-too-soon")+ )+ await tick(service, clock, 7)+ assert not (await service.store.get_ride(ride.ride_id)).attached+ ride = await service.board_ride("agent", ride.ride_id, RoverActionCommand(request_id="board"))+ assert ride.attached+ assert all(body.owner.kind == "vehicle" for body in (await service.snapshot()).occupancies)+ await service.travel_ride(+ "agent", ride.ride_id, RoverTravelCommand(request_id="travel", destination_dock_id="b")+ )+ await tick(service, clock)+ vehicle = (await service.snapshot()).vehicles[0]+ assert vehicle.position == (9, 0, 0)+ await tick(service, clock, 3)+ assert (await service.store.get_ride(ride.ride_id)).state is RideState.ARRIVED+ ride = await service.exit_ride("agent", ride.ride_id, RoverActionCommand(request_id="exit"))+ assert ride.state is RideState.COMPLETED and not ride.attached+ snapshot = await service.snapshot()+ assert {body.owner.kind for body in snapshot.occupancies} == {"agent", "vehicle"}+ assert (await service.store.get(ride.approach_command_id)).position == (15, 0, -2.8)+ assert snapshot.vehicles[0].position == (15, 0, 0)+++async def test_revoked_boarding_cannot_acquire_seat_and_tick_releases_reservation(runtime):+ service, clock, authority = runtime+ ride = await ready(service, clock)+ authority.allowed = False+ with pytest.raises(StationError, match="navigation_not_authorized"):+ await service.board_ride("agent", ride.ride_id, RoverActionCommand(request_id="board"))+ await tick(service, clock)+ assert (await service.store.get_ride(ride.ride_id)).state is RideState.CANCELED+ assert (await service.snapshot()).vehicles[0].ride_id is None+++async def test_cancel_midroad_retains_seat_and_pose_until_safe_dock_exit(runtime):+ service, clock, _ = runtime+ ride = await boarded(service, clock)+ await service.travel_ride(+ "agent", ride.ride_id, RoverTravelCommand(request_id="travel", destination_dock_id="b")+ )+ await tick(service, clock)+ before = (await service.snapshot()).vehicles[0]+ cancel = RoverActionCommand(request_id="cancel")+ stopped = await service.cancel_ride("agent", ride.ride_id, cancel)+ assert await service.cancel_ride("agent", ride.ride_id, cancel) == stopped+ await tick(service, clock, 10)+ after = (await service.snapshot()).vehicles[0]+ assert after.position == before.position and after.edge_progress == before.edge_progress+ blocked = await service.exit_ride(+ "agent", ride.ride_id, RoverActionCommand(request_id="unsafe-exit")+ )+ assert blocked.state is RideState.EXIT_BLOCKED and blocked.attached+ with pytest.raises(StationError, match="rover_seat_reserved"):+ await service.reserve_ride(+ "other", RoverReserveCommand(request_id="reserve", vehicle_id="rover")+ )+ await service.travel_ride(+ "agent", ride.ride_id, RoverTravelCommand(request_id="resume", destination_dock_id="b")+ )+ assert (await service.snapshot()).vehicles[0].position == before.position+ await tick(service, clock, 3)+ exited = await service.exit_ride(+ "agent", ride.ride_id, RoverActionCommand(request_id="safe-exit")+ )+ assert exited.state is RideState.COMPLETED+++async def test_blocked_primary_exit_uses_alternate_and_both_blocked_retain_seat(runtime):+ service, clock, _ = runtime+ first = await service.submit("blocker", MoveCommand(request_id="block", station_id="a-exit"))+ await tick(service, clock, 8)+ assert (await service.store.get(first.command_id)).state is NavigationState.ARRIVED+ await service.submit("other", MoveCommand(request_id="block", station_id="a-alt"))+ await tick(service, clock, 8)+ ride = await boarded(service, clock)+ blocked = await service.exit_ride(+ "agent", ride.ride_id, RoverActionCommand(request_id="exit-both-blocked")+ )+ assert blocked.state is RideState.EXIT_BLOCKED and blocked.attached+ await service.submit("other", MoveCommand(request_id="leave", station_id="b-alt"))+ await tick(service, clock, 25)+ exited = await service.exit_ride(+ "agent", ride.ride_id, RoverActionCommand(request_id="exit-alternate")+ )+ assert exited.state is RideState.COMPLETED+ assert (await service.store.get(ride.approach_command_id)).current_node == "a-alt"+++async def test_obstruction_retry_budget_stops_without_releasing_rider(runtime):+ service, clock, _ = runtime+ ride = await boarded(service, clock)+ await service.travel_ride(+ "agent", ride.ride_id, RoverTravelCommand(request_id="travel", destination_dock_id="b")+ )+ await tick(service, clock)+ pose = (await service.snapshot()).vehicles[0].position+ await tick(service, clock, 15, blocked_edges=["road"])+ ride = await service.store.get_ride(ride.ride_id)+ assert ride.state is RideState.STOPPED and ride.attached+ assert (await service.snapshot()).vehicles[0].position == pose+++async def test_restart_pauses_distance_but_wall_deadline_retains_attached_seat(runtime):+ service, clock, _ = runtime+ ride = await boarded(service, clock)+ await service.travel_ride(+ "agent", ride.ride_id, RoverTravelCommand(request_id="travel", destination_dock_id="b")+ )+ await tick(service, clock)+ before = (await service.snapshot()).vehicles[0]+ await service.close()+ clock.now += 60_000+ await service.start()+ await service.advance()+ after = (await service.snapshot()).vehicles[0]+ assert after.position == before.position+ clock.now += 700_000+ await service.advance()+ ride = await service.store.get_ride(ride.ride_id)+ assert ride.state is RideState.STOPPED and ride.attached+ assert (await service.snapshot()).vehicles[0].position == before.position+++async def test_failed_mutation_rolls_back_seat_body_and_receipt(runtime):+ service, _, _ = runtime+ before = await service.snapshot()++ def fail(world, now):+ world.vehicles.clear()+ world.leases.clear()+ raise RuntimeError("fixture rollback")++ with pytest.raises(RuntimeError, match="fixture rollback"):+ await service.store.mutate_world(fail)+ assert await service.snapshot() == before+++async def test_unsafe_collision_data_prevents_vehicle_initialization(tmp_path):+ data = definition()+ data["navigation"]["collision"]["solid_boxes"].append(+ {"id": "wall", "min": [3, 0, -1], "max": [7, 3, 1]}+ )+ with pytest.raises(ValueError, match="unsafe rover dock"):+ MarsNavigationService(+ MarsNavigationStore(tmp_path / "navigation.db"), data, authorize=Authority()+ )+ assert not (tmp_path / "navigation.db").exists()+++async def test_static_road_obstruction_refuses_travel_before_displacement(runtime):+ service, clock, _ = runtime+ ride = await boarded(service, clock)+ service.graph.geometry.boxes.append(((9, 0, -1), (10, 3, 1)))+ before = (await service.snapshot()).vehicles[0]+ with pytest.raises(StationError, match="rover_route_clearance_failed"):+ await service.travel_ride(+ "agent", ride.ride_id, RoverTravelCommand(request_id="travel", destination_dock_id="b")+ )+ assert (await service.snapshot()).vehicles[0] == before+++def test_public_pedestrian_request_still_rejects_rover():+ from pydantic import ValidationError++ from jarvis.society.mars.navigation_models import PedestrianMoveCommand++ with pytest.raises(ValidationError):+ PedestrianMoveCommand.model_validate_json(+ '{"request_id":"x","station_id":"a","mode":"rover"}'+ )diff --git a/tests/unit/society/test_mars_service.py b/tests/unit/society/test_mars_service.pynew file mode 100644index 0000000000..aaed831dd7--- /dev/null+++ b/tests/unit/society/test_mars_service.py@@ -0,0 +1,282 @@+"""Test-only executor fixtures; these never call a provider or claim live evidence."""++from __future__ import annotations++import asyncio++import pytest++from jarvis.society.mars.models import CommandState, DispatchRejected, StationCommand, StationError+from jarvis.society.mars.service import MarsStationService+from jarvis.society.mars.store import MarsStore+++class RecordingExecutor:+ """Test-only trusted-boundary stand-in with inspectable acceptance and cancellation."""++ def __init__(self):+ self.dispatches = []+ self.inspections = []+ self.cancellations = []+ self.denied = set()+ self.receipts = {}+ self.dispatch_error = None+ self.cancel_error = None+ self.hang_dispatch = False+ self.hang_cancel = False+ self.invalid_receipt = False+ self.cancel_unavailable = False++ async def authorize(self, *, agent_id, capability_id):+ assert capability_id == "communication-draft"+ if agent_id in self.denied:+ raise DispatchRejected("permission_denied")++ async def dispatch(self, *, agent_id, command_id, trace_id, draft):+ self.dispatches.append((agent_id, command_id, trace_id, draft))+ self.receipts[command_id] = {"state": "active", "task_ref": f"turn:{command_id}"}+ if self.hang_dispatch:+ await asyncio.Event().wait()+ if self.dispatch_error:+ raise self.dispatch_error+ if self.invalid_receipt:+ return {"state": "completed"}+ return self.receipts[command_id]++ async def inspect(self, *, agent_id, command_id, trace_id, task_ref):+ self.inspections.append((agent_id, command_id, trace_id, task_ref))+ return self.receipts.get(command_id, {"state": "unknown"})++ async def cancel(self, *, agent_id, command_id, trace_id, task_ref):+ if self.cancel_unavailable:+ return {"state": "unknown", "cancel_attempt": "not_attempted"}+ task_ref = task_ref or self.receipts.get(command_id, {}).get("task_ref")+ self.cancellations.append((agent_id, command_id, trace_id, task_ref))+ if self.hang_cancel:+ await asyncio.Event().wait()+ if self.cancel_error:+ raise self.cancel_error+ self.receipts[command_id] = {"state": "canceled", "task_ref": task_ref}+ return self.receipts[command_id]+++async def service(tmp_path):+ executor = RecordingExecutor()+ service = MarsStationService(+ MarsStore(tmp_path / "mars.db"),+ executor,+ operation_timeout_s=0.05,+ cancellation_timeout_s=0.05,+ )+ await service.start()+ try:+ yield service, executor+ finally:+ await service.close()+++async def settle(service):+ """Drain just the service's owned one-shot work, with no renderer or connection."""+ if service._background:+ await asyncio.gather(*tuple(service._background))+++def request(ident="one"):+ return StationCommand(request_id=ident, draft="Draft a short communications handover.")+++async def test_submit_uses_trusted_agent_and_accepts_raw_string_receipt(service):+ gateway, executor = service+ queued = await gateway.submit("operator", request())+ await settle(gateway)+ active = await gateway.store.get(queued.command_id)+ assert active.state is CommandState.ACTIVE+ assert active.task_ref == f"turn:{queued.command_id}"+ assert executor.dispatches == [+ ("operator", queued.command_id, queued.trace_id, request().draft)+ ]+ assert active.result_ref is None+++async def test_authorization_denial_persists_no_command(service):+ gateway, executor = service+ executor.denied.add("operator")+ with pytest.raises(DispatchRejected, match="permission_denied"):+ await gateway.submit("operator", request())+ assert (await gateway.snapshot()).seq == 0+ assert not executor.dispatches+++async def test_credentials_are_rejected_before_start_or_authorization(tmp_path, caplog):+ executor = RecordingExecutor()+ path = tmp_path / "must-not-open.db"+ gateway = MarsStationService(MarsStore(path), executor)+ credential = "sk-proj-" + "A1" * 20+ command = StationCommand(request_id="secret-rejected", draft="Use this key " + credential)+ with pytest.raises(StationError, match="credential_input_use_api_key_settings"):+ await gateway.submit("operator", command)+ assert not path.exists()+ assert not executor.dispatches and not executor.inspections+ assert credential not in caplog.text+++async def test_durable_completion_reopens_without_running_again(service):+ gateway, executor = service+ submitted = await gateway.submit("operator", request())+ await settle(gateway)+ executor.receipts[submitted.command_id] = {+ "state": "completed",+ "task_ref": f"turn:{submitted.command_id}",+ "result_ref": "result:actual",+ }+ await gateway.reconcile()+ completed = await gateway.store.get(submitted.command_id)+ assert completed.state is CommandState.COMPLETED+ assert completed.result_ref == "result:actual"+ await gateway.close()+ await gateway.start()+ replay = await gateway.submit("operator", request())+ await settle(gateway)+ assert replay.command_id == completed.command_id+ assert replay.result_ref == completed.result_ref+ assert len(executor.dispatches) == 1+++async def test_dispatch_uncertainty_never_repeats_and_reconciles_reference(service):+ gateway, executor = service+ executor.dispatch_error = TimeoutError("private upstream response must not enter event")+ submitted = await gateway.submit("operator", request())+ await settle(gateway)+ unknown = await gateway.store.get(submitted.command_id)+ assert unknown.state is CommandState.UNKNOWN+ assert (await gateway.snapshot()).lease.command_id == submitted.command_id+ executor.receipts[submitted.command_id] = {+ "state": "completed",+ "task_ref": "turn:accepted",+ "result_ref": "result:accepted",+ }+ await gateway.submit("operator", request())+ await settle(gateway)+ assert len(executor.dispatches) == 1+ assert (await gateway.store.get(submitted.command_id)).state is CommandState.COMPLETED+ assert "private upstream response" not in (await gateway.events(0)).model_dump_json()+++async def test_dispatch_timeout_and_invalid_success_remain_unknown(service):+ gateway, executor = service+ executor.hang_dispatch = True+ submitted = await gateway.submit("operator", request())+ await settle(gateway)+ assert (await gateway.store.get(submitted.command_id)).state is CommandState.UNKNOWN+ assert len(executor.dispatches) == 1+ executor.hang_dispatch = False+ executor.receipts[submitted.command_id] = {"state": "failed"}+ await gateway.reconcile()+ executor.invalid_receipt = True+ other = await gateway.submit("operator", request("other"))+ await settle(gateway)+ assert (await gateway.store.get(other.command_id)).state is CommandState.UNKNOWN+++async def test_known_preaccept_refusal_fails_without_claiming_success(service):+ gateway, executor = service+ executor.dispatch_error = DispatchRejected("budget_exhausted")+ submitted = await gateway.submit("operator", request())+ await settle(gateway)+ record = await gateway.store.get(submitted.command_id)+ assert record.state is CommandState.FAILED and record.reason == "budget_exhausted"+ assert (await gateway.snapshot()).lease is None+++async def test_revoked_queued_agent_never_dispatches(service):+ gateway, executor = service+ first = await gateway.submit("one", request("one"))+ await settle(gateway)+ second = await gateway.submit("two", request("two"))+ await settle(gateway)+ executor.denied.add("two")+ executor.receipts[first.command_id] = {"state": "failed"}+ await gateway.reconcile()+ await gateway.reconcile()+ assert len(executor.dispatches) == 1+ rejected = await gateway.store.get(second.command_id)+ assert rejected.state is CommandState.FAILED and rejected.reason == "permission_denied"+++async def test_owned_cancel_remains_available_after_grant_revocation(service):+ gateway, executor = service+ first = await gateway.submit("operator", request())+ await settle(gateway)+ executor.denied.add("operator")+ with pytest.raises(StationError, match="command_not_found"):+ await gateway.cancel("other-agent", first.command_id)+ await gateway.cancel("operator", first.command_id)+ await settle(gateway)+ assert len(executor.cancellations) == 1+ assert executor.cancellations[0][-1] == f"turn:{first.command_id}"+ assert (await gateway.store.get(first.command_id)).state is CommandState.CANCELED+ await gateway.cancel("operator", first.command_id)+ await settle(gateway)+ assert len(executor.cancellations) == 1+++async def test_unknown_cancellation_is_not_reissued_on_tick_or_restart(service):+ gateway, executor = service+ first = await gateway.submit("operator", request())+ await settle(gateway)+ executor.cancel_error = TimeoutError("lost cancellation response")+ await gateway.cancel("operator", first.command_id)+ await settle(gateway)+ assert (await gateway.store.get(first.command_id)).state is CommandState.UNKNOWN+ await gateway.reconcile()+ await gateway.close()+ await gateway.start()+ await gateway.reconcile()+ assert len(executor.cancellations) == 1+ assert len(executor.dispatches) == 1+ assert (await gateway.store.get(first.command_id)).cancel_requested+++async def test_not_attempted_cancellation_retries_after_prerequisite_recovers(service):+ gateway, executor = service+ # Simulate acceptance whose task reference was lost before the dispatch receipt.+ executor.dispatch_error = TimeoutError("lost acceptance response")+ first = await gateway.submit("operator", request())+ await settle(gateway)+ assert (await gateway.store.get(first.command_id)).task_ref is None+ executor.cancel_unavailable = True+ await gateway.cancel("operator", first.command_id)+ await settle(gateway)+ pending = await gateway.store.get(first.command_id)+ assert pending.cancel_requested and not pending.cancel_dispatched+ assert not executor.cancellations+ await gateway.close()+ await gateway.start()+ executor.cancel_unavailable = False+ # Reconcile discovers the durable task reference and the pending stop is attempted once.+ executor.receipts[first.command_id] = {"state": "active", "task_ref": "turn:recovered"}+ await gateway.reconcile()+ assert len(executor.cancellations) == 1+ assert len(executor.dispatches) == 1+ assert executor.cancellations[0][-1] == "turn:recovered"+ assert (await gateway.store.get(first.command_id)).state is CommandState.CANCELED+++async def test_two_clients_submit_one_request_and_close_without_stopping_work(service):+ gateway, executor = service+ clients = await asyncio.gather(+ gateway.submit("operator", request()), gateway.submit("operator", request())+ )+ await settle(gateway)+ assert clients[0].command_id == clients[1].command_id+ # No client or scene objects exist. Backend reconciliation observes actual executor evidence.+ executor.receipts[clients[0].command_id] = {+ "state": "completed",+ "task_ref": f"turn:{clients[0].command_id}",+ "result_ref": "result:headless",+ }+ await gateway.reconcile()+ snapshot = await gateway.snapshot()+ assert snapshot.commands[0].state is CommandState.COMPLETED+ assert len(executor.dispatches) == 1diff --git a/tests/unit/society/test_mars_store.py b/tests/unit/society/test_mars_store.pynew file mode 100644index 0000000000..e78eab2348--- /dev/null+++ b/tests/unit/society/test_mars_store.py@@ -0,0 +1,319 @@+"""Real isolated SQLite fixtures: capacity, fencing, rollback and cursor correctness."""++from __future__ import annotations++import asyncio+import threading++import aiosqlite+import pytest+from pydantic import ValidationError++from jarvis.society.mars.models import (+ CommandState,+ ExecutionReceipt,+ StationCommand,+ StationError,+)+from jarvis.society.mars.navigation_store import MarsNavigationStore+from jarvis.society.mars.store import MarsStore+++async def store(tmp_path):+ value = MarsStore(tmp_path / "mars.db")+ await value.open()+ try:+ yield value+ finally:+ await value.close()++[email protected]("kind", ["station", "navigation"])[email protected]("cancel_at", ["begin", "body"])+async def test_cancellation_joins_rollback_before_unlock_and_connection_reuse(+ tmp_path, kind, cancel_at+):+ """Gate real SQLite worker statements, including cancellation during cleanup."""+ value = (MarsStore if kind == "station" else MarsNavigationStore)(tmp_path / "cancel.db")+ await value.open()+ transaction = value._transaction if kind == "station" else value.transaction+ connection = value._conn+ await connection.execute("CREATE TABLE cancellation_probe(value INTEGER)")+ loop = asyncio.get_running_loop()+ begin_seen, rollback_seen, body_seen = (asyncio.Event() for _ in range(3))+ begin_release, rollback_release = threading.Event(), threading.Event()+ callback_timeouts = []+ first_begin = True++ def trace(statement):+ nonlocal first_begin+ if statement == "BEGIN IMMEDIATE" and first_begin:+ first_begin = False+ loop.call_soon_threadsafe(begin_seen.set)+ if cancel_at == "begin" and not begin_release.wait(timeout=10):+ callback_timeouts.append("begin")+ if statement == "ROLLBACK":+ loop.call_soon_threadsafe(rollback_seen.set)+ if not rollback_release.wait(timeout=10):+ callback_timeouts.append("rollback")++ await connection.set_trace_callback(trace)++ async def write():+ async with transaction() as conn:+ await conn.execute("INSERT INTO cancellation_probe VALUES(1)")+ body_seen.set()+ await asyncio.Event().wait()++ async def successor():+ async with transaction() as conn:+ async with conn.execute("SELECT COUNT(*) FROM cancellation_probe") as cursor:+ assert (await cursor.fetchone())[0] == 0+ await conn.execute("INSERT INTO cancellation_probe VALUES(2)")++ writer = asyncio.create_task(write())+ next_writer = None+ try:+ await asyncio.wait_for((begin_seen if cancel_at == "begin" else body_seen).wait(), 2)+ writer.cancel()+ await asyncio.sleep(0)+ if cancel_at == "begin":+ # BEGIN is accepted by the worker but still blocked before execution.+ assert value._lock.locked() and not writer.done()+ assert not body_seen.is_set()+ begin_release.set()+ await asyncio.wait_for(rollback_seen.wait(), 2)+ writer.cancel() # A stop deadline may cancel an owner already rolling back.+ await asyncio.sleep(0)+ assert value._lock.locked() and not writer.done()+ next_writer = asyncio.create_task(successor())+ await asyncio.sleep(0)+ assert not next_writer.done()+ rollback_release.set()+ with pytest.raises(asyncio.CancelledError):+ await asyncio.wait_for(writer, 2)+ await asyncio.wait_for(next_writer, 2)+ assert not connection.in_transaction+ async with connection.execute("SELECT value FROM cancellation_probe") as cursor:+ assert [row[0] for row in await cursor.fetchall()] == [2]+ assert callback_timeouts == []+ finally:+ begin_release.set()+ rollback_release.set()+ writer.cancel()+ if next_writer is not None:+ next_writer.cancel()+ await asyncio.gather(+ writer, *([next_writer] if next_writer else []), return_exceptions=True+ )+ await connection.set_trace_callback(None)+ await value.close()+++def request(ident="request-1", text="Draft a short shift handover."):+ return StationCommand(request_id=ident, draft=text)+++async def test_concurrent_duplicate_submit_has_one_identity_and_event(store):+ records = await asyncio.gather(*(store.submit("operator", request()) for _ in range(12)))+ assert len({row.command_id for row in records}) == 1+ assert (await store.snapshot()).seq == 1+ with pytest.raises(StationError, match="idempotency_payload_mismatch"):+ await store.submit("operator", request(text="Different content."))+ other = await store.submit("second-agent", request())+ assert other.command_id != records[0].command_id+++async def test_exclusive_station_fifo_and_terminal_release(store):+ first = await store.submit("one", request("first"))+ second = await store.submit("two", request("second"))+ claims = await asyncio.gather(store.claim_next(), store.claim_next())+ owned = [record for record in claims if record is not None]+ assert len(owned) == 1 and owned[0].command_id == first.command_id+ assert (await store.get(second.command_id)).state is CommandState.QUEUED+ completed = await store.apply(+ first.command_id,+ owned[0].fence,+ ExecutionReceipt(+ state=CommandState.COMPLETED, task_ref="turn:one", result_ref="result:one"+ ),+ )+ assert completed.state is CommandState.COMPLETED+ assert (await store.snapshot()).lease is None+ next_claim = await store.claim_next()+ assert next_claim.command_id == second.command_id+ assert next_claim.fence > owned[0].fence+ with pytest.raises(StationError, match="stale_station_lease"):+ await store.apply(+ second.command_id,+ owned[0].fence,+ ExecutionReceipt(state=CommandState.FAILED),+ )+++async def test_restart_fences_previous_owner_without_releasing_unknown_work(tmp_path):+ path = tmp_path / "restart.db"+ first = MarsStore(path)+ await first.open()+ queued = await first.submit("one", request())+ old = await first.claim_next()+ await first.close()+ second = MarsStore(path)+ await second.open()+ try:+ current = await second.current()+ assert current.command_id == queued.command_id+ assert current.state is CommandState.INTERRUPTED+ assert current.fence > old.fence+ assert await second.claim_next() is None+ with pytest.raises(StationError, match="stale_station_lease"):+ await second.apply(+ old.command_id, old.fence, ExecutionReceipt(state=CommandState.FAILED)+ )+ finally:+ await second.close()+++async def test_expired_lease_requires_reconciliation_and_rejects_late_result(tmp_path):+ clock = [1000]+ store = MarsStore(tmp_path / "expiry.db", clock_ms=lambda: clock[0], lease_ms=100)+ await store.open()+ try:+ await store.submit("operator", request())+ old = await store.claim_next()+ clock[0] = 1101+ with pytest.raises(StationError, match="stale_station_lease"):+ await store.apply(+ old.command_id, old.fence, ExecutionReceipt(state=CommandState.FAILED)+ )+ current = await store.current()+ assert current.fence > old.fence+ assert current.state is CommandState.INTERRUPTED+ assert current.reason == "lease_expired"+ assert await store.claim_next() is None+ finally:+ await store.close()+++async def test_second_store_cannot_take_live_owner_lock(tmp_path):+ first = MarsStore(tmp_path / "owner.db")+ second = MarsStore(tmp_path / "owner.db")+ await first.open()+ try:+ with pytest.raises(StationError, match="world_owned_by_another_process"):+ await second.open()+ finally:+ await first.close()+ await second.close()+ await second.open()+ await second.close()+++async def test_event_failure_rolls_back_command_without_false_acknowledgement(store):+ async with store._transaction() as conn:+ await conn.execute(+ "CREATE TRIGGER reject_events BEFORE INSERT ON mars_events "+ "BEGIN SELECT RAISE(ABORT, 'test storage failure'); END"+ )+ with pytest.raises(aiosqlite.IntegrityError, match="test storage failure"):+ await store.submit("operator", request())+ assert (await store.snapshot()).commands == ()+ async with store._transaction() as conn:+ await conn.execute("DROP TRIGGER reject_events")+ result = await store.submit("operator", request())+ assert result.state is CommandState.QUEUED+++async def test_snapshot_boundary_and_limited_delivered_cursor(store):+ first = await store.submit("operator", request())+ snapshot = await store.snapshot()+ assert snapshot.seq == 1+ await store.claim_next()+ await store.request_cancel("operator", first.command_id)+ batch = await store.events(snapshot.seq, limit=1)+ assert batch.next_cursor == 2 and batch.latest_seq == 3 and batch.has_more+ final = await store.events(batch.next_cursor, limit=1)+ assert final.next_cursor == 3 and not final.has_more+ assert [event.seq for event in batch.events + final.events] == [2, 3]+ # Retrying a page delivers identical immutable records for deterministic client dedupe.+ assert await store.events(snapshot.seq, limit=1) == batch+++async def test_retention_gap_and_future_cursor_require_snapshot(tmp_path):+ store = MarsStore(tmp_path / "retained.db", retain_events=2)+ await store.open()+ try:+ command = await store.submit("operator", request())+ await store.claim_next()+ await store.request_cancel("operator", command.command_id)+ gap = await store.events(0)+ assert gap.resync_required and not gap.events and not gap.has_more+ assert (await store.events(999)).resync_required+ snapshot = await store.snapshot()+ assert not (await store.events(snapshot.seq)).resync_required+ finally:+ await store.close()+++async def test_cancel_queued_does_not_consume_or_release_another_lease(store):+ first = await store.submit("one", request("first"))+ second = await store.submit("two", request("second"))+ await store.claim_next()+ with pytest.raises(StationError, match="command_not_found"):+ await store.request_cancel("one", second.command_id)+ canceled = await store.request_cancel("two", second.command_id)+ assert canceled.state is CommandState.CANCELED+ assert (await store.snapshot()).lease.command_id == first.command_id+++async def test_queue_cap_preserves_idempotent_retrieval(tmp_path):+ store = MarsStore(tmp_path / "bounded.db", queue_limit=1)+ await store.open()+ try:+ first = await store.submit("one", request())+ assert (await store.submit("one", request())).command_id == first.command_id+ with pytest.raises(StationError, match="station_queue_full"):+ await store.submit("two", request())+ finally:+ await store.close()+++async def test_private_draft_never_enters_snapshot_or_event_projection(store):+ private = "Only this private draft contains SECRET-CONTENT-SENTINEL."+ await store.submit("operator", request(text=private))+ assert "SECRET-CONTENT-SENTINEL" not in (await store.snapshot()).model_dump_json()+ assert "SECRET-CONTENT-SENTINEL" not in (await store.events(0)).model_dump_json()+++async def test_credential_shaped_draft_is_rejected_before_store_write(store, caplog):+ # Deliberately synthetic credential shape, never a usable key.+ credential = "sk-proj-" + "A1" * 20+ with pytest.raises(StationError, match="credential_input_use_api_key_settings") as exc:+ await store.submit("operator", request(text="Use this key " + credential))+ assert exc.value.status_code == 422+ assert credential not in str(exc.value)+ assert credential not in caplog.text+ snapshot = await store.snapshot()+ assert snapshot.seq == 0 and snapshot.commands == ()+++ "change",+ [+ {"world_id": "mars:swarm:other"},+ {"station_id": "not-a-station"},+ {"capability_id": "send-email"},+ {"schema_version": 2},+ {"layout_version": True},+ {"agent_id": "forged"},+ {"transform": [0, 0, 0]},+ {"draft": " "},+ {"draft": "x" * 4001},+ {"draft": "null\x00text"},+ {"request_id": "../escape"},+ ],+)+def test_command_rejects_unsupported_scope_versions_and_client_identity(change):+ with pytest.raises(ValidationError):+ StationCommand.model_validate({"request_id": "request", "draft": "A draft", **change})diff --git a/tests/unit/society/test_page_cursor.py b/tests/unit/society/test_page_cursor.pynew file mode 100644index 0000000000..818e360020--- /dev/null+++ b/tests/unit/society/test_page_cursor.py@@ -0,0 +1,49 @@+"""The real Chrome window gets the agent arrow, and can hide it again."""++from jarvis.society.browser.page_cursor import ARM_SOURCE, CURSOR_SCRIPT, arm_cursor, install_cursor+++class Frame:+ def __init__(self) -> None:+ self.calls: list[tuple[str, object]] = []++ async def evaluate(self, source: str, arg: object = None) -> None:+ self.calls.append((source, arg))+++class Page:+ def __init__(self) -> None:+ self.frame = Frame()+ self.frames = [self.frame]+ self.closed = False++ def is_closed(self) -> bool:+ return self.closed+++class Context:+ def __init__(self) -> None:+ self.page = Page()+ self.pages = [self.page]+ self.scripts: list[str] = []++ async def add_init_script(self, source: str) -> None:+ self.scripts.append(source)+++async def test_cursor_is_prepared_for_later_pages_and_can_be_shown() -> None:+ context = Context()+ await install_cursor(context)+ await arm_cursor(context, True)+ assert context.scripts == [CURSOR_SCRIPT]+ assert context.page.frame.calls[0][0] == CURSOR_SCRIPT+ assert context.page.frame.calls[1] == (ARM_SOURCE, True)+ assert "dataset.jarvisCursor" in CURSOR_SCRIPT+ assert "mousemove" in CURSOR_SCRIPT+++async def test_a_closed_page_is_skipped_and_hiding_reaches_open_frames() -> None:+ context = Context()+ context.page.closed = True+ await arm_cursor(context, False)+ assert context.page.frame.calls == []diff --git a/tests/unit/society/test_routines.py b/tests/unit/society/test_routines.pyindex d55c6196f5..530b6210a2 100644--- a/tests/unit/society/test_routines.py+++ b/tests/unit/society/test_routines.py@@ -14,6 +14,8 @@ from jarvis.society.routines import (create_routine,is_agent_routine,list_routines,+ manage_routine,+ routine_seat,)from jarvis.society.store import SocietyStore@@ -144,3 +146,109 @@ def test_the_agent_id_is_read_off_the_tags():assert agent_id_from_tags(("society", "agent:")) is Noneassert agent_id_from_tags(()) is Noneassert agent_id_from_tags(("automation",)) is None+++async def test_spec_pins_the_owner_seat_by_default(agent):+ spec = build_task_spec(agent, title="t", prompt="p", schedule={"kind": "every"})+ assert routine_seat(spec) == {+ "provider": agent.provider,+ "model": agent.model,+ "effort": agent.effort,+ "account_id": agent.account_id,+ }+++async def test_spec_accepts_an_explicit_seat(agent):+ spec = build_task_spec(+ agent,+ title="t",+ prompt="p",+ schedule={"kind": "every"},+ provider="openai-codex",+ model="gpt-5.6-sol",+ effort="high",+ account_id="acc-1",+ )+ assert routine_seat(spec) == {+ "provider": "openai-codex",+ "model": "gpt-5.6-sol",+ "effort": "high",+ "account_id": "acc-1",+ }+++async def test_list_exposes_the_pinned_seat(agent):+ store = FakeTaskStore()+ spec = build_task_spec(+ agent, title="t", prompt="p", schedule={"kind": "every"}, provider="antigravity"+ )+ await create_routine(store, None, spec)+ rows = await list_routines(store, "mailbox")+ assert rows[0]["provider"] == "antigravity"+ assert rows[0]["model"] == agent.model+++class _ManageStore(FakeTaskStore):+ def __init__(self, spec, row) -> None:+ super().__init__()+ self._spec = spec+ self._row = row+ self.updated = None++ async def get(self, task_id):+ return self._row++ async def get_spec(self, task_id):+ return self._spec+++class _ManageScheduler:+ def __init__(self) -> None:+ self.saved = None++ async def update_task(self, task_id, spec) -> None:+ self.saved = spec+++async def test_update_keeps_the_pin_unless_the_seat_moves(agent):+ spec = build_task_spec(+ agent, title="t", prompt="p", schedule={"kind": "every"}, provider="claude-api"+ )+ row = {"id": "task-1", "state": "scheduled", "spec_json": spec.model_dump_json()}+ store = _ManageStore(spec, row)+ scheduler = _ManageScheduler()+ await manage_routine(+ agent,+ {+ "task_id": "task-1",+ "operation": "update",+ "title": "t2",+ "prompt": "p2",+ "schedule": {"kind": "every"},+ },+ store,+ scheduler,+ )+ assert routine_seat(scheduler.saved)["provider"] == "claude-api"+ await manage_routine(+ agent,+ {+ "task_id": "task-1",+ "operation": "update",+ "title": "t2",+ "prompt": "p2",+ "schedule": {"kind": "every"},+ "provider": "openai-codex",+ "model": "gpt-5.6-sol",+ "effort": "",+ "account_id": "",+ },+ store,+ scheduler,+ )+ assert routine_seat(scheduler.saved) == {+ "provider": "openai-codex",+ "model": "gpt-5.6-sol",+ "effort": "",+ "account_id": "",+ }diff --git a/tests/unit/tasks/test_runner_agent_result.py b/tests/unit/tasks/test_runner_agent_result.pyindex a87ff149e0..15204bbc88 100644--- a/tests/unit/tasks/test_runner_agent_result.py+++ b/tests/unit/tasks/test_runner_agent_result.py@@ -211,8 +211,8 @@ async def test_rub95_explicit_announce_on_success_still_speaks_once(assert announcements[0].kind == "subagent"-async def test_a_failed_owner_seat_finishes_through_task_tools(store: TaskStore) -> None:- """A cancelled / tool-less owner seat is not the end of the routine."""+async def test_a_failed_owner_seat_is_never_rerouted_onto_api(store: TaskStore) -> None:+ """A society routine stays on its owner's seat: no silent API fallback."""async def owned_runner(task_id: str, tags: tuple[str, ...], prompt: str, cancel: Any):raise RuntimeError("cancelled")@@ -240,16 +240,43 @@ async def test_a_failed_owner_seat_finishes_through_task_tools(store: TaskStore)task_id = await store.insert(spec)await asyncio.wait_for(runner.run(task_id, CancelToken()), timeout=2.0)row = await store.get(task_id)+ assert row is not None and row["state"] == "failed"+ assert brain.prompts == []+ assert row["last_error"] is not None and "not rerouted" in row["last_error"]+ assert delivered and delivered[0][2] == "failed"+ assert announcements and "not rerouted" in announcements[0].text+ seat_step = next(+ s+ for s in row["steps"]+ if s["kind"] == "log" and s["payload"].get("event") == "owner_seat_failed"+ )+ assert seat_step["payload"]["fallback"] == "none"+++async def test_a_failed_owner_seat_still_falls_back_for_plain_tasks(store: TaskStore) -> None:+ """Generic (non-society) tasks keep the task-tools fallback path."""++ async def owned_runner(task_id: str, tags: tuple[str, ...], prompt: str, cancel: Any):+ raise RuntimeError("cancelled")++ brain = FakeAgentBrain()+ runner = TaskRunner(store, EventBus(), agent_brain=brain, owned_agent_runner=owned_runner)+ spec = TaskSpec(+ title="Plain sweep",+ trigger=TriggerAfterDelay(delay_seconds=0.01),+ action=AgentAction(+ prompt="Sort the inbox.",+ plugin_grants=(PluginGrant(plugin_id="gmail", scope="read"),),+ ),+ tags=("team",),+ )+ task_id = await store.insert(spec)+ await asyncio.wait_for(runner.run(task_id, CancelToken()), timeout=2.0)+ row = await store.get(task_id)assert row is not None and row["state"] == "completed"assert brain.prompts and "Sort the inbox." in brain.prompts[0]assert brain.kwargs[0].get("prefer_api") is Trueassert brain.kwargs[0]["allowed_tools"] == ("gmail",)- assert delivered == [(("society", "agent:mailbox"), "Inbox sorted: 3 replies drafted.", "done")]- assert announcements == []- assert any(- s["kind"] == "log" and s["payload"].get("event") == "owner_seat_failed"- for s in row["steps"]- )async def test_a_paused_owner_is_explained_not_impersonated(store: TaskStore) -> None:@@ -303,4 +330,4 @@ async def test_no_brain_after_seat_failure_says_there_was_no_other_path(row = await store.get(task_id)assert row is not None and row["state"] == "failed"assert row["last_error"] is not None- assert "No other path was available" in row["last_error"]+ assert "not rerouted" in row["last_error"]diff --git a/tests/unit/test_gigi_companion_asset.py b/tests/unit/test_gigi_companion_asset.pynew file mode 100644index 0000000000..2f773d7cd6--- /dev/null+++ b/tests/unit/test_gigi_companion_asset.py@@ -0,0 +1,45 @@+"""Check the actual review export, not an invented substitute model."""++import json+import struct+from pathlib import Path++ROOT = Path(__file__).resolve().parents[2]+STUDY = ROOT / "art/studies/gigi-hover-companion"+++def test_review_glb_has_editable_body_and_expression_nodes():+ raw = (STUDY / "exports/gigi.glb").read_bytes()+ assert raw[:4] == b"glTF"+ size = struct.unpack_from("<I", raw, 12)[0]+ data = json.loads(raw[20 : 20 + size])+ names = {node.get("name") for node in data["nodes"]}+ assert {+ "Gigi.Root",+ "Gigi.Housing",+ "Gigi.Face",+ "Gigi.Eye.L",+ "Gigi.Eye.R",+ "Gigi.Pupil.L",+ "Gigi.Pupil.R",+ "Gigi.Mouth",+ "Gigi.Arm.L",+ "Gigi.Arm.R",+ "Gigi.RearPanel",+ "Gigi.HoverEmitter",+ "Gigi.HemLight",+ } <= names+ assert not any("emblem" in name.lower() or "logo" in name.lower() for name in names)+ assert len(raw) <= 1_000_000+ triangles = sum(+ data["accessors"][primitive["indices"]]["count"] // 3+ for mesh in data["meshes"]+ for primitive in mesh["primitives"]+ )+ assert triangles <= 40_000+ assert len(data["meshes"]) <= 40+ assert not any("uri" in buffer for buffer in data["buffers"])+ assert {clip["name"] for clip in data["animations"]} >= {"Gigi.Blink.L", "Gigi.Blink.R"}+ # Blender 5 saves compressed sources; actual readability is checked by the+ # manifest export command, not guessed from an uncompressed file signature.+ assert (STUDY / "source/gigi.blend").stat().st_size > 1024diff --git a/tests/unit/test_outpost_reference.py b/tests/unit/test_outpost_reference.pynew file mode 100644index 0000000000..668f58373b--- /dev/null+++ b/tests/unit/test_outpost_reference.py@@ -0,0 +1,384 @@+"""Geometry and navigation contracts for the authored Outpost source recipe."""++from __future__ import annotations++import importlib.util+import json+import math+import struct+from pathlib import Path++import pytest++ROOT = Path(__file__).resolve().parents[2]+SPEC = importlib.util.spec_from_file_location(+ "outpost_reference", ROOT / "scripts/art/build_outpost_reference.py"+)+assert SPEC and SPEC.loader+recipe = importlib.util.module_from_spec(SPEC)+SPEC.loader.exec_module(recipe)+++def signed_volume(vertices, faces):+ total = 0+ for face in faces:+ origin = vertices[face[0]]+ for index in range(1, len(face) - 1):+ a, b = vertices[face[index]], vertices[face[index + 1]]+ cross = recipe.cross(a, b)+ total += sum(origin[axis] * cross[axis] for axis in range(3)) / 6+ return total+++def inside_box(point, center, size):+ return all(abs(point[axis] - center[axis]) < size[axis] / 2 for axis in range(3))+++def test_recipe_imports_without_blender_and_preserves_runtime_handedness():+ assert recipe.blender_point((0, 1, 0)) == (0, 0, 1)+ assert recipe.blender_point((0, 0, 1)) == (0, -1, 0)+ assert recipe.cross(+ recipe.blender_point((1, 0, 0)), recipe.blender_point((0, 1, 0))+ ) == recipe.blender_point((0, 0, 1))+++def test_shared_definition_drives_outpost_station_and_bridge_locations():+ layout = recipe.canonical_layout(ROOT / "jarvis/society/mars/definition.json")+ assert layout["origin"] == [320, 58, 50]+ assert layout["buildings"]["operations"]["local"] == (-26, 0, 14)+ assert layout["nodes"]["console"] == layout["buildings"]["operations"]["local"]+ assert layout["nodes"]["hub-east"] == (-195, -10, -10)+ assert layout["nodes"]["outpost-west"] == (-64, 0, 0)+++def test_incompatible_shared_axes_are_rejected(tmp_path):+ data = json.loads((ROOT / "jarvis/society/mars/definition.json").read_text())+ data["axes"]["up"] = "+Z"+ path = tmp_path / "definition.json"+ path.write_text(json.dumps(data))+ with pytest.raises(ValueError, match="metre/Y-up"):+ recipe.canonical_layout(path)+++def test_terrain_is_repeatable_closed_and_outward_with_real_depth():+ vertices, faces = recipe.plateau_mesh(6901)+ assert (vertices, faces) == recipe.plateau_mesh(6901)+ assert vertices != recipe.plateau_mesh(6902)[0]+ assert recipe.closed_edges(faces)+ assert signed_volume(vertices, faces) > 100_000+ assert min(point[1] for point in vertices) < -60+ assert max(point[1] for point in vertices) == pytest.approx(-0.12)+ assert all(math.isfinite(component) for point in vertices for component in point)++[email protected]("radius,depth", [(10.1, 2.5), (12.0, 3.1)])+def test_parabolic_dishes_have_front_back_and_closed_rim(radius, depth):+ vertices, faces = recipe.dish_mesh(radius, depth)+ assert recipe.closed_edges(faces)+ assert signed_volume(vertices, faces) > 0+ assert min(point[1] for point in vertices) == pytest.approx(-0.1)+ assert max(point[1] for point in vertices) == pytest.approx(depth)+++def test_graded_bridge_top_matches_both_navigation_endpoints():+ start, end = (-195, -10, -10), (-64, 0, 0)+ vertices, faces = recipe.deck_mesh(start, end)+ assert recipe.closed_edges(faces)+ assert signed_volume(vertices, faces) > 0+ assert recipe.lerp(vertices[0], vertices[3], 0.5) == start+ assert recipe.lerp(vertices[1], vertices[2], 0.5) == end+ assert recipe.length(+ tuple(vertices[0][axis] - vertices[3][axis] for axis in range(3))+ ) == pytest.approx(10)+ normal = recipe.cross(+ tuple(vertices[1][axis] - vertices[0][axis] for axis in range(3)),+ tuple(vertices[2][axis] - vertices[0][axis] for axis in range(3)),+ )+ assert normal[1] > 0+++def test_operations_door_has_true_clear_width_and_headroom():+ walls = recipe.operations_walls()+ # This journey crosses the advertised south doorway into the station room.+ for x in (-27.19, -26, -24.81):+ for y in (0.01, 1.75, 2.99):+ for z in (21.25, 21, 20.75, 19, 16, 14):+ assert not any(inside_box((x, y, z), center, size) for _, center, size in walls)+ assert any(inside_box((-27.35, 1.5, 21), center, size) for _, center, size in walls)+ assert any(inside_box((-26, 3.01, 20.81), center, size) for _, center, size in walls)+++def test_private_concepts_are_not_authored_geometry_dependencies():+ source = (ROOT / "scripts/art/build_outpost_reference.py").read_text(encoding="utf-8")+ assert "references/private" not in source+ assert "Downloads" not in source+ assert "image.open" not in source.lower()+++def test_shared_route_endpoints_export_one_anchor_and_reject_identity_conflicts():+ author = recipe.Author.__new__(recipe.Author)+ author.anchors = []+ author.anchor("outpost-arrival", (-52, 0, 18), kind="navigation")+ author.anchor("outpost-arrival", (-52, 0, 18), kind="navigation")+ assert len(author.anchors) == 1+ with pytest.raises(ValueError, match="conflicting definitions"):+ author.anchor("outpost-arrival", (-53, 0, 18), kind="navigation")+++def test_revised_tower_uses_separate_equipment_sections_inside_collision_envelope():+ sections = recipe.tower_sections()+ assert sections[0]["bottom"] == 5.8+ assert all(section["width"] < 14 and section["depth"] < 14 for section in sections)+ assert all(section["top"] > section["bottom"] for section in sections)+ assert all(a["top"] == b["bottom"] for a, b in zip(sections, sections[1:], strict=False))+ assert sections[-1]["top"] < 62++[email protected]("family", list(recipe.SURFACE_PROFILES))+def test_authored_surface_maps_are_repeatable_and_have_valid_tangent_normals(family):+ heights, normals = recipe.surface_grain(family, 16)+ assert (heights, normals) == recipe.surface_grain(family, 16)+ assert len(heights) == 256 and len(normals) == 1024+ assert max(heights) - min(heights) > 0.1+ assert all(0 <= value <= 1 for value in normals)+ for offset in range(0, len(normals), 4):+ vector = [normals[offset + axis] * 2 - 1 for axis in range(3)]+ assert sum(value * value for value in vector) == pytest.approx(1)+ assert vector[2] > 0+++def test_paint_relief_is_submillimetre_and_does_not_inherit_cliff_scale():+ paint = recipe.SURFACE_PROFILES["paint"]+ paving = recipe.SURFACE_PROFILES["paving"]+ mineral = recipe.SURFACE_PROFILES["mineral"]+ assert paint["relief_metres"] <= 0.0002+ assert paving["relief_metres"] <= 0.001+ assert mineral["relief_metres"] > paving["relief_metres"] * 10+ for family in ("paint", "metal", "paving"):+ _, normals = recipe.surface_grain(family)+ # Maximum microfacet tilt below 5 degrees; large seams belong to geometry.+ assert min(normals[2::4]) * 2 - 1 > math.cos(math.radians(5))+ assert recipe.surface_grain("paving", 16) != recipe.surface_grain("mineral", 16)+++def test_crossing_roads_have_one_top_surface_per_ground_location():+ horizontal = [(-4, -1), (4, -1), (4, 1), (-4, 1)]+ vertical = [(-1, -4), (1, -4), (1, 4), (-1, 4)]+ diagonal = [(-4, -3), (-3, -4), (4, 3), (3, 4)]+ routes = [+ ("arrival", horizontal, "road"),+ ("crossing", vertical, "road"),+ ("footpath", diagonal, "paving"),+ ]+ pieces = list(recipe.road_surface_pieces(routes))+ assert len(pieces) > len(routes)+ for index, (_, polygon, _) in enumerate(pieces):+ assert abs(recipe.polygon_area(polygon)) > 1e-8+ for _, other, _ in pieces[:index]:+ after = recipe.subtract_convex_polygon(polygon, other)+ assert sum(abs(recipe.polygon_area(part)) for part in after) == pytest.approx(+ abs(recipe.polygon_area(polygon)), abs=1e-7+ )+ vertices, faces = recipe.road_piece_mesh(polygon)+ assert recipe.closed_edges(faces)+ assert signed_volume(vertices, faces) == pytest.approx(+ abs(recipe.polygon_area(polygon)) * 0.24+ )++[email protected]("reverse", [False, True])+def test_surface_partition_handles_touching_edges_and_fully_occluded_route(reverse):+ first = [(0, 0), (2, 0), (2, 2), (0, 2)]+ second = [(2, 0), (4, 0), (4, 2), (2, 2)]+ if reverse:+ first.reverse()+ second.reverse()+ pieces = list(+ recipe.road_surface_pieces(+ [("first", first, "road"), ("touching", second, "road"), ("duplicate", first, "paving")]+ )+ )+ assert len(pieces) == 2+ assert sum(abs(recipe.polygon_area(polygon)) for _, polygon, _ in pieces) == 8+++def test_cliff_fragments_stay_below_walkable_terrace_without_moving_deep_rocks():+ assert recipe.fracture_center_y(-25, 8) == -25+ assert recipe.fracture_center_y(-3, 8) + 8 == pytest.approx(-0.20)+ for center in (-25, -15, -5, -3):+ for radius in (3, 5, 8):+ assert recipe.fracture_center_y(center, radius) + radius <= -0.20 + 1e-8+++def test_authored_perimeter_and_arrival_slabs_have_no_coplanar_top_overlap():+ class CapturePaths(recipe.Author):+ def __init__(self):+ self.layout = recipe.canonical_layout(ROOT / "jarvis/society/mars/definition.json")+ self.anchors = []+ self.surfaces = []++ def mesh(self, name, vertices, faces, material, smooth=False):+ if "surface" in name:+ self.surfaces.append(+ [(vertices[index][0], vertices[index][2]) for index in faces[0]]+ )+ assert recipe.closed_edges(faces)+ assert all(vertices[index][1] == 0.006 for index in faces[0])++ def group(self, *args):+ pass # Collection bookkeeping is irrelevant to the geometry check.++ def tube(self, *args, **kwargs):+ pass # Markings are deliberately raised, not competing slab tops.++ def lamp(self, *args):+ pass # Fixtures do not contribute road surface polygons.++ def beam(self, *args):+ pass # Railings do not contribute road surface polygons.++ author = CapturePaths()+ author.paths()+ assert 50 < len(author.surfaces) < 150+ for index, polygon in enumerate(author.surfaces):+ for other in author.surfaces[:index]:+ remaining = recipe.subtract_convex_polygon(polygon, other)+ assert sum(abs(recipe.polygon_area(piece)) for piece in remaining) == pytest.approx(+ abs(recipe.polygon_area(polygon)), abs=1e-6+ )+++def test_export_preserves_absolute_surface_tints_and_embeds_material_images():+ path = ROOT / "art/studies/mars-outpost-reference/exports/communications-outpost.glb"+ raw = path.read_bytes()+ json_bytes = struct.unpack_from("<I", raw, 12)[0]+ document = json.loads(raw[20 : 20 + json_bytes])+ mapped = 0+ for mesh in document["meshes"]:+ for primitive in mesh["primitives"]:+ material = document["materials"][primitive["material"]]+ if "COLOR_0" in primitive["attributes"]:+ # Surface tint contains absolute albedo, not a second darkening factor.+ factor = material.get("pbrMetallicRoughness", {}).get("baseColorFactor", [1] * 4)+ assert factor == pytest.approx([1] * 4)+ if "normalTexture" in material:+ mapped += 1+ assert "TEXCOORD_0" in primitive["attributes"]+ assert mapped > 0+ assert document["images"]+ assert all("bufferView" in image and "uri" not in image for image in document["images"])+ actual = recipe.validate_glb_material_attributes(raw)+ assert actual["colored_primitives"] > 0+ assert 0 <= actual["linear_color_range"][0] <= actual["linear_color_range"][1] <= 1+++def material_buffer_fixture(colors, *, byte_colors=False, normalized=False):+ """Padded, offset data makes incorrect accessor decoding fail visibly."""+ binary = b"PAD!" + struct.pack("<9f", *([0.0] * 9))+ encoded = b"PAD!"+ for color in colors:+ encoded += (+ struct.pack("<3B", *color) + b"\xff"+ if byte_colors+ else struct.pack("<4f", *color, 1234)+ )+ binary += encoded+ document = {+ "asset": {"version": "2.0"},+ "buffers": [{"byteLength": len(binary)}],+ "bufferViews": [+ {"buffer": 0, "byteOffset": 4, "byteLength": 36},+ {+ "buffer": 0,+ "byteOffset": 40,+ "byteLength": len(encoded),+ "byteStride": 4 if byte_colors else 16,+ },+ ],+ "accessors": [+ {"bufferView": 0, "componentType": 5126, "count": 3, "type": "VEC3"},+ {+ "bufferView": 1,+ "byteOffset": 4,+ "componentType": 5121 if byte_colors else 5126,+ "normalized": normalized,+ "count": 3,+ "type": "VEC3",+ },+ ],+ "meshes": [+ {"name": "regression", "primitives": [{"attributes": {"POSITION": 0, "COLOR_0": 1}}]}+ ],+ }+ payload = json.dumps(document).encode()+ payload += b" " * (-len(payload) % 4)+ return (+ struct.pack("<III", 0x46546C67, 2, 28 + len(payload) + len(binary))+ + struct.pack("<II", len(payload), 0x4E4F534A)+ + payload+ + struct.pack("<II", len(binary), 0x004E4942)+ + binary+ )+++def test_numeric_validator_rejects_uv_coordinates_written_into_color_memory():+ # Reproduced from the three-vertex Blender 5.0.1 stale-UV-handle failure.+ raw = material_buffer_fixture([(0.2, 0.3, 21), (22, 32, 0.4), (0.2, 0.3, 0.4)])+ with pytest.raises(ValueError, match="COLOR_0 outside"):+ recipe.validate_glb_material_attributes(raw)++[email protected]("bad", [float("nan"), float("inf"), -244.272, 72.88])+def test_numeric_validator_rejects_nonfinite_and_out_of_range_color_components(bad):+ raw = material_buffer_fixture([(0.2, 0.3, bad), (0.2, 0.3, 0.4), (0.2, 0.3, 0.4)])+ with pytest.raises(ValueError, match="COLOR_0"):+ recipe.validate_glb_material_attributes(raw)+++def test_numeric_validator_reads_offsets_strides_and_normalized_byte_colors():+ float_report = recipe.validate_glb_material_attributes(+ material_buffer_fixture([(0.2, 0.3, 0.4)] * 3)+ )+ assert float_report["linear_color_range"] == pytest.approx([0.2, 0.4])+ byte_report = recipe.validate_glb_material_attributes(+ material_buffer_fixture([(0, 128, 255)] * 3, byte_colors=True, normalized=True)+ )+ assert byte_report["linear_color_range"] == [0, 1]+++def test_public_source_validation_checks_packed_snapshot_separately_from_image_path():+ records = [+ ("Image.filepath", "//materials/paint-normal.png"),+ ("ImagePackedFile.filepath", "C:/Users/private-fixture/paint-normal.png"),+ ]+ with pytest.raises(ValueError, match=r"ImagePackedFile.filepath is not a portable") as failure:+ recipe.validate_source_path_records(records)+ assert "private-fixture" not in str(failure.value)++[email protected]("value", [b"C:/Users/private-fixture/", b"/home/private-fixture/", b"../"])+def test_public_source_validation_rejects_file_browser_profile_defaults(value):+ with pytest.raises(ValueError, match="FileSelectParams.dir"):+ recipe.validate_source_path_records([("FileSelectParams.dir", value)])+++def test_public_source_validation_accepts_only_neutral_relative_field_contracts():+ assert recipe.validate_source_path_records(+ [+ ("Image.filepath", "//materials/paint-normal.png"),+ ("ImagePackedFile.filepath", "//materials/paint-normal.png"),+ ("FileSelectParams.dir", b"//"),+ ("RenderData.pic", "//renders/"),+ ]+ ) == {"validated_fields": 4}+++def test_public_source_validation_handles_blender_native_relative_separators():+ assert recipe.validate_source_path_records(+ [+ ("Image.filepath", "//materials\\paint-normal.png"),+ ("RenderData.pic", "//renders\\"),+ ]+ ) == {"validated_fields": 2}+ with pytest.raises(ValueError, match="portable"):+ recipe.validate_source_path_records([("Image.filepath", "\\\\materials\\paint-normal.png")])diff --git a/tests/unit/ui/test_desktop_background.py b/tests/unit/ui/test_desktop_background.pynew file mode 100644index 0000000000..320220bb45--- /dev/null+++ b/tests/unit/ui/test_desktop_background.py@@ -0,0 +1,383 @@+"""Background lifecycle contracts with fake native surfaces, not physical OS proof."""++from __future__ import annotations++import asyncio+import sys+import threading+from types import SimpleNamespace++import pytest++from jarvis.ui.desktop_app import DesktopApp+from jarvis.ui.desktop_background import BackgroundSession+++class Event:+ def __init__(self, ready=False):+ self.handlers = []+ self.ready = ready++ def __iadd__(self, handler):+ self.handlers.append(handler)+ return self++ def is_set(self):+ return self.ready++ def wait(self, timeout=None):+ return self.ready++ def fire(self):+ self.ready = True+ for handler in self.handlers:+ handler()+++class Window:+ def __init__(self, renderer="edgechromium", *, ready=True):+ self.gui = SimpleNamespace(renderer=renderer)+ self.events = SimpleNamespace(+ shown=Event(ready), closed=Event(), closing=Event(), loaded=Event(),+ )+ self.hidden = False+ self.destroyed = False+ self.evaluated = []++ def hide(self):+ self.hidden = True++ def show(self):+ self.hidden = False++ def restore(self):+ self.hidden = False++ def destroy(self):+ self.events.closing.fire()+ self.destroyed = True+ self.events.closed.fire()++ def evaluate_js(self, script):+ self.evaluated.append(script)+++class Tray:+ ready = True++ def __init__(self):+ self.modes = []+ self.errors = []++ def set_background_mode(self, mode):+ self.modes.append(mode)++ def set_error(self, message):+ self.errors.append(message)+++def rig(monkeypatch):+ app = DesktopApp.__new__(DesktopApp)+ app._background = BackgroundSession()+ app._webview_persistent_profile = True+ app._window = Window()+ app._window_visible = True+ app._detached_windows = {}+ app._shutdown_done = False+ app._user_requested_quit = False+ app._tray = Tray()+ app._blank_watchdog = None+ app._background_created = []+ app._publish_detached_event_threadsafe = lambda *args, **kwargs: None+ app._window_background = lambda: "#000000"+ app._url = lambda: "http://localhost:47869"+ app._arm_blank_window_watchdog = lambda window: None+ app._restore_overlay_for_visible_window = lambda: None+ app._reload_window_if_stale = lambda: None+ app._safe_window_show = lambda: None+ app._arm_force_exit = lambda **kwargs: None+ app.realtime_transport_broker_token = "test-broker" # noqa: S105 - inert token-replay fixture++ def create_window(title, url=None, **kwargs):+ window = Window()+ app._background_created.append((window, title, url, kwargs))+ return window++ monkeypatch.setitem(sys.modules, "webview", SimpleNamespace(create_window=create_window))+ monkeypatch.setattr("jarvis.ui.desktop_app._bring_window_to_front_by_title", lambda title: True)+ monkeypatch.setattr("jarvis.ui.icon_utils.set_window_icon_by_title", lambda *args: True)+ monkeypatch.setattr("jarvis.ui.icon_utils.project_icon_path", lambda: "icon.ico")+ return app+++async def enable(app):+ return await asyncio.to_thread(app.set_background_mode, True)+++async def test_opt_in_destroys_real_window_keeps_same_backend_and_reopens(rig):+ original = rig._window+ backend = rig._server = object()+ rig._hook_main_window_lifecycle()+ assert rig.get_background_status()["enabled"] is False+ assert (await enable(rig))["enabled"] is True+ keeper, _, url, kwargs = rig._background_created[0]+ assert url is None+ assert kwargs["hidden"] is True+ assert "script" not in kwargs["html"]+ assert "jarvis" not in kwargs["html"].lower()+ assert keeper.evaluated == []+ assert not keeper.events.loaded.handlers++ original.destroy()++ assert original.destroyed and not original.hidden+ assert rig._window is None+ assert rig._server is backend+ assert not rig._user_requested_quit+ assert rig.get_background_status()["mode"] == "background"+ assert rig._tray.modes[-1] == "background"+ assert not keeper.destroyed++ result = await asyncio.to_thread(rig._focus_window_now)+ assert result == {"ok": True, "focused": True}+ assert rig._window is not original+ assert rig._server is backend+ assert rig.get_background_status()["mode"] == "foreground"+++def test_default_close_still_quits(rig):+ assert rig._on_window_closing() is True+ assert rig._user_requested_quit is True+ assert rig._background_created == []++[email protected]("renderer", ["edgechromium", "wkwebview", "qtwebengine"])+async def test_shared_background_path_with_fake_gui_capabilities(rig, renderer):+ rig._window.gui.renderer = renderer+ assert (await enable(rig))["enabled"] is True+++ "reason", ["tray_unavailable", "hidden_window_unavailable", "native_window_not_ready"],+)+async def test_unavailable_never_arms_or_creates_keeper(rig, reason):+ if reason == "tray_unavailable":+ rig._tray.ready = False+ elif reason == "hidden_window_unavailable":+ rig._window.gui.renderer = "gtkwebkit2"+ else:+ rig._window.events.shown.ready = False+ status = await enable(rig)+ assert not status["available"] and not status["enabled"]+ assert status["reason"] == reason+ assert rig._background_created == []++[email protected]("persistent", [False, None])+async def test_private_or_unknown_profile_refuses_keeper_without_changing_auth(rig, persistent):+ rig._webview_persistent_profile = persistent+ status = await enable(rig)+ assert status["reason"] == "persistent_profile_unavailable"+ assert not status["available"] and not status["enabled"]+ assert rig._background_created == []+++async def test_enable_is_idempotent_and_disabling_restores_main_first(rig):+ await enable(rig)+ await enable(rig)+ assert len(rig._background_created) == 1+ keeper = rig._background.keeper+ rig._window = None++ status = await asyncio.to_thread(rig.set_background_mode, False)++ assert rig._window is not None+ assert keeper.destroyed+ assert not status["enabled"]+ assert not rig._user_requested_quit+++async def test_reopen_failure_preserves_background_control(rig):+ await enable(rig)+ rig._window = None+ keeper = rig._background.keeper+ rig._ensure_main_window = lambda: None+ status = await asyncio.to_thread(rig.set_background_mode, False)+ assert status["enabled"] and status["reason"] == "reopen_failed"+ assert not keeper.destroyed+++async def test_failed_keeper_readiness_does_not_change_close_policy(rig, monkeypatch):+ keeper = Window(ready=False)+ monkeypatch.setitem(+ sys.modules, "webview", SimpleNamespace(create_window=lambda *a, **k: keeper),+ )+ status = await enable(rig)+ assert status["reason"] == "hidden_window_not_ready"+ assert not status["enabled"] and keeper.destroyed+ assert rig._on_window_closing() is True+ assert rig._user_requested_quit+++async def test_last_detached_close_respects_opt_in(rig):+ await enable(rig)+ rig._window = None+ rig._detached_windows["chats"] = Window()+ rig._on_detached_closed("chats")+ assert not rig._user_requested_quit+ assert rig.get_background_status()["mode"] == "background"+++async def test_explicit_quit_destroys_keeper_even_with_no_visible_window(rig, monkeypatch):+ await enable(rig)+ keeper = rig._background.keeper+ rig._window = None+ done = threading.Event()++ def sequence(*, set_quit, destroy_window):+ set_quit()+ destroy_window()+ done.set()++ monkeypatch.setattr("jarvis.ui.relauncher.run_restart_quit_sequence", sequence)+ assert rig.request_quit()+ assert await asyncio.to_thread(done.wait, 2.0)+ assert keeper.destroyed and rig._user_requested_quit+ assert not rig.get_background_status()["enabled"]+++async def test_tray_loss_restores_real_control_surface(rig):+ await enable(rig)+ keeper = rig._background.keeper+ rig._window = None+ rig._tray.ready = False+ await asyncio.to_thread(rig._background_control_lost)+ assert rig._window is not None+ assert keeper.destroyed+ assert not rig._user_requested_quit+++async def test_tray_loss_with_failed_reopen_ends_hidden_execution(rig):+ await enable(rig)+ keeper = rig._background.keeper+ rig._window = None+ rig._tray.ready = False+ rig._ensure_main_window = lambda: None+ await asyncio.to_thread(rig._background_control_lost)+ assert rig._user_requested_quit and keeper.destroyed+++async def test_idle_bridge_restores_control_without_any_client_or_status_request(rig, monkeypatch):+ import queue++ from jarvis.ui.tray import TrayCommand++ class BridgeTray(Tray):+ def __init__(self):+ super().__init__()+ self._command_queue = queue.Queue()++ def start(self):+ pass # The fake has no native thread; the real bridge still runs.++ def set_state(self, state):+ pass # Voice activity does not affect this lifecycle fixture.++ await enable(rig)+ keeper = rig._background.keeper+ rig._window = None+ tray = BridgeTray()+ monkeypatch.setattr("jarvis.ui.tray.JarvisTray", lambda: tray)+ restored = threading.Event()+ restore = rig._background_control_lost++ def on_loss():+ restore()+ restored.set()++ rig._background_control_lost = on_loss+ rig._start_tray_and_bridge()+ try:+ # No frontend, GET/status read, or tray command reports the loss.+ tray.ready = False+ assert await asyncio.to_thread(restored.wait, 2.0)+ assert keeper.destroyed and rig._window is not None+ assert not rig._background.enabled and not rig._user_requested_quit+ restored_window = rig._window+ await asyncio.to_thread(restore)+ assert rig._window is restored_window++ # A recovered tray does not silently re-arm the session's close policy.+ tray.ready = True+ assert not rig._background.enabled+ assert (await enable(rig))["enabled"]+ finally:+ rig._shutdown_done = True+ tray._command_queue.put(TrayCommand(action="test_shutdown"))+ await asyncio.to_thread(rig._tray_bridge_thread.join, 2.0)+ rig._destroy_background_keeper()+ assert not rig._tray_bridge_thread.is_alive()+++async def test_backend_death_with_only_keeper_exits_instead_of_ghosting(rig):+ await enable(rig)+ keeper = rig._background.keeper+ rig._window = None+ destroyed = threading.Event()+ original_destroy = rig._destroy_all_windows++ def destroy():+ original_destroy()+ destroyed.set()++ rig._destroy_all_windows = destroy+ rig._note_backend_stopped("test failure")+ assert await asyncio.to_thread(destroyed.wait, 2.0)+ assert keeper.destroyed and rig._user_requested_quit+ assert rig._tray.errors == ["Backend stopped"]+++def test_reopened_main_does_not_replay_one_time_auth_token(rig):+ window = Window()+ rig._inject_reopened_main(window)+ script = "".join(window.evaluated)+ assert "__JARVIS_EMBEDDED_DESKTOP" in script+ assert "__JARVIS_REALTIME_BROKER_TOKEN" in script+ assert "__JARVIS_TOKEN =" not in script+++async def test_quit_racing_enable_cannot_leave_keeper(rig, monkeypatch):+ keeper = Window()++ def create(*args, **kwargs):+ rig._user_requested_quit = True+ return keeper++ monkeypatch.setitem(sys.modules, "webview", SimpleNamespace(create_window=create))+ status = await enable(rig)+ assert not status["enabled"] and status["mode"] == "stopping"+ assert keeper.destroyed+++async def test_disable_during_window_close_preserves_keeper(rig):+ await enable(rig)+ keeper = rig._background.keeper+ assert rig._on_window_closing()+ result = await asyncio.to_thread(rig.set_background_mode, False)+ assert result["reason"] == "window_closing"+ assert result["enabled"] and not keeper.destroyed+++async def test_disable_waits_for_native_reopened_window(rig):+ await enable(rig)+ keeper = rig._background.keeper+ rig._window = None++ def pending_reopen():+ rig._window = Window(ready=False)++ rig._ensure_main_window = pending_reopen+ result = await asyncio.to_thread(rig.set_background_mode, False)+ assert result["reason"] == "reopen_failed"+ assert result["enabled"] and not keeper.destroyeddiff --git a/tests/unit/ui/test_desktop_background_tray.py b/tests/unit/ui/test_desktop_background_tray.pynew file mode 100644index 0000000000..6288b29e86--- /dev/null+++ b/tests/unit/ui/test_desktop_background_tray.py@@ -0,0 +1,164 @@+"""A background shell needs a visible, stoppable tray, not a started thread."""++from __future__ import annotations++import threading++from jarvis.ui.tray import JarvisTray+++class Icon:+ HAS_MENU = True+ visible = False++ def __init__(self):+ self.stopped = threading.Event()+ self.stop_calls = 0+ self.menu_updates = 0++ def stop(self):+ self.stop_calls += 1+ self.stopped.set()++ def update_menu(self):+ self.menu_updates += 1+++def test_readiness_waits_for_visibility_setup_and_reset_notifies_bridge():+ present = [True]+ tray = JarvisTray(native_presence=lambda icon: present[0])+ icon = tray._icon = Icon()+ assert not tray.ready+ tray._setup_icon(icon)+ assert icon.visible and tray.ready+ present[0] = False+ assert not tray.ready+ assert tray._command_queue.get_nowait().action == "tray_unavailable"+ tray._notify_unavailable()+ assert tray._command_queue.empty()+++def test_icon_without_menu_cannot_offer_background_mode():+ tray = JarvisTray(native_presence=lambda icon: True)+ icon = tray._icon = Icon()+ icon.HAS_MENU = False+ tray._setup_icon(icon)+ assert icon.visible and not tray.ready+++def test_shutdown_cannot_race_late_setup_back_to_ready():+ tray = JarvisTray(native_presence=lambda icon: True)+ icon = tray._icon = Icon()+ tray.stop()+ tray._setup_icon(icon)+ assert not tray.ready and not icon.visible+++def test_tray_stop_joins_owned_native_thread_and_is_idempotent():+ tray = JarvisTray(native_presence=lambda icon: True)+ icon = tray._icon = Icon()+ thread = tray._thread = threading.Thread(target=icon.stopped.wait, daemon=True)+ thread.start()+ tray._setup_icon(icon)+ tray.stop()+ tray.stop()+ assert not thread.is_alive()+ assert not tray.ready+ assert icon.stop_calls == 1+ assert tray._command_queue.empty()+++def test_background_status_is_distinct_from_voice_activity():+ tray = JarvisTray()+ icon = tray._icon = Icon()+ tray.set_background_mode("background")+ assert "background" in icon.title+ assert "idle" in icon.title+ assert icon.menu_updates == 1+++def test_optimistic_visible_flag_is_not_native_registration():+ tray = JarvisTray(native_presence=lambda icon: False)+ icon = tray._icon = Icon()+ tray._setup_icon(icon)+ assert icon.visible+ assert not tray.ready+++def test_native_presence_recovers_only_after_fresh_positive_ack():+ present = [True]+ tray = JarvisTray(native_presence=lambda icon: present[0])+ tray._icon = Icon()+ tray._setup_icon(tray._icon)+ assert tray.ready+ present[0] = False+ assert not tray.ready+ assert tray._command_queue.get_nowait().action == "tray_unavailable"+ present[0] = True+ assert tray.ready+++def test_native_query_marshals_own_hwnd_and_requires_successful_nonempty_rect():+ from types import SimpleNamespace++ from jarvis.ui.desktop_background import _query_notification_icon_rect++ class Query:+ result = 0+ width = 20++ def __call__(self, identifier, rect):+ value = identifier._obj+ assert value.hWnd == 0x123456789+ assert value.uID == 0+ assert bytes(value.guidItem) == bytes(16)+ assert value.cbSize > 0+ rect._obj.left = -20+ rect._obj.top = 10+ rect._obj.right = -20 + self.width+ rect._obj.bottom = 30+ return self.result++ query = Query()+ shell32 = SimpleNamespace(Shell_NotifyIconGetRect=query)+ assert _query_notification_icon_rect(0x123456789, 0, shell32)+ query.result = -2147467259+ assert not _query_notification_icon_rect(0x123456789, 0, shell32)+ query.result = 0+ query.width = 0+ assert not _query_notification_icon_rect(0x123456789, 0, shell32)+++def test_nonwindows_tray_presence_is_honestly_unavailable(monkeypatch):+ from types import SimpleNamespace++ from jarvis.ui import desktop_background++ monkeypatch.setattr(desktop_background, "os", SimpleNamespace(name="posix"))+ assert not desktop_background.native_tray_present(SimpleNamespace(_hwnd=123))+++def test_hung_native_query_has_one_worker_and_bounded_caller_wait():+ from jarvis.ui.desktop_background import TrayPresenceProbe++ release = threading.Event()+ entered = threading.Event()+ calls = []++ def query(icon):+ calls.append(icon)+ entered.set()+ release.wait(timeout=2.0)+ return True++ probe = TrayPresenceProbe(query)+ try:+ assert not probe.check("icon", timeout=0.01)+ assert entered.wait(timeout=1.0)+ for _ in range(3):+ assert not probe.check("icon", timeout=0.01)+ assert calls == ["icon"]+ finally:+ release.set()+ probe.stop()+ assert not probe.check("icon")diff --git a/tests/unit/ui/test_desktop_detached_windows.py b/tests/unit/ui/test_desktop_detached_windows.pyindex 2baaeb7fd9..d450ce1650 100644--- a/tests/unit/ui/test_desktop_detached_windows.py+++ b/tests/unit/ui/test_desktop_detached_windows.py@@ -327,7 +327,7 @@ def test_ensure_main_window_recreates_and_rehooks(monkeypatch) -> None:assert app._window_visible is Trueassert len(created[0].events.closing) == 1 # quit contract re-attachedassert len(created[0].events.closed) == 1 # null-out re-attached- assert len(created[0].events.loaded) == 1 # drop-path bridge re-attached+ assert len(created[0].events.loaded) == 2 # drop bridge and authenticated shell restore# --- native drop bridge --------------------------------------------------------diff --git a/tests/unit/ui/test_restart_launch_context.py b/tests/unit/ui/test_restart_launch_context.pynew file mode 100644index 0000000000..406574a637--- /dev/null+++ b/tests/unit/ui/test_restart_launch_context.py@@ -0,0 +1,169 @@+"""A desktop restart keeps the endpoint and source environment it was given."""++from __future__ import annotations++from contextlib import nullcontext+from pathlib import Path+from types import SimpleNamespace++import pytest++from jarvis.ui import relauncher++[email protected](autouse=True)+def _isolated_context(monkeypatch):+ monkeypatch.setattr(relauncher, "_desktop_launch_args", ())+++def test_desktop_overrides_are_replaced_for_each_launch():+ relauncher.remember_desktop_launch_args(port=47869, dev=True, no_lock=True)+ assert relauncher.desktop_launch_args() == ("--port", "47869", "--dev", "--no-lock")+ relauncher.remember_desktop_launch_args(port=None, dev=False, no_lock=False)+ assert relauncher.desktop_launch_args() == ()++[email protected]("platform", ["win32", "linux", "darwin"])+def test_dev_restart_keeps_explicit_overrides_and_active_interpreter(monkeypatch, platform):+ from jarvis.core import instance++ identity = SimpleNamespace(is_default=False, launcher_args=("--instance", "dev"))+ monkeypatch.setattr(instance, "current_instance", lambda: identity)+ monkeypatch.setattr(relauncher.sys, "platform", platform)+ monkeypatch.setattr(relauncher, "_existing_branded_launcher", lambda: None)+ executable = "/isolated/.venv/bin/python"+ args = ("--port", "47869", "--dev", "--no-lock")+ assert relauncher.build_launch_command(executable, launcher_args=args) == [+ executable,+ "-m",+ relauncher.LAUNCHER_MODULE,+ "--instance",+ "dev",+ *args,+ ]+++def test_macos_default_keeps_launchservices_and_passes_overrides(monkeypatch, tmp_path):+ from jarvis.core import instance+ from jarvis.setup import macos_app_bundle++ monkeypatch.setattr(+ instance,+ "current_instance",+ lambda: SimpleNamespace(+ is_default=True,+ launcher_args=(),+ ),+ )+ monkeypatch.setattr(relauncher.sys, "platform", "darwin")+ bundle = tmp_path / "Personal Jarvis.app"+ monkeypatch.setattr(macos_app_bundle, "macos_app_bundle_path", lambda: bundle)+ monkeypatch.setattr(macos_app_bundle, "macos_app_bundle_is_launchable", lambda _: True)+ args = ("--port", "47869", "--no-lock")+ assert relauncher.build_launch_command("python", launcher_args=args) == [+ "/usr/bin/open",+ "-W",+ "-a",+ str(bundle),+ "--args",+ *args,+ ]+++def test_explicit_port_probe_never_uses_the_configured_instance_port(monkeypatch):+ addresses = []++ def forbidden_config_port(_cwd):+ raise AssertionError("An explicit endpoint must not be re-derived from config")++ monkeypatch.setattr(relauncher, "_restart_admin_port", forbidden_config_port)+ assert relauncher._desktop_is_serving(+ cwd="isolated",+ port=47869,+ _connect=lambda address, **kwargs: addresses.append(address) or nullcontext(),+ )+ assert addresses == [("127.0.0.1", 47869)]+++def test_helper_preserves_overrides_cwd_and_venv_without_repinning(monkeypatch, tmp_path):+ from jarvis.core import instance+ from jarvis.ui import desktop_log++ monkeypatch.setattr(+ instance,+ "current_instance",+ lambda: SimpleNamespace(+ is_default=False,+ launcher_args=("--instance", "dev"),+ ),+ )+ monkeypatch.setattr(relauncher.sys, "platform", "linux")+ executable = str(tmp_path / ".venv" / "bin" / "python")+ monkeypatch.setattr(relauncher.sys, "executable", executable)+ monkeypatch.setattr(relauncher, "fresh_user_env", lambda: {"VIRTUAL_ENV": "preserved"})+ monkeypatch.setattr(desktop_log, "_install_desktop_log_sink", lambda _: None)+ spawned = []+ probes = []+ monkeypatch.setattr(relauncher, "_desktop_is_serving", lambda **kw: probes.append(kw) or True)+ args = ("--port", "47869", "--dev", "--no-lock")+ assert (+ relauncher.main(+ ["123", str(tmp_path), *args],+ _spawn=lambda cmd, **kw: spawned.append((cmd, kw)) or SimpleNamespace(pid=456),+ _alive=lambda _: False,+ _sleep=lambda _: None,+ _finalize_update=lambda _: True,+ )+ == 0+ )+ assert len(spawned) == 1+ command, kwargs = spawned[0]+ assert command == [executable, "-m", relauncher.LAUNCHER_MODULE, "--instance", "dev", *args]+ assert kwargs["cwd"] == str(tmp_path)+ assert kwargs["env"] == {"VIRTUAL_ENV": "preserved"}+ assert probes and all(p == {"cwd": str(tmp_path), "port": 47869} for p in probes)++[email protected]("args", [["--port", "0"], ["--port", "65536"], ["--port"], ["--other"]])+def test_invalid_helper_overrides_do_not_start_or_stop_any_process(args):+ def forbidden(*_args, **_kwargs):+ raise AssertionError("Invalid overrides must be rejected before lifecycle work")++ assert relauncher.main(["123", "isolated", *args], _spawn=forbidden, _alive=forbidden) == 2+++def test_desktop_sends_context_to_detached_helper_without_running_it(monkeypatch):+ import jarvis+ from jarvis.ui import desktop_app++ relauncher.remember_desktop_launch_args(port=47869, dev=True, no_lock=True)+ spawned = []+ threads = []+ monkeypatch.setattr(relauncher, "fresh_user_env", lambda: {"JARVIS_INSTANCE": "dev"})+ monkeypatch.setattr(relauncher, "spawn_detached", lambda cmd, **kw: spawned.append((cmd, kw)))++ class DeferredThread:+ def __init__(self, **kwargs):+ threads.append(kwargs)++ def start(self):+ pass # Keep the real quit callback unexecuted in this test.++ monkeypatch.setattr(desktop_app.threading, "Thread", DeferredThread)+ app = SimpleNamespace(_window=object())+ assert desktop_app.DesktopApp._schedule_restart(app, drop_elevation=False)[0]+ command, kwargs = spawned[0]+ root = str(Path(jarvis.__file__).resolve().parent.parent)+ assert command == [+ desktop_app.sys.executable,+ "-m",+ "jarvis.ui.relauncher",+ str(desktop_app.os.getpid()),+ root,+ "--port",+ "47869",+ "--dev",+ "--no-lock",+ ]+ assert kwargs == {"cwd": root, "env": {"JARVIS_INSTANCE": "dev"}}+ assert len(threads) == 1 and threads[0]["daemon"] is Truediff --git a/tests/unit/ui/test_tk_runtime.py b/tests/unit/ui/test_tk_runtime.pynew file mode 100644index 0000000000..eddb1b0773--- /dev/null+++ b/tests/unit/ui/test_tk_runtime.py@@ -0,0 +1,74 @@+"""Relocated launchers must find their own Tcl/Tk script libraries."""++import os+import sys+from types import SimpleNamespace++import pytest++from jarvis.ui import tk_runtime+++def runtime(monkeypatch, tmp_path):+ monkeypatch.setattr(sys, "platform", "win32")+ monkeypatch.setattr(sys, "base_prefix", str(tmp_path / "base"))+ monkeypatch.setitem(sys.modules, "_tkinter", SimpleNamespace(+ __file__=str(tmp_path / "loaded" / "DLLs" / "_tkinter.pyd"),+ TCL_VERSION="8.6", TK_VERSION="8.6",+ ))+ # Restore both process-local variables after every case, including ones+ # where production code fills an initially missing value.+ monkeypatch.setenv("TCL_LIBRARY", "")+ monkeypatch.setenv("TK_LIBRARY", "")+ return tmp_path+++def libraries(root, folder="tcl", version="8.6"):+ tcl = root / folder / f"tcl{version}"+ tk = root / folder / f"tk{version}"+ tcl.mkdir(parents=True)+ tk.mkdir(parents=True)+ (tcl / "init.tcl").write_text("# Tcl test data", encoding="utf-8")+ (tk / "tk.tcl").write_text("# Tk test data", encoding="utf-8")+ return str(tcl), str(tk)+++def test_relocated_launcher_uses_loaded_extension_installation(runtime):+ expected = libraries(runtime / "loaded")+ libraries(runtime / "base")+ tk_runtime.prepare_tk_runtime()+ assert (os.environ["TCL_LIBRARY"], os.environ["TK_LIBRARY"]) == expected++[email protected]("folder", ["tcl", "lib"])+def test_base_installation_is_a_valid_fallback(runtime, folder):+ expected = libraries(runtime / "base", folder=folder)+ tk_runtime.prepare_tk_runtime()+ assert (os.environ["TCL_LIBRARY"], os.environ["TK_LIBRARY"]) == expected+++def test_explicit_environment_overrides_are_preserved(runtime, monkeypatch):+ libraries(runtime / "loaded")+ monkeypatch.setenv("TCL_LIBRARY", "custom-tcl")+ monkeypatch.setenv("TK_LIBRARY", "custom-tk")+ tk_runtime.prepare_tk_runtime()+ assert os.environ["TCL_LIBRARY"] == "custom-tcl"+ assert os.environ["TK_LIBRARY"] == "custom-tk"+++def test_incomplete_or_wrong_version_data_is_not_selected(runtime):+ libraries(runtime / "loaded", version="9.0")+ (runtime / "base" / "tcl" / "tcl8.6").mkdir(parents=True)+ tk_runtime.prepare_tk_runtime()+ assert os.environ["TCL_LIBRARY"] == ""+ assert os.environ["TK_LIBRARY"] == ""++[email protected]("platform", ["darwin", "linux"])+def test_other_platforms_need_no_tk_import_or_environment_change(runtime, monkeypatch, platform):+ monkeypatch.setattr(sys, "platform", platform)+ monkeypatch.setitem(sys.modules, "_tkinter", None)+ tk_runtime.prepare_tk_runtime()+ assert os.environ["TCL_LIBRARY"] == ""+ assert os.environ["TK_LIBRARY"] == ""diff --git a/tests/unit/ui/test_tray.py b/tests/unit/ui/test_tray.pyindex edeadd51a3..184c60bc9b 100644--- a/tests/unit/ui/test_tray.py+++ b/tests/unit/ui/test_tray.py@@ -35,14 +35,19 @@ def test_tray_start_is_noop_without_display(monkeypatch, caplog) -> None:class _FakeDetachedIcon:"""Records the ctor kwargs + run_detached()/stop() calls."""+ HAS_MENU = True+def __init__(self, name: str, **kwargs) -> None:self.name = nameself.kwargs = kwargsself.run_detached_calls = 0self.stop_calls = 0+ self.visible = False- def run_detached(self) -> None:+ def run_detached(self, setup=None) -> None:self.run_detached_calls += 1+ if setup is not None:+ setup(self)def stop(self) -> None:self.stop_calls += 1@@ -111,7 +116,7 @@ def test_tray_start_on_macos_main_thread_runs_detached(monkeypatch) -> None:monkeypatch.setattr(tray_mod, "display_present", lambda: True, raising=False)monkeypatch.setattr(tray_mod, "_make_icon", lambda state, size=64: object())nsapp = _install_fake_darwin_modules(monkeypatch, _FakeDetachedIcon)- t = JarvisTray()+ t = JarvisTray(native_presence=lambda icon: True)t.start()assert t._thread is None # no jarvis-tray worker thread on darwinicon = t._icon@@ -119,11 +124,13 @@ def test_tray_start_on_macos_main_thread_runs_detached(monkeypatch) -> None:assert icon.kwargs["darwin_nsapplication"] is nsappassert icon.run_detached_calls == 1assert t._darwin_detached is True+ assert t.ready is True# stop() must reach the detached icon through the main-thread marshal.t.stop()assert icon.stop_calls == 1assert t._icon is Noneassert t._darwin_detached is False+ assert t.ready is Falsedef test_tray_start_on_macos_main_thread_degrades_when_icon_ctor_raises(diff --git a/tests/unit/ui/test_window_command.py b/tests/unit/ui/test_window_command.pynew file mode 100644index 0000000000..a1e76c2056--- /dev/null+++ b/tests/unit/ui/test_window_command.py@@ -0,0 +1,70 @@+"""Caption buttons call the same window methods the frame used to."""++from types import SimpleNamespace++from fastapi import FastAPI+from fastapi.testclient import TestClient++from jarvis.ui.web.desktop_routes import router+from jarvis.ui.window_command import run_window_command, window_chrome+++class Window:+ def __init__(self) -> None:+ self.calls: list[str] = []++ def minimize(self) -> None:+ self.calls.append("minimize")++ def maximize(self) -> None:+ self.calls.append("maximize")++ def restore(self) -> None:+ self.calls.append("restore")++ def destroy(self) -> None:+ self.calls.append("destroy")+++def test_chrome_side_follows_the_platform():+ assert window_chrome("darwin")["controls"] == "leading"+ assert window_chrome("win32")["controls"] == "trailing"+ assert window_chrome("linux")["controls"] == "trailing"+ assert window_chrome("win32")["frameless"] is False+++def test_maximize_toggles_and_close_destroys():+ window = Window()+ assert run_window_command(window, "maximize")["maximized"] is True+ assert run_window_command(window, "maximize")["maximized"] is False+ assert run_window_command(window, "maximize", maximized=True)["maximized"] is False+ assert run_window_command(window, "minimize") == {"ok": True, "maximized": False}+ assert run_window_command(window, "close")["ok"] is True+ assert window.calls == ["maximize", "restore", "restore", "minimize", "destroy"]+++def test_missing_window_and_unknown_action():+ assert run_window_command(None, "close")["reason"] == "no_window"+ window = Window()+ assert run_window_command(window, "explode")["reason"] == "unknown_action"+ assert window.calls == []+++def test_routes_without_a_desktop_shell():+ app = FastAPI()+ app.include_router(router)+ client = TestClient(app)+ assert client.get("/api/window/chrome").json()["controls"] == "none"+ denied = client.post("/api/window/command", json={"action": "minimize"}).json()+ assert denied["reason"] == "no_desktop_shell"+ window = Window()+ app.state.desktop_app = SimpleNamespace(+ window_chrome_snapshot=lambda: {**window_chrome("win32"), "frameless": True},+ window_command=lambda action, view: run_window_command(window, action),+ )+ assert client.get("/api/window/chrome").json()["frameless"] is True+ assert client.post("/api/window/command", json={"action": "close"}).json()["ok"] is True+ assert window.calls == ["destroy"]+ operation = app.openapi()["paths"]["/api/window/command"]["post"]+ assert operation["operationId"] == "command"+ assert operation["tags"] == ["window"]diff --git a/tests/unit/ui/web/test_society_routes.py b/tests/unit/ui/web/test_society_routes.pyindex a447117408..30f512cce7 100644--- a/tests/unit/ui/web/test_society_routes.py+++ b/tests/unit/ui/web/test_society_routes.py@@ -53,7 +53,11 @@ def client(tmp_path: Path):app.state.society = Noneapp.state.society_factory = lambda: runtimewith TestClient(app) as c:- yield c, manager+ try:+ yield c, manager+ finally:+ assert c.portal is not None+ c.portal.call(runtime.close)def test_lead_is_seeded_and_listed(client):@@ -85,7 +89,7 @@ def test_create_derives_focus_and_rules(client):assert again["created"] is False-def test_patch_rederives_focus_on_description_change(client):+def test_patch_preserves_and_extends_focus_on_description_change(client):c, _ = clientc.post("/api/society/agents", json={"name": "Scout", "description": "Research on the web."})first = c.get("/api/society/agents/scout").json()["agent"]@@ -93,7 +97,7 @@ def test_patch_rederives_focus_on_description_change(client):patched = c.patch("/api/society/agents/scout", json={"description": "Handle my mail inbox."}).json()["agent"]- assert patched["focus"] == ["plugin:gmail"]+ assert patched["focus"] == ["core:search-web", "plugin:gmail"]explicit = c.patch("/api/society/agents/scout", json={"focus": []}).json()["agent"]assert explicit["focus"] == []@@ -193,7 +197,7 @@ def test_kill_switch_round_trip(client):def test_capabilities_catalog_hides_dispatch(client):c, _ = clientids = [r["id"] for r in c.get("/api/society/capabilities").json()["capabilities"]]- assert ids == ["plugin:gmail", "core:search-web"]+ assert ids == ["plugin:gmail", "core:browser", "core:coding-session", "core:search-web"]def test_rooms_over_rest(client):diff --git a/tests/unit/ui/web/test_society_shutdown.py b/tests/unit/ui/web/test_society_shutdown.pynew file mode 100644index 0000000000..25074e17f0--- /dev/null+++ b/tests/unit/ui/web/test_society_shutdown.py@@ -0,0 +1,351 @@+"""The server must release the real roster database before its event loop exits."""++from __future__ import annotations++import asyncio+import os+import subprocess+import sys+import threading+from pathlib import Path++import pytest+from fastapi import HTTPException, Request++from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS+from jarvis.society.runtime import SocietyRuntime, SocietyRuntimeClosed, current_runtime+from jarvis.ui.web.society_routes import list_agents+from tests.fakes.fake_society_shutdown import society_shutdown_server+++async def start_roster(tmp_path):+ runtime = SocietyRuntime(tmp_path)+ server, cleaned = society_shutdown_server(runtime)+ response = await list_agents(Request({"type": "http", "app": server.app}))+ assert response["agents"]+ connection = runtime.store._conn+ delivery = runtime._delivery_task+ assert connection is not None and delivery is not None+ assert current_runtime() is runtime+ return runtime, server, cleaned, connection, delivery+++async def test_server_stop_closes_real_roster_store_and_delivery(tmp_path, monkeypatch):+ runtime, server, cleaned, connection, delivery = await start_roster(tmp_path)+ original_close = runtime.browser.close+ watcher_started = asyncio.Event()++ async def check_close_order():+ assert server.app.state.mars_station_stopping+ assert runtime.store._conn is connection+ cleaned.append("society-browser")+ await original_close()++ async def watch():+ watcher_started.set()+ try:+ await asyncio.Event().wait()+ finally:+ cleaned.append("society-watcher")++ monkeypatch.setattr(runtime.browser, "close", check_close_order)+ watcher = runtime.background(watch())+ await watcher_started.wait()+ try:+ await asyncio.wait_for(server.stop(), timeout=3)+ assert runtime.store._conn is None+ with pytest.raises(ValueError, match="no active connection"):+ await connection.execute("SELECT 1")+ assert delivery.done()+ assert watcher.done() and not runtime._watchers+ assert cleaned.count("society-browser") == 1+ assert cleaned.index("society-watcher") < cleaned.index("society-browser")+ assert current_runtime() is None+ assert not runtime._started+ assert server.app.state.mars_station_stopping+ assert {"chat", "pty", "mission-approvals"} <= set(cleaned)+ finally:+ # The red test must not itself leak a non-daemon SQLite worker.+ monkeypatch.setattr(runtime.browser, "close", original_close)+ await runtime.close()++[email protected]("component", ["browser", "coding_supervision"])+async def test_component_failure_still_closes_store_and_finishes_server(+ tmp_path, monkeypatch, component+):+ runtime, server, cleaned, connection, delivery = await start_roster(tmp_path)+ resource = getattr(runtime, component)+ original_close = resource.close++ async def broken_close():+ raise RuntimeError("PRIVATE-COMPONENT-PAYLOAD")++ monkeypatch.setattr(resource, "close", broken_close)+ try:+ with pytest.raises(RuntimeError, match="society_runtime_shutdown_incomplete") as failure:+ await asyncio.wait_for(server.stop(), timeout=3)+ assert "PRIVATE-COMPONENT-PAYLOAD" not in str(failure.value)+ assert runtime.store._conn is None+ with pytest.raises(ValueError, match="no active connection"):+ await connection.execute("SELECT 1")+ assert delivery.done()+ assert current_runtime() is None+ assert {"chat", "pty", "mission-approvals"} <= set(cleaned)+ finally:+ monkeypatch.setattr(resource, "close", original_close)+ await runtime.close()+++async def test_cancelled_browser_cleanup_still_releases_roster_store(tmp_path, monkeypatch):+ runtime, _server, _cleaned, connection, delivery = await start_roster(tmp_path)+ original_close = runtime.browser.close+ closing = asyncio.Event()++ async def stalled_close():+ closing.set()+ await asyncio.Event().wait()++ monkeypatch.setattr(runtime.browser, "close", stalled_close)+ task = asyncio.create_task(runtime.close())+ try:+ await asyncio.wait_for(closing.wait(), timeout=2)+ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await asyncio.wait_for(task, timeout=2)+ assert runtime.store._conn is None+ with pytest.raises(ValueError, match="no active connection"):+ await connection.execute("SELECT 1")+ assert delivery.done()+ assert current_runtime() is None+ finally:+ monkeypatch.setattr(runtime.browser, "close", original_close)+ await runtime.close()+++async def test_roster_poll_during_remaining_server_cleanup_cannot_restart(tmp_path, monkeypatch):+ runtime, server, _cleaned, connection, delivery = await start_roster(tmp_path)+ cleanup_started = asyncio.Event()+ release_cleanup = asyncio.Event()++ async def pending_cleanup():+ cleanup_started.set()+ await release_cleanup.wait()++ monkeypatch.setattr(server, "_stop_marketplace_refresh_scheduler", pending_cleanup)+ stopping = asyncio.create_task(server.stop())+ try:+ await asyncio.wait_for(cleanup_started.wait(), timeout=2)+ assert not stopping.done()+ assert runtime.store._conn is None+ for _ in range(3):+ with pytest.raises(HTTPException) as error:+ await list_agents(Request({"type": "http", "app": server.app}))+ assert error.value.status_code == 503+ assert await runtime.prepare_context() is False+ assert runtime.store._conn is None+ assert runtime._delivery_task is None and delivery.done()+ assert current_runtime() is None+ with pytest.raises(ValueError, match="no active connection"):+ await connection.execute("SELECT 1")+ finally:+ release_cleanup.set()+ await asyncio.wait_for(stopping, timeout=2)+ await runtime.close()++[email protected]("pause_at", ["first-await", "remaining-cleanup"])+async def test_shutdown_fences_empty_owner_before_lazy_roster_factory(+ tmp_path, monkeypatch, pause_at+):+ from jarvis.ui.web import mars_routes++ server, _cleaned = society_shutdown_server(None)+ paused = asyncio.Event()+ release = asyncio.Event()+ factory_calls = []++ def factory():+ factory_calls.append("constructed")+ return SocietyRuntime(tmp_path)++ async def pending_cleanup(*_args):+ paused.set()+ await release.wait()++ server.app.state.society_factory = factory+ if pause_at == "first-await":+ monkeypatch.setattr(mars_routes, "stop_mars_station", pending_cleanup)+ else:+ monkeypatch.setattr(server, "_stop_marketplace_refresh_scheduler", pending_cleanup)+ stopping = asyncio.create_task(server.stop())+ try:+ await asyncio.wait_for(paused.wait(), timeout=2)+ assert server.app.state.society_stopping+ with pytest.raises(HTTPException) as error:+ await list_agents(Request({"type": "http", "app": server.app}))+ assert error.value.status_code == 503+ assert error.value.detail == "society runtime stopped"+ assert factory_calls == []+ assert server.app.state.society is None+ assert list(tmp_path.iterdir()) == []+ finally:+ release.set()+ await asyncio.wait_for(stopping, timeout=2)+ if server.app.state.society is not None:+ await server.app.state.society.close()++[email protected]("existing_owner", [None, object()])+def test_shared_brain_factory_rejects_shutdown_before_owner_lookup(existing_owner):+ server, _cleaned = society_shutdown_server(existing_owner)+ server.app.state.society_stopping = True+ # The guard must run before consulting config or constructing collaborators.+ with pytest.raises(SocietyRuntimeClosed, match="society runtime stopped"):+ server._build_society_runtime()+ assert server.app.state.society is existing_owner+++async def test_close_cancels_and_joins_initial_roster_request(tmp_path, monkeypatch):+ runtime = SocietyRuntime(tmp_path)+ server, _cleaned = society_shutdown_server(runtime)+ seeded = asyncio.Event()+ original_seed = runtime.seed_lead++ async def pending_seed():+ await original_seed()+ seeded.set()+ await asyncio.Event().wait()++ monkeypatch.setattr(runtime, "seed_lead", pending_seed)+ starting = asyncio.create_task(list_agents(Request({"type": "http", "app": server.app})))+ try:+ await asyncio.wait_for(seeded.wait(), timeout=2)+ connection = runtime.store._conn+ assert connection is not None+ await asyncio.wait_for(server.stop(), timeout=3)+ assert starting.done() and starting.cancelled()+ assert runtime._starting_task is None+ assert runtime.store._conn is None+ assert runtime._delivery_task is None+ assert current_runtime() is None+ with pytest.raises(ValueError, match="no active connection"):+ await connection.execute("SELECT 1")+ with pytest.raises(HTTPException) as error:+ await list_agents(Request({"type": "http", "app": server.app}))+ assert error.value.status_code == 503+ finally:+ starting.cancel()+ await asyncio.gather(starting, return_exceptions=True)+ await runtime.close()+++async def test_cancel_initial_connect_releases_real_sqlite_worker(tmp_path, monkeypatch):+ import sqlite3++ runtime = SocietyRuntime(tmp_path)+ server, _cleaned = society_shutdown_server(runtime)+ original_connect = sqlite3.connect+ connecting = asyncio.Event()+ release_connect = threading.Event()+ worker_threads = []+ loop = asyncio.get_running_loop()++ def slow_connect(*args, **kwargs):+ worker_threads.append(threading.current_thread())+ loop.call_soon_threadsafe(connecting.set)+ assert release_connect.wait(timeout=5)+ return original_connect(*args, **kwargs)++ monkeypatch.setattr(sqlite3, "connect", slow_connect)+ starting = asyncio.create_task(runtime.ensure_started())+ try:+ await asyncio.wait_for(connecting.wait(), timeout=2)+ assert runtime.store._conn is None+ await asyncio.wait_for(server.stop(), timeout=3)+ assert starting.done() and starting.cancelled()+ release_connect.set()+ for worker in worker_threads:+ await asyncio.to_thread(worker.join, 2)+ assert not worker.is_alive()+ assert runtime.store._conn is None+ assert current_runtime() is None+ finally:+ release_connect.set()+ await asyncio.gather(starting, return_exceptions=True)+ await runtime.close()+++async def test_slow_startup_keeps_owner_until_it_can_release_store(tmp_path, monkeypatch):+ from jarvis.society import runtime as runtime_module++ runtime = SocietyRuntime(tmp_path)+ seeded = asyncio.Event()+ cancelled = asyncio.Event()+ release = asyncio.Event()+ original_seed = runtime.seed_lead++ async def reluctant_seed():+ await original_seed()+ seeded.set()+ try:+ await release.wait()+ except asyncio.CancelledError:+ cancelled.set()+ await release.wait()++ monkeypatch.setattr(runtime_module, "_CLOSE_TASK_TIMEOUT_S", 0.02)+ monkeypatch.setattr(runtime, "seed_lead", reluctant_seed)+ starting = asyncio.create_task(runtime.ensure_started())+ try:+ await asyncio.wait_for(seeded.wait(), timeout=2)+ with pytest.raises(TimeoutError, match="society task shutdown incomplete"):+ await runtime.close()+ assert cancelled.is_set()+ assert runtime._starting_task is starting and not starting.done()+ assert runtime.store._conn is None+ release.set()+ with pytest.raises(runtime_module.SocietyRuntimeClosed):+ await starting+ assert runtime._starting_task is None+ assert runtime.store._conn is None+ assert runtime._delivery_task is None+ assert current_runtime() is None+ finally:+ release.set()+ await asyncio.gather(starting, return_exceptions=True)+ await runtime.close()+++def test_roster_process_exits_after_real_server_stop(tmp_path):+ script = """+import asyncio+import sys+from pathlib import Path+from fastapi import Request+from jarvis.society.runtime import SocietyRuntime+from jarvis.ui.web.society_routes import list_agents+from tests.fakes.fake_society_shutdown import society_shutdown_server++async def main():+ runtime = SocietyRuntime(Path(sys.argv[1]))+ server, _ = society_shutdown_server(runtime)+ await list_agents(Request({'type': 'http', 'app': server.app}))+ await server.stop()+ print('SOCIETY_SERVER_STOP_RETURNED', flush=True)++asyncio.run(main())+"""+ result = subprocess.run(+ [sys.executable, "-c", script, str(tmp_path)],+ cwd=Path(__file__).resolve().parents[4],+ env={**os.environ, "PYTHONIOENCODING": "utf-8"},+ capture_output=True,+ text=True,+ encoding="utf-8",+ timeout=15,+ creationflags=NO_WINDOW_CREATIONFLAGS,+ check=False,+ )+ assert result.returncode == 0, result.stderr+ assert "SOCIETY_SERVER_STOP_RETURNED" in result.stdoutdiff --git a/tests/unit/web/test_voice_mode_route.py b/tests/unit/web/test_voice_mode_route.pyindex 7668d5d09a..890398cdd5 100644--- a/tests/unit/web/test_voice_mode_route.py+++ b/tests/unit/web/test_voice_mode_route.py@@ -66,12 +66,12 @@ def test_get_voice_mode(monkeypatch):assert body["requires_webrtc_offer"] is Falseassert body["transport_offer_ready"] is Noneassert body["transport_offer_detail"] is None- assert body["active_provider"] == "openai-realtime"+ assert body["active_provider"] == "openai-live"# Sidebar display fields: registry label + the catalog-default model (no# pin configured in this app fixture).- assert body["active_provider_label"] == "OpenAI Realtime"- assert body["active_model"] == "gpt-realtime"- assert body["active_model_label"] == "GPT Realtime (default)"+ assert body["active_provider_label"] == "OpenAI GPT-Live"+ assert body["active_model"] == "gpt-live-1"+ assert body["active_model_label"] == "GPT-Live 1"assert body["session_active"] is Falseassert body["active_session_mode"] is Nonediff --git a/ui/orb/bus_bridge.py b/ui/orb/bus_bridge.pyindex f0cb077625..40a4ba9420 100644--- a/ui/orb/bus_bridge.py+++ b/ui/orb/bus_bridge.py@@ -171,7 +171,7 @@ _USER_SIDE_BUBBLE_STATES = frozenset(# it stays hidden until a genuine new ``VoiceSessionStarted`` (the user calls# "Hey Jarvis" again). See ``_on_session_ended`` / ``_on_session_started`` and# the guard at the top of ``_on_state``.-_ACTIVE_VOICE_STATES = frozenset({"LISTENING", "THINKING", "SPEAKING"})+_ACTIVE_VOICE_STATES = frozenset({"CONNECTING", "LISTENING", "THINKING", "SPEAKING"})# German public-broadcaster subtitle-credit boilerplate that German-language# STT sometimes hallucinates onto silence/noise (e.g. "Untertitelung des ZDF@@ -1643,7 +1643,14 @@ class OrbBusBridge:the same normalized value through it and retain the recency guard thatsuppresses simultaneous silent-mic updates."""- self._last_tts_level_t = time.monotonic()+ from jarvis.audio import level_tap++ # reset_playing publishes an explicit zero after clearing the audible+ # window. Give the microphone back immediately on that edge; silence+ # inside an ongoing utterance still retains the normal recency guard.+ self._last_tts_level_t = (+ time.monotonic() if level > 0.0 or level_tap.playback_active() else 0.0+ )try:self._orb.set_level(level)except Exception: # noqa: BLE001@@ -1672,7 +1679,7 @@ class OrbBusBridge:"PAUSED",}if (- self._last_state != "LISTENING"+ self._last_state not in {"LISTENING", "CONNECTING"}and not candidate_listeningand not self._dictation_active):diff --git a/ui/orb/overlay.py b/ui/orb/overlay.pyindex 77d429096a..5229ae612a 100644--- a/ui/orb/overlay.py+++ b/ui/orb/overlay.py@@ -2025,6 +2025,9 @@ class OrbOverlay:if "pytest" in sys.modules and not os.environ.get("JARVIS_GUI_TESTS"):self._started.set()return+ from jarvis.ui.tk_runtime import prepare_tk_runtime++ prepare_tk_runtime()# DPI awareness MUST be set before Win32 GetWindowRect calls, else# taskbar coords come back DPI-virtualised and the mascot ends up# misplaced on 125%/150% scaled displays.diff --git a/uv.lock b/uv.lockindex 2182dc2152..461e4fff62 100644--- a/uv.lock+++ b/uv.lock@@ -2741,7 +2741,7 @@ wheels = [[[package]]name = "personal-jarvis"-version = "2.1.0"+version = "2.2.1"source = { editable = "." }dependencies = [{ name = "aiofiles" },@@ -2998,7 +2998,7 @@ requires-dist = [{ name = "pyobjc-framework-avfoundation", marker = "sys_platform == 'darwin' and extra == 'desktop-macos'", specifier = ">=10" },{ name = "pyobjc-framework-quartz", marker = "sys_platform == 'darwin' and extra == 'desktop-macos'", specifier = ">=10" },{ name = "pyobjc-framework-screencapturekit", marker = "sys_platform == 'darwin' and extra == 'desktop-macos'", specifier = ">=10" },- { name = "pypdf", specifier = ">=6.15" },+ { name = "pypdf", specifier = ">=6.16.1" },{ name = "pyside6-essentials", marker = "(platform_machine != 'aarch64' and extra == 'desktop') or (sys_platform != 'linux' and extra == 'desktop')", specifier = ">=6.7" },{ name = "pystray", marker = "extra == 'desktop'", specifier = ">=0.19" },{ name = "pytest", marker = "extra == 'dev'", specifier = ">=8.3" },@@ -3938,11 +3938,11 @@ wheels = [[[package]]name = "pypdf"-version = "6.15.0"+version = "6.19.0"source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/17/17/ee75a92718ec7212de831e71454d702225aa5e474a805cce169806044453/pypdf-6.15.0.tar.gz", hash = "sha256:d39c4d955a76409284a905e2d65b40076d77ab76129e0faaeeb6612403ecfc79", size = 6993794, upload-time = "2026-08-06T13:06:49.929Z" }+sdist = { url = "https://files.pythonhosted.org/packages/1f/ac/63d71aaedb59acbcdef491e6ca6469165e3771c9c74358204818fd9bc5a6/pypdf-6.19.0.tar.gz", hash = "sha256:bbc43aca292369ccc6cbc8a921991ecf2538a3587ab5a116eff06c321d647155", size = 7033266, upload-time = "2026-09-16T09:32:05.946Z" }wheels = [- { url = "https://files.pythonhosted.org/packages/af/72/ce3067ac31e214a66388159f8462ddb8c13dd00170f24d555a1f1ae8ee91/pypdf-6.15.0-py3-none-any.whl", hash = "sha256:14e001d6504822cb1ca9c7ed9a69bccb320f59b320730f55af804361abe4d5ee", size = 378123, upload-time = "2026-08-06T13:06:47.709Z" },+ { url = "https://files.pythonhosted.org/packages/3c/2c/c43c03eaf630435f023f1dc61ec4a4a78951ad5530a62c71cc89bde307b7/pypdf-6.19.0-py3-none-any.whl", hash = "sha256:7e5d6e730e7dae87d560a2cee218b852f6498c8be61966f3cd02ead971e48d14", size = 395480, upload-time = "2026-09-16T09:32:04.087Z" },][[package]]