Skip to content

Your lightweight open-source personal agent.

feat(update): integrate managed installs and recoverable in-app updates (#6168)

Xubin Renfbb61a373f47
diff --git a/.gitattributes b/.gitattributes
index 9da244d8c..0ad04d9a9 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -1,2 +1,5 @@
# Ensure shell scripts always use LF line endings (Docker/Linux compat)
*.sh text eol=lf
+
+# The public Sigstore fixture is signed over exact bytes, including newlines.
+tests/fixtures/sigstore/bundle_v3.txt -text
diff --git a/.github/release-signing-requirements.in b/.github/release-signing-requirements.in
new file mode 100644
index 000000000..b1cfaa596
--- /dev/null
+++ b/.github/release-signing-requirements.in
@@ -0,0 +1,3 @@
+# This isolated signing job never installs nanobot or candidate dependencies.
+sigstore==4.5.0
+packaging==26.3
diff --git a/.github/release-signing-requirements.txt b/.github/release-signing-requirements.txt
new file mode 100644
index 000000000..05bf3922d
--- /dev/null
+++ b/.github/release-signing-requirements.txt
@@ -0,0 +1,615 @@
+annotated-types==0.8.0 \
+ --hash=sha256:13b2beaad985e05e2d6407ee4c4f35590b11f8d693a258a561055cac8f64cab7 \
+ --hash=sha256:f072f4d804ea359e4eaf198b1af7a8b0943881a87f31bb764f8bf219bb9419e0
+ # via pydantic
+certifi==2026.7.22 \
+ --hash=sha256:62f22742b58a1a33014a2b6b706588a8d7e2a88ae7bd1a6ebe8c992928483775 \
+ --hash=sha256:741e2c3b351ddf169a738da9f2c048608ff7f2c5cc02f1ebc6b118bb090d5d55
+ # via requests
+cffi==2.1.1 \
+ --hash=sha256:046bfc24911b37851ee1b51aab8bffe713d89c68c6a057b09484ce9fd5f69b4e \
+ --hash=sha256:06c72bb76605a4b0cd0aad6930b69d4baf7dd5d806cfc409b824191099700e66 \
+ --hash=sha256:0beceaabe56af686895136a2de78db54ecd8e4046b236b8fd6d6cb61389e9bf2 \
+ --hash=sha256:154852545011f779917b11c78db2358d095da62a9a172b78ad0a583ee5adc0d0 \
+ --hash=sha256:194cffa889098ced9976c3fc6340305e43f6303657d298da55366907c05c22d6 \
+ --hash=sha256:19ee6127ee34de7d83ce3d371ebc5ed91addbdcc39f9ab15ce4eb35a4e534971 \
+ --hash=sha256:1a18a57b58cfb21fc28d72e876acf10eaed67a1ed96226f92af4df681d571c4c \
+ --hash=sha256:1aa5645c30469b09530c4ebca77ebf8f17618293c58f8549cb1a543a50236e7d \
+ --hash=sha256:1dea0e4d7d4f11f619fe8c1d76caf49e24405b4b5743c0e3be16a500ecd930c9 \
+ --hash=sha256:208f941bb9d18e768138677f0a6d2ce01f590df56043dda1df1535ac57c88517 \
+ --hash=sha256:210019b6c7cf07f081b4c54635c8cf744377001350e29cc0f81c4377b4797735 \
+ --hash=sha256:246fa40ce8645a614ff682e0b70f37134e460eaf93a775e0cbe3cca585a67a80 \
+ --hash=sha256:25792eac27877609e7bb06d42ff88278a6624fff2ba9bbb523c09616b117e80f \
+ --hash=sha256:27350daa11d4f10c540e6e89dada4c54feb7256ad03e9a4dc075ebad7ba360d1 \
+ --hash=sha256:28907ab9bfb6aa13184cfc17c6b8e1023c5ab6fd7076d8c20a35e59fe04f8f29 \
+ --hash=sha256:2ae64be792b8966f2c69538199728b290e34726562896df1e5dc8ffd8d8188e8 \
+ --hash=sha256:31348097ff5bbe827ccc41795d4dd099d9f0625e7def00ee653c137a490c2a6c \
+ --hash=sha256:3143d81e29e1e20a9ce10901ec369012947876596f75a222235965f2b7ae832e \
+ --hash=sha256:3222ba5d678f80a030e6afbcc33dc1ae5cb45facabb61cee2c7016b8432fde48 \
+ --hash=sha256:3311ed60d36f83378794e1009ac6258bafbf81f7888b4caa7b35a521e3f95813 \
+ --hash=sha256:334644fbac4eff73d985a17a91226df55d0f394160c4cfb880e084c8f7161cac \
+ --hash=sha256:34e261f78cb6ceaaa36f42f2613f4380d94d9c759a9c73c769ee6e0247364632 \
+ --hash=sha256:363e05fa78e15116c3c32c210ee36884fd6b9afa6d440e47112c3bd511d64cb6 \
+ --hash=sha256:398aff33cee2767e3e781d2554c54bd0dff386bb437581e0d8011fde1a942ec1 \
+ --hash=sha256:3d22a20b1fb1632cc72c22f95f7b0d2961c3e1c235f245ba4c606c4771035659 \
+ --hash=sha256:42a494cee34437f05546455144f2b5d9ac09b1face62bcfce597d2e521066688 \
+ --hash=sha256:42e2f76b9455f5a9a844f770bf3e200ed3da0e15f5df3db9c31fe80b04b3d004 \
+ --hash=sha256:42f6930c31dc7f50732c9ae793c2786c7b6b044195967bbdde40bb9be81c4cc0 \
+ --hash=sha256:456a61fa52d579ebf9df2e9552ead5129855dbaff6c1e5a9b1bc408809bdc062 \
+ --hash=sha256:471cee653ae88de62096552e6d24ccb4a5adb8c8c9f10b5054d0122c15bf2779 \
+ --hash=sha256:49cbc70e6542d4ccccb936558d1064a8012541e78f821f955cff24e357776c94 \
+ --hash=sha256:4a7c934f7360e8cd64fe9efadcbd10c7c6364f531e432b9a4bf5ccbc9e0e8b50 \
+ --hash=sha256:4be96343e422f2dfcd12ab5c9f5aebe03f82f737c6bffeca6830b3875cb44aab \
+ --hash=sha256:4f42141fc14250de6dde5ee7ea4432be017252d91f19c5ad043c084cea629cac \
+ --hash=sha256:507a24c282e0f42f8ed737cf048572cbf580468da5555764a8331735e9c736b6 \
+ --hash=sha256:51b31d1c98274844cfd7838ce00bfc27c7423a4dc00fc0772fc3331c2cc90676 \
+ --hash=sha256:58acb8ab8e295e6c5ea12f888cbb13cf21511ef2a3303a23f4325c29d17fe5c1 \
+ --hash=sha256:5a59cc1c4442bc3d5c703bf720b51138d0bfc173618807c9ee2490a7541dd3d9 \
+ --hash=sha256:5bb4e7ea95dcd6a014a6fef62e62467d67d8e582326443f3d68e71d6320a9fcf \
+ --hash=sha256:5c58fe613dc5e5336357eff555824a314d8e43282600435c8d1cb6a7a2fedd13 \
+ --hash=sha256:5e7cecbaadb83884793e05828cee59b210b24583b9c7425d0ba6a754fe22eb4e \
+ --hash=sha256:616f097f2fe415bc92a247f02e11f634e1f9e9a83d327e3c915c15089c87869e \
+ --hash=sha256:63bbfd5ded17c4840ac07cd8f1c21ba9d9708141f840b324f422f41b207e3973 \
+ --hash=sha256:64faea20f4e2613363a1a9b9c7dd73058f3ecd00133a511e72ad7c511658f527 \
+ --hash=sha256:661c298b4821edebead0c91edd2b00374d67ad7c5a1f7a91d4442633b79d6a72 \
+ --hash=sha256:68e62fe11f30d5ca8289242866f0a5291402d8529ca2178ab8afc5c9694ae890 \
+ --hash=sha256:6a8dddef476fab96d066d578fc88526767b836ab5ab21754e1d5bf3879c31c7c \
+ --hash=sha256:6e192623c49c94421616a5778fba35cf0d5a8d000650c1967ef4448ee5cdd990 \
+ --hash=sha256:7225e4514edb64eb6740324353e0da0711954fd8d7da4576755b1c6e09b697cd \
+ --hash=sha256:75f80557d1389eddbd0de2681f6a390a0c5338c31ddaa821381c203fc3fd50d9 \
+ --hash=sha256:770de9db11e84213beec501cfcaa013b019820ca881e03344dea5844f7876d94 \
+ --hash=sha256:7750c6449dff7864bb9bb27ddfb0267756189201a3afc911d82b3caacd70dfc3 \
+ --hash=sha256:7bde5e4cc5c10140859842b9d383af292b22639a4dffb725314baf45968cef80 \
+ --hash=sha256:7ce713ace7c0e4520535b42b77eaa742c16dab813978064913e5a3cf82973b41 \
+ --hash=sha256:7da0c5eff80f0197f3b3d1232ec5a682a9325f4ae9016a78f5f5ca35f9ced1f5 \
+ --hash=sha256:7dbb61fe3a7699468030f71bbe5f8a0e326a151daa91beb11a6fc1f980c55e1c \
+ --hash=sha256:811bd1e21d32de12efca32393a0ab3f5133b54fce9bd44b8bd77ab07da14bf6a \
+ --hash=sha256:8ef53b2de9bcb9197d31854256575d59dbac0cba72ac627bb291ef5eceb74be4 \
+ --hash=sha256:937c0052c05a31ca1daf18de3158eed4dbfcb9cc107adbea227728d647be701e \
+ --hash=sha256:9d2055050ea716bd38b7f7f1579c275386646b4894c155a3e2f3cd62ed41b7c6 \
+ --hash=sha256:9f8d177621de5cb38ee3e731eda45d421db093ec0739f46a5594babda7987a98 \
+ --hash=sha256:a2d7755bef5a12ed488f4ef1f1b69ee9191d7396083b755a5d2295f6edb4768b \
+ --hash=sha256:a48d62ab9d6f4f98c983223a547af44be6ca3691074c31cecced6facd3ba2dc1 \
+ --hash=sha256:a4f00aa42f75d6e4595e8866e748cc1705adc0cddfeb2ca86d0d03993d63ba03 \
+ --hash=sha256:a6e721d4b0e45d5b65e87534470e67b18dcd092c83f68fba09f152b9cbc061af \
+ --hash=sha256:a730a083190634c65cca36ba5f489531576ebd79bcd5c8e172130f6453127231 \
+ --hash=sha256:a931079504ecc49efed7744c476a5c343a92fabf66dec2db95edb1b2fdc770e2 \
+ --hash=sha256:aa9511c62d14da7aacc9b4bf51f3f697a621e83b2d6919008243c3aad168eea3 \
+ --hash=sha256:ab36d55f9ed2d067327667c2fea18dda018eb628dd6347aa01dda6cf1f5d3836 \
+ --hash=sha256:ad2c86c495b899d862ea0f4b42891b8713a3bd45dd4105c7fd51c2a72f39f3a5 \
+ --hash=sha256:aeae0e330c9f6acd681f647d46cefd30c29f93e3392882e792e82080c9691399 \
+ --hash=sha256:b0431303acaea1089ad4b3e9ce4e6518193def1118d4073ca848635ee4ea2e96 \
+ --hash=sha256:b5bdfd1c873d4e093aabc0ca84c4ca6dbc4f752afb5c86f146d9742580c9da2e \
+ --hash=sha256:baed1e86cc735622097354b9d1281406caf42ff42a886d29faa8e8d1630333be \
+ --hash=sha256:c1453022f490d2459a11819d83ad1d586e9ff65a12ac3e705ffebd46d3685dcf \
+ --hash=sha256:c26608d2222fb1e94487e4a387d85f13eb55d5ed725cb25a0c589ac4ee60e7bc \
+ --hash=sha256:c7659f22557c5a0bc4855cd635f55edec690cc008a40768527762cb9fb263455 \
+ --hash=sha256:c8c69575568085ba0b1b10c0249d779a214aea6f6522e949a0fc9fb0fcb449d0 \
+ --hash=sha256:c8d2c9fd1f2d16f780d15127abb050d13d1a76c03a4bd87d7e4980e45e511e12 \
+ --hash=sha256:ca82be1a1d406ecfe1d25dc16cb33488e5a16bf4438c9fb590484ea29d92478b \
+ --hash=sha256:cc572dace3f60ef98d7b12ff411d20f5362feb31a0439eab0085bbfd349982d7 \
+ --hash=sha256:d18e5ac0f2f03f4f518d3e23db0f0cad7faa1da8620e9c09461d443bbf6e6692 \
+ --hash=sha256:d28630f5854ab07ab1fd4aba756de52326c82e6be15d414b12793f1975048b54 \
+ --hash=sha256:d9c275eaacd24aa73f94ffd6de08fc3f932424d8b6c376f4bed7cde376fe7bc3 \
+ --hash=sha256:da0e573f9f97159390c89d9f1a9e41908b66d408cc5b58d08cf3847d844c531b \
+ --hash=sha256:dd31f52ea1086513bb9df30f8fcee9b8918323ae067a3d5b78bc826a000712be \
+ --hash=sha256:dddad92b554513a31f272570678ba307fb9f618f05e3d4a5eacafff9eae03e1d \
+ --hash=sha256:df423d40ee8654634421812bc3b196da3f9bd7d32929da813f8394c4348a5358 \
+ --hash=sha256:df913725b79db7bcf03448f36b7bf8815363417d5b58deecf9305e3e30f0f21a \
+ --hash=sha256:e0bcb7e0f677f543555d2adff3bf19c05f66cdb4796e5ff602442ab2fe3c4ef7 \
+ --hash=sha256:e2d65b31f36619cda3999b78b2aa9632e76b78448e7a56fc4240824200e7c4fc \
+ --hash=sha256:e6e8cff14d6fb0be70a09c0bdc58096f501952d04624ebf867e0e56da2df8960 \
+ --hash=sha256:f16c709686a78c727bbbf059f92b0bf41c6fc60deec706d2dc19f529175a6125 \
+ --hash=sha256:f24fb43132a4c6b4cb4eb029492919b2db645be6808d738f244fd146c03c32cb \
+ --hash=sha256:f53e442b08449d42821fa4a4fba000095af9f62742a500f978a9f557ec44339a \
+ --hash=sha256:f5cfbc5fe74540d335175b656c725d74d90e3730c626d92575eea35029d9afaa \
+ --hash=sha256:f81b3b8f3d4e343550fa4baa0e479bba9f2d29ce9c2e9b51d1ce1718d7442fcf \
+ --hash=sha256:f8ec5e643a9a937f64e1999eb9f75d072263751912dc5cd06d3c85f8f44be7c3 \
+ --hash=sha256:fb92203a88b3d3053034db775110081c49d28be6551923805e039924093761e4 \
+ --hash=sha256:fcd22650c908d7b7da162bbfaab594a1227a15d1643a98c68b122ac642fa2264
+ # via cryptography
+charset-normalizer==3.5.2 \
+ --hash=sha256:01077390b03f7988f11d700a2194e69b119741a86b1a638b1db88891e3eced8e \
+ --hash=sha256:01b0c0d2262a9e28e8484a278c7e1b5d650e3ac8cf2683d2967e25899f208bdf \
+ --hash=sha256:04851f73ae72b8413dddadb16a49dfee95263553741fd42d546f7d66907e6be5 \
+ --hash=sha256:0521c5665880b33d603717defa76c094048900010897909952397feb3039da56 \
+ --hash=sha256:0774bf9bf620249fee3e0b8b9fd3065de213be30f3aa94ce2494b3b638949e26 \
+ --hash=sha256:0891b9d3903c5571c03771ca669a4b0ec5618ca722a5c957d3d29cd4e5062848 \
+ --hash=sha256:0c951d5e6dd9c2ff60609476752bee49da4206adde960ebc247766937f72e718 \
+ --hash=sha256:0fed1d06615f022ee3b13caf5e8b180cfea32bb2c5aded8a9d44277afc040f93 \
+ --hash=sha256:114e4d0c92d618409ed82a99e22b5c5e768fe995f2973f78265f4524f49d4640 \
+ --hash=sha256:11912e4bb14baae7c5d8791aa55ba0a3a03ec6729073307b0f57270abaa713d3 \
+ --hash=sha256:11a4d68a6ecda3292cb1e50239e111543ba5d709bb62a6b4ea1afcfa729d8875 \
+ --hash=sha256:124fbf1a8ff966d87ae05bb8bd45a71f966055ed8bba320d0c7cf450bc5f4d0e \
+ --hash=sha256:1461ac396c4fdb983a675f20aa555624f0ee18ac83d832b9244ffff3d8055275 \
+ --hash=sha256:1503bccbeb36d5527790c3930327704c39af22de3112f1b1666a9f3ce15ee204 \
+ --hash=sha256:15bb4005af6320d259dc7593ca84a38d7fe06a421dbcf7b910ae23979101e787 \
+ --hash=sha256:15c44f7edfd477b06f517a5cc317fc1707edb9de2c865f43d4b6513907473234 \
+ --hash=sha256:16fa0eccf81304b79c5cd87f9271c3b85dd9dd99245e4422ae9c0dd45e0f99d3 \
+ --hash=sha256:183b88127acdb4fabe59d951ab424faf1af7b63cdbb5f776186c1ea2ffcaed98 \
+ --hash=sha256:195c26fb65950f8fce54e26349852b7bdd7c5f120aeefbcc440b8a20faaed4a3 \
+ --hash=sha256:1afb975bd5d68d5ce9f6b6d44fdf2f7e34b895a35e95708a7a91b20a3b51d187 \
+ --hash=sha256:1b4cbc7c3491ccb4aa17fcd8165649d01cf39f76de1696da8631b5f71b85401d \
+ --hash=sha256:1bc0baf5ef96b6ede57d47f4b8fe4d9d84019c3bfcbeb20a41edc6a6ee341f1f \
+ --hash=sha256:1c50fe28bbc2ced33386f298650d91218076c05420e6cbd790b913adc41659e7 \
+ --hash=sha256:1db38f4c5496827c1a501846d64d14c3b80c7e6714e406cd7dc36a9899fa1011 \
+ --hash=sha256:211d5a3eb6af8f513b8d4ca19a8c1b7accab1b5f0d3175f9826b03c1a920dc1f \
+ --hash=sha256:23851fb4e1b85ed3f6c2a27b777cdfe2e19fb5b38429a8faf38c7542b7665869 \
+ --hash=sha256:254eb48b9fa5ee9898a3c445825a1f340fe53712a098904b39b0bddba8ea3cb1 \
+ --hash=sha256:2625388c6c754520c37abaf3b41eb34d1cc4a373f457898f08606c8e362b891d \
+ --hash=sha256:281cb91036248400f4cc957495cccd44c275c2e0c5854f7e45ac5cf7dc193847 \
+ --hash=sha256:28a15fdad492a99b6eccfaaed66ef3f74050680545ea61ec8b2f4c538f1f1320 \
+ --hash=sha256:28b4f0d66fb834ff90f28209ac7bce77868c45d8c93e26f906709d9b7c2e1af9 \
+ --hash=sha256:2a925889534b3748302dae5dead07cc13480de1dac3aea80a941b729b471ef93 \
+ --hash=sha256:2b7b3bbfb4fe8ef40600792d762fbaa9057559f9d3fad209525b7a22b99e91fd \
+ --hash=sha256:2c9ad19a6cfcd5ea5c0d41161d22f9df1dcc277e9bef2751391334546a314c00 \
+ --hash=sha256:2cc961b171b3f3440f410489ab3573e86aea8736134ebbb40ea1338b7f0831bc \
+ --hash=sha256:2ce45c6627b22c47e390bc91a41c3d13032192e699fa0bea96e9671b373d69b0 \
+ --hash=sha256:2e06a3a98f916dd41d27f3105e02e7a40181c98c94b9158733d03a6f80506c09 \
+ --hash=sha256:304d5463e65a35d7bb0850550e0780395395f6fcf452f04db7d5ca7cecc425ac \
+ --hash=sha256:304d8e4d493af723536393eee0c689eb7813f4a474c8b479dee63f1fdd98f621 \
+ --hash=sha256:30fcd120b732aa79317f08dee04d7de0847822e4cf7ee0e9f445bb958832252c \
+ --hash=sha256:31f3930700408d211f13378ccbe1c40845d8da54bd0681fac3a9b5aae81c7aa8 \
+ --hash=sha256:34276fd796040bf0993ab33a369aa572e6979c7aab225a88893667ad8eac8f7a \
+ --hash=sha256:355ad8011081dec5412240c087a9a0c9d4d5039f3ed11a3f13e18c2b29b56c51 \
+ --hash=sha256:38a873987f3be698494da8b2e3085e29da02da7b633dce73e79c699a113d7bf0 \
+ --hash=sha256:39de2a259fc954455c57274dc94c79d5842774e1247a016aff30bc0efed0f4ef \
+ --hash=sha256:3d14b50de6bf4d0edf857a9386836846f982b8f524e188e2e68b96d702bcf4aa \
+ --hash=sha256:3d21b8b13c7592db2ac5e544a6d83187b995257472b0c9e8351b6d507ae37ed6 \
+ --hash=sha256:3d31298449090ab8d47b7b1b2a555ff73cac7ed438a08b7ac160980c7ebed649 \
+ --hash=sha256:3ddacd27458c45bdacd6bd6db644bfb730efbf9e830310186e3045c9c5be8fb2 \
+ --hash=sha256:3df041de8887954562c9b261cba85ca0e9ded74048daf125f45edcfaa4832229 \
+ --hash=sha256:40ab6bffa02ae10a0581e6c198be7d2d8ca5c2a0c64e4ed3465d766df457573e \
+ --hash=sha256:4275811936e2f06feff5e598fb42a1b7ae852da8e39605211892b56b81a34efd \
+ --hash=sha256:443eae2bf318abeaf6f15d785138f71fd6de770e99a92158b8b814265e079115 \
+ --hash=sha256:447441e76ec720b15e64418d32e092297340387053047c7c694f579efb0ee1d9 \
+ --hash=sha256:4495c5002a7b28557e7e222e77e0b661183e432b7d6d2e788101e3f240e05b8c \
+ --hash=sha256:44bd4fbb29dfbeba60e7d2bd000c59e4b21ddb3cc53912b14048d37092706d7c \
+ --hash=sha256:4685902cf26edf013ed7a3da0f426ebba7a00ebb9541386d835afbf002c11cab \
+ --hash=sha256:498dc3188ca05a68231ac3fdbfc7f57eb67e1343c30e0fea17f8218c1599b253 \
+ --hash=sha256:4c2b5031f63e331e3839b40aed2dd6f191e9c07edbde303e7876846ea1946995 \
+ --hash=sha256:4d48f2d08b9de5864e2c8744d4461b862fb149a18274abc8b698c45975573438 \
+ --hash=sha256:4f87960d57feabfb618e4e0af6e7371645fa26a277860739d6e5d6e0012c92f0 \
+ --hash=sha256:50e3adfb96fc189eb27b1cf62d3b598b89b4bb0420d93a3d3e42e137409011be \
+ --hash=sha256:51cf45226a9b588d0d2b4880c62d686934b63ab0bd79ca23ab0e9762eb27441b \
+ --hash=sha256:52aa6992700996af31f375de0c6bacd402b0097fe40b53c426b9f51a90ebabc7 \
+ --hash=sha256:55ea99acb17b9325618de155a0cd6a2e8f5d10be008113e1d433bbb58db543b2 \
+ --hash=sha256:56bc200a365efb37383b7852e4cc5898d3b2da5987289b543956cf8cad71018a \
+ --hash=sha256:588461c2e8384d309bd63e5826019b6977bc66d629b99ac8737bb795d7b2cb5a \
+ --hash=sha256:58ca3755ee7ff7f59b57789ec9833c9de9ea275405cdd240eda1f193112e398a \
+ --hash=sha256:58f361dcbab699cf8f42db3f47c8e7fd1036f138c23a5d08de9fde5f425a730c \
+ --hash=sha256:598a11a2c7ebaa5334bf698bf29568c9c390abac6a154d8170fedecd1cea38c5 \
+ --hash=sha256:59f63901b0031c3136cf64704dcb21de0bbae62ce2c9529bc39d27665463de37 \
+ --hash=sha256:5cde776b7cc66e4f6c99612cea4aa7269aa65863f7a15841b2c264f103822f4e \
+ --hash=sha256:5e2b6b57e9733d39f0c9fd3185efa6b8e29652c4cd8fe94180272cf6ed9a78c4 \
+ --hash=sha256:5fb29fb8cd1a46c27a1bf9613ad5ec2599310d46b4025d9556404a6b6a292800 \
+ --hash=sha256:6045373d5a89a5ec71afde535db987ca28e76dfa276c2d4c818265b375d4b055 \
+ --hash=sha256:619799369eeef6366ed3e8755a5670f4f2f0fb6b30a0fd7264dc0fdc2357058e \
+ --hash=sha256:62588a277bfb59def052abd940703fa35107152bf479781a878617d60faf8fb5 \
+ --hash=sha256:62603db9a7caa0802eaa28c1c46fecd7b3a263a774069c24c3c28c302448721c \
+ --hash=sha256:65cd72beeeca9d3aaea1201e5923859f308f952f9c71de93f06063c79f0f7a3b \
+ --hash=sha256:68eb192d85ab8e5f6ec69c2bc6ac0179fbf04a5ac1569d12fbef74883fe102d0 \
+ --hash=sha256:6bd128f206a7752ae1f2ab6c61bf8a24ba28913a10df8b14c2637b973ff97a80 \
+ --hash=sha256:6be488a102b8cf28d0391d8c4ba7748938ae28b78ad901f8585520fca33ead1a \
+ --hash=sha256:7218e8f32b0956cfcd048fd42d9d5779809745ca1d86113ca56f66e7ae1549c4 \
+ --hash=sha256:7441d755b7ab94f8d4eb3e43ec05482d760842fd263d003a99102d742cd835e2 \
+ --hash=sha256:749e97e1b32313717a565abbe321bc2190bc8b35f1a67e4cdbc7c56c8d8ffe58 \
+ --hash=sha256:75a3ceed0724d625d64b86ca20aba182e4df462e04c2414fc941c0f523f06aac \
+ --hash=sha256:780fbe7cab297b81dad9fb8dc5eb003c0468ffb0d9e5f65068c53a34661a96bc \
+ --hash=sha256:78456a747de8dc58360ffa581f30a002baf5aa28cb262536545e91f113ed7639 \
+ --hash=sha256:7967d08cf06dee78443b874f98c98036f624f3a4e73e11f9f64f5be4d25393cf \
+ --hash=sha256:7a881931aa470808df94a8c380eed2bbbc76cd9dc622310f99665658c821eb6d \
+ --hash=sha256:7dcd882da75ef9adf94903b1e3b9419e8aa8fb4c7396822b834b9ef7fb96954f \
+ --hash=sha256:7e841fb9010836c992c9f12fcbd43a831de93a5f726fc1ccd8ca1d0268c5014c \
+ --hash=sha256:7fdde2c9fd9e3eca40631e024664cf2584272cc8f96308cbe5fdfc930f51d8bc \
+ --hash=sha256:8024d00c3faf3fc0c16e07a69f4405e8eac7cc0ab15f65fe6cf43827c4cf72b4 \
+ --hash=sha256:80d02b6f04e92601a081dd97b23d3128033098bff5d35d392ddcc0476ea11253 \
+ --hash=sha256:838dcc90063569a0448120554591a1d6c4a4ffe11babf048908793154ab86ade \
+ --hash=sha256:849df64e889b2e17230d58410a03dba311a65b163508fd33679b2b737d4b7858 \
+ --hash=sha256:87475fabc8d9996fd9c27debb395e642e8c838d78a00b6e932227a0e06b81e26 \
+ --hash=sha256:87e50a3e7cb90af586b6c5faf23e302a970415ac73bd7bd90a515a04b427ef96 \
+ --hash=sha256:89b53f3cda69831909888e0494f4fa0bcd3537e3e138dabeb620bd6ad946bae8 \
+ --hash=sha256:8a893cc101149f80a653f82062ebc95b34525a2614382e1da5458fe7c6997249 \
+ --hash=sha256:8b2bfab86aa71ae13aa41a6a26aab338e0db2b8bc75434b05aea89e011ff35a4 \
+ --hash=sha256:8d86d6fc60743dc916eb79e2eb1ec4818e21e427731543af40a3021851174a13 \
+ --hash=sha256:915563965d418f986e7e145accc592eae9e1a1be3566ff98a05d7a9ec42a76e1 \
+ --hash=sha256:92888bb3187c5ba50500b00b3b310c9f2c651709d28036077680cb5255450a03 \
+ --hash=sha256:93223adc95033dd47133a46ccfc316a0139176fd79085762e27202ec56018f03 \
+ --hash=sha256:9373ad13ef0d2c0fb761e04e55bfdee5a08b52cef2c882c8fbe9935b1517152e \
+ --hash=sha256:9409a8bf35cf78353942504b24a57de3d75b708997a1e4bd8db71ac8633ce364 \
+ --hash=sha256:9b7f416ff0978e2f2249330527f0ad6fa02f4932e6199692d3b52da2048c19e4 \
+ --hash=sha256:9bde855991b7e362c146535e3136a50bfaffc0487d38b33ca7e5edefc6e23849 \
+ --hash=sha256:9cae88599c7219005d879f98e5ed53341e9a122af585e1091200358a3003d2a0 \
+ --hash=sha256:9cf9b1a857e25c4baceeb3624e92a56df3668f398c4acba74e174d81fb4d1d3a \
+ --hash=sha256:9f56f72050826f63dcee7a7f55b0a77168cb3bfc553fd405e7f8f9ece75a4036 \
+ --hash=sha256:a090bb2c68df85450502e3e20d665e3a5af9c65a84d6508ed477badd49166fd3 \
+ --hash=sha256:a192e2c40070d92c3ccf777e3a5c4ff515573cd2bb7ed0c537fdadbbec5bbf21 \
+ --hash=sha256:a19a731138fc27d5682277d3b9df22855cea1239bce7fcec5f78f42ef2d1f3c3 \
+ --hash=sha256:a66c3bc5ab1f0ff2164fc9965ddd611ff0802173f4b9d24554c563f6ab7e1d6e \
+ --hash=sha256:a815775b6c38d4e0ff7bcffbeba67feded90202bb6a226b8dd35f1c855217413 \
+ --hash=sha256:a89012d6d5476ee112d20d998570ed58df2260a852afb1758809cd6900411d21 \
+ --hash=sha256:ae4f5fea5b8b8ccff88238cc8569303e5ee95efae67fa62922a311397a71f346 \
+ --hash=sha256:b6856554c4f44d79fc2307d5768854310a8f0096e501c75637542c82292b0429 \
+ --hash=sha256:b6b751274acb69d77b3323d6b7dbaa3c7fdfc1eb829b7eb61d262f32e1af9685 \
+ --hash=sha256:b736353c0a625bbd5fcec108576e2385db3496f4f771f785ff32e108d3c3bc45 \
+ --hash=sha256:b7fd005a73d9e657273b7a10dc71a9e03c8fb9ee6999798d6918ce095b81ac7f \
+ --hash=sha256:b91363207bd9dc966a691e959bb47f64b30f7ac4b072be9968b366982f7db77c \
+ --hash=sha256:ba0b1d2620edf869789c3879223f52bf2afc5d31b3cb47cc57b3a12c05e2aa9d \
+ --hash=sha256:bbbfc8e28816f19d7c0f1816664980c0a9875d01b27cdf8eedddb639d9e108ad \
+ --hash=sha256:bd16aabe4a02a297c23417aa17ac6299dbd8c49f673bcd645b4929b11f5a4400 \
+ --hash=sha256:c0afc6800ba57ccc350374c5bd6150419915d95ce93cdbab2d783d75eaf30ecb \
+ --hash=sha256:c6708715abcf3c73b99508253e961a9967f02fe536532834149574eda6de0d1c \
+ --hash=sha256:c7c9ab723cde841fefb34efbad91e87f00a674b1fe1cd0784fde742bf2c154dc \
+ --hash=sha256:c8f3d67aeaf55f017982b73683f0e7342ba2f6635a78f69ce89ebb26aa411e5c \
+ --hash=sha256:c9790464842f85f437dbbb54417eda1e0e6bfc52dd8d22d6fd1c994b73b2dc74 \
+ --hash=sha256:ca403d7e4798f525fdfc78e258820419cbbd0f0ecbab9de7840e3c017cf6b8cf \
+ --hash=sha256:d008d90a7f2471519aef0c90dfbe73b3e6e4d5e66ac48e19154c17e89e98b604 \
+ --hash=sha256:d19fbd981a488e22cd04883659ca6b08f50b5974f9fd7c95655ef6a043e5893f \
+ --hash=sha256:d1befeed746d247c81127bb14de9dc3d30edb6e5976d34f83f86ed262b1d9105 \
+ --hash=sha256:d2374b62878abb00cd8309b32af6c0b715cd02dec0ca74ef12e5069bdc64144a \
+ --hash=sha256:d376bbd28b3a8999db1a103b3b388aee6f1ddeb3e51bc2172993efdcd86e064d \
+ --hash=sha256:d4a7319f304a774bed22115bc891618e45f85065ab44ea6acd07d274e750519a \
+ --hash=sha256:d6734d2ef8a50fbf8445c139477da401f50d62a0606bf00e20ec6d87773fefb1 \
+ --hash=sha256:d760fe2a4d7c3b226cb9026d6a842868d52a7901bd98420e1baf14e80da85cf5 \
+ --hash=sha256:d913de495d90407cd859d263bee2e5d1a4ed3eb6573c04e70d9ec619a7cbed7f \
+ --hash=sha256:db19d07e2e0129e974a0e65d0064fc222a446cd5122c2fd4184d2af9fc734a9e \
+ --hash=sha256:dca9ab98072a5a54ebacebdc45f53e645336b320c667410b061be1ca588ae709 \
+ --hash=sha256:ddc7dacc8ece3a182e7f15cb862d1fd616b46d076cb1ae9dd232b2c38b655874 \
+ --hash=sha256:ddf19c062bea7a0cc80f519243d2c01dd091be0cf952a0750d4ad576709559f5 \
+ --hash=sha256:def79fa35ef0cef8d2accec024f4fdc7ead3012ff02f5215c783f39f03ef8cfc \
+ --hash=sha256:df29a0a7107f7011e77f4eebdddec4c7331e24d787a0b21a46d63bdf7445da95 \
+ --hash=sha256:e09a3942ecbdee5cce73ea9d42da82b81b72ac1bf031ce069b93b5adf4eac8cd \
+ --hash=sha256:e242bb1c5e76e97dfa9e7f209a71e93a01d7f19ffdd5cfbb2e2d55b4f08f8ab0 \
+ --hash=sha256:e243bd13217235fc7290c621941c3f5cc8b66e4872495be821d7436ba2fb838d \
+ --hash=sha256:e2af3aad578aa6bd1384bcf4750fc285e5a9de53f40b7d41e5a0bf748edeb2b3 \
+ --hash=sha256:e4e81e09c1578b8df602e3db08b0b3ea0a6947ad612f52bf8dc5ea8d47691f0c \
+ --hash=sha256:e54da4baf05720032d527874d40b65fa4d7e5c6c6a43d0c3adbeffcaf275a2b3 \
+ --hash=sha256:e80e6c2f55656b4824d72065abb4ddd6a525c74bd78a0aab5d9fc2cf4fb5af50 \
+ --hash=sha256:ed2a239c0ea213acc1908150a3037257083c7c083128f1a4cec2ec4b97dca491 \
+ --hash=sha256:ed905975ab14056a2e5eb1c376cb2e1ebc5396baf84163939c518556fccde9f5 \
+ --hash=sha256:ee21e28f0430bd6dc9086c6e525d5e818a44a5ad19720c8a0ef766792f3eb5e5 \
+ --hash=sha256:ee43c17b173d46a3212baa6ead3ae258eeabdae48c263a01ccf0218c366dd655 \
+ --hash=sha256:ef4fcbf3327382cd4c9f540babd61248208af7b93eec4de397b4d5f58a09e288 \
+ --hash=sha256:eff0ac9dbe711a4aee69bf04a83896aa9b85f19641264053a9f6d48573abb7dd \
+ --hash=sha256:f0aa869112ef88429ae17820d99c3dd9504c9e9c671d3c246f3d7442cb051084 \
+ --hash=sha256:f3c96f633825733f735c5a9cf21d21a257d8e1edf0b1cee0a064b9c424ca0f7d \
+ --hash=sha256:f5833ad231be5eb6553de524a70f48d71b2c8563101750531e0b80184e175cd4 \
+ --hash=sha256:f5ec61164adcec446f8969a3358ec3f9b26bbda3b9213e5586d219afa8df2915 \
+ --hash=sha256:f7d486c83842422badd511868fd8a9a20e9407ace71564b6af47ce7e60a336c1 \
+ --hash=sha256:fb9e68df06293761f9fe66ade60a9bc6d0f5e42b8acf2939a9158af86ab0e5bd \
+ --hash=sha256:fc14a032f813bf5fe624d991960ea83e9715adc27e4c1830a2361eb1d02ac341 \
+ --hash=sha256:fcff63213e8e6e47770541a4607175404f47cbb3ebea7b6058cc82d524a0e424 \
+ --hash=sha256:fd1fbe0f116b6e55da77aca2c6ddcddcfac2186cbf78bdebf40fc156efca389d \
+ --hash=sha256:fe9753dfee015c570d73df76f899f18444d41388bffcde097deba51c4fadbb9f
+ # via requests
+cryptography==50.0.2 \
+ --hash=sha256:0ddc924c04591c2811ca024d62ecad4f7f6f08af8939c211438f48a16bd23602 \
+ --hash=sha256:0ec5f09541743261e66e291b4a0cbf0fb2997aeaab6d9e9c740b9dba1b58d1c2 \
+ --hash=sha256:0ecbc5652bdb6fc9eaf89a7d196e20941adfe812f43bc4ca05d9150496821047 \
+ --hash=sha256:1981f1db4630889b9ef7803fadef12b056f428cb6b85c27ba57b774793b6093c \
+ --hash=sha256:1ba34f04897fcdaa73f74145c25f3ec146fbd56593853e88adc2e811303c5f42 \
+ --hash=sha256:241449bf940a5d27309bd317e6f9a2af6932113818bb2b8f5c59ddc7ef16da18 \
+ --hash=sha256:25784ce8b9621c90c643efb9e1e2162ab3b0224cae446ad5e70e7fcb1ce18b51 \
+ --hash=sha256:3dc4fd8058cea1644971207d530e1a03a184a805ffc8ebdddf0599d78a331b81 \
+ --hash=sha256:4061c0079120205fb760c58acab6443e217307dcf05e3702cf970e0689972856 \
+ --hash=sha256:4a20ce1e5cb4284a86692fdcba7cb8754185c6b2e5c56fcef3751cf451d3cdc2 \
+ --hash=sha256:4e81d95e5bafc2d6e34e4bed780e53e4d5b9a2f928573428aa4d35fbec1eb0de \
+ --hash=sha256:58a0c478eeca76fe5e07993c5a0703def34a6dc6a0cda4f5564639b33112ffe7 \
+ --hash=sha256:58ddb5a8e3179d12f19e4ea34d2d32e9d63a4baa142c875c1eb59f41b7243acd \
+ --hash=sha256:630ebfea3bf689d075f82316324ff7433dc447fe6bc1bfc76524b74b4a9567d2 \
+ --hash=sha256:6f8700550aa1474a91e5dc07049c46f98b423b5b1ddd0483e0b51362eeeaf5be \
+ --hash=sha256:78198641e5be9521beea5aa782bb551a58068d10e6eb04c9c680c1b69f2e7d45 \
+ --hash=sha256:79def8d059362e7831389ed3be0ecdf58a89386e1271e35dd9f5af84e81bffd0 \
+ --hash=sha256:7a8701d6b584d76e909e3d305b7d126b41439876a5aaf76cddc67fc230eafa2e \
+ --hash=sha256:7afa5a6602a9f29af1f3a2965f831bae7c9d5d597b7cbb716d41ab3b7d89879c \
+ --hash=sha256:7b46165bb56eb4704e2eaaf86f3c940d19154535d9b0ca7d6d590b04060e00d5 \
+ --hash=sha256:7b75de3c8b3be1cdb1052747c929440c3eea46c1bc2cb8a6e3a48388e9b7b452 \
+ --hash=sha256:7c6d0330c472d96f6a6afe24d80dfdf15176c33096f0a4397ae4c60f3dd3be48 \
+ --hash=sha256:828d49b0ff5a0e3975865571c5d91dbbdd0d38d8289b249a163e9425413a5e05 \
+ --hash=sha256:84f964e537f916e2cc85199e5a88742e964939b575ac8598b3f9d6cc416cdaf1 \
+ --hash=sha256:85d0d9a31b9098e98534226d5686b47264b95e62ce459dc2e62fdfc809f9fe93 \
+ --hash=sha256:87e9ce85beb6b328ba370cc6e6aea483c92617b4c95b1d33a49297eb662bfb04 \
+ --hash=sha256:8c71ba2cd31fc93748c38e1b613200ff1c2665cbfd5341fe3a61cfde35a1430e \
+ --hash=sha256:92e665960f25fcdc73725b9cec7a3824f279ba97a98653afe9ffac2e43668f67 \
+ --hash=sha256:94e5e9f108ee10471288214d3d233fbfbb492840a8457eb85178d643ddeb32c7 \
+ --hash=sha256:9c8402a82ea0dc4ceeab793db05f0fafa8ca139ca34fcde5df0f596103c74107 \
+ --hash=sha256:9dab55f57c74c3cad24c323bacbbd04be4705ba6eb0d92e920b1fc4837ed5079 \
+ --hash=sha256:a582ab2ae1d34f67112cadc86702774c9ea4374df6bca6afe672817203c99134 \
+ --hash=sha256:a6557e5f38e065ca9fbdaf7cfc7435ecb1d113aa81a022d1b51921ee7432e227 \
+ --hash=sha256:a9f7355e6fab51f6c369b86fb7571cffa05edee2c2121e0380a37fb9ac1cd5c1 \
+ --hash=sha256:ab50ee449bf968271e820086f10a33d101dd060370abc10bcd22279be2656539 \
+ --hash=sha256:ac9ed99d81760c62fe89d5f0815cdfa1ba9a35141cf30f1c2d044f04b4803d2e \
+ --hash=sha256:b13478603dcd0a2479ff8e87e2c19a7d525734686fe3c49542472293a204212d \
+ --hash=sha256:c423ab384a46c4dff7217b2ea5ba2e11cffdeab6441acd04cf65a369caf0366c \
+ --hash=sha256:c5e67125c7dca78d199ec4e116aa93dbb83494808ecbb8211a2cb09b1bf41dbd \
+ --hash=sha256:c71be1cbfa5cd9a41ee452acf1eccd82b2c05950358b106ec8ceb83411d1a020 \
+ --hash=sha256:cbc8738fd8526d80f35cb3a40d41f41a2e7030bb3b18b09a6778ef63d291c2fd \
+ --hash=sha256:ce47f66801c20ec6c6632453bb5960fe38939e9306970b48b3a5a26de7745d94 \
+ --hash=sha256:d370b8d1dfcdf7130178137f6fbee6140774a1acc6cacefc4b42643ec11d0a3a \
+ --hash=sha256:d38cdff612d06fa6a32840d5e1b1f7a27cee4a349aa9085d94a67789d6bfd408 \
+ --hash=sha256:d8947001be83df1394050758ce0e745dd74fb134eef0a4b5124208dfc3a68c37 \
+ --hash=sha256:deb9fde5c60e437ee4821bc9bc39ff31b42135c27e1dc61ef0a629389c1de62e \
+ --hash=sha256:dfe9763530994147d9af1def057a5b9658b00e8f8fe8743d144d1e0911c2e454 \
+ --hash=sha256:e105ab60406787da31fccc883fc0f733af1efd78f0136a4599692c4083a73d0c \
+ --hash=sha256:e275096ea1e60cc595cda2836fd4a6c725d1125108b868be17f53684d164e2cc \
+ --hash=sha256:edc3342adf8f697fc5f59c887a304356f147b397809440ed64e2fa6af2f50f37 \
+ --hash=sha256:ee247f5c245c9a2fe7c8e2214e295918838e44e00a45a6718451e4004219e767 \
+ --hash=sha256:eef4c2f3423810b3070ab391f85436d2f8bbfcb286ac15cbc73190b3563b1f1a \
+ --hash=sha256:f21e8a22c8605750c7af886bab299a363721264061b4ac0a30efb73cfd58efc5 \
+ --hash=sha256:f265528741e048bce55c3463ed721fb0aa45a5888d8add8cfeccb3035451bbdc \
+ --hash=sha256:f2f9bd7f90c64fe89253f0a2c05e3c4856072660429ce8831b4235bf29403a67 \
+ --hash=sha256:f785f6161f202ab04d8ca194158968798e480ca058943907972da5f12e2881e8 \
+ --hash=sha256:f9f6143a8c75945eb960d9eb98905a441394abfa24afaae239d514ffb2586480 \
+ --hash=sha256:fa8f5efb344d6908a1ce62f4a24e2e5780f825d6f53f5f50ec5ffacac72936cb \
+ --hash=sha256:fdd28f912fccfec1846a94e2e1e8f9b0012f557f0c46fe4f3eb0d7a87afcf90b
+ # via
+ # pyopenssl
+ # rfc3161-client
+ # sigstore
+dnspython==2.9.0 \
+ --hash=sha256:9a4aedb833c3c1b49214d04d44d3032ab7a9135f7c1d29a549b4ff78fd82fda9 \
+ --hash=sha256:b44dc6b18f07a8b1c56676a19fbfdb5209415b046a9cece286baafa87ff3f7f1
+ # via email-validator
+email-validator==2.3.0 \
+ --hash=sha256:80f13f623413e6b197ae73bb10bf4eb0908faf509ad8362c5edeb0be7fd450b4 \
+ --hash=sha256:9fc05c37f2f6cf439ff414f8fc46d917929974a82244c20eb10231ba60c54426
+ # via pydantic
+id==1.6.1 \
+ --hash=sha256:d0732d624fb46fd4e7bc4e5152f00214450953b9e772c182c1c22964def1a069 \
+ --hash=sha256:f5ec41ed2629a508f5d0988eda142e190c9c6da971100612c4de9ad9f9b237ca
+ # via sigstore
+idna==3.20 \
+ --hash=sha256:a7db850025b95ded1eae8a46181a1a6c56c92c96f0e2b005d9ff8dc0210cab44 \
+ --hash=sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c
+ # via
+ # email-validator
+ # requests
+markdown-it-py==4.2.0 \
+ --hash=sha256:04a21681d6fbb623de53f6f364d352309d4094dd4194040a10fd51833e418d49 \
+ --hash=sha256:9f7ebbcd14fe59494226453aed97c1070d83f8d24b6fc3a3bcf9a38092641c4a
+ # via rich
+mdurl==0.1.2 \
+ --hash=sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8 \
+ --hash=sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba
+ # via markdown-it-py
+packaging==26.3 \
+ --hash=sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79 \
+ --hash=sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c
+ # via -r .github/release-signing-requirements.in
+platformdirs==4.13.3 \
+ --hash=sha256:5e567f664eb087ab8521c0179cd8d1bd60857d271136567a39719e28e2d383ce \
+ --hash=sha256:f6ad7f447f24f8a3b82cce5976387428bff894a0eca6c3488f4a17f153c130c4
+ # via sigstore
+pyasn1==0.6.4 \
+ --hash=sha256:9c447d8431c947fe4c8febc4ed9e760bc29011a5b01e5c74b67025bd9fb8ce81 \
+ --hash=sha256:deda9277cfd454080ec40b207fb6df82206a3a2688735233cdcd8d3d565f088b
+ # via sigstore
+pycparser==3.11 \
+ --hash=sha256:51d5a8ba2be0bbe440b99d2112604c95bbbc3c2748a64260186c541e1729cd80 \
+ --hash=sha256:d875f09c3507d00e1aba0eecc6dcadc1352f30fff09dc6bff2f1c2935e97c2bc
+ # via cffi
+pydantic==2.14.1 \
+ --hash=sha256:9195d967ec791692a04438115466764fb8b9a27b31f14a760437694f40d6b454 \
+ --hash=sha256:94f478203dd03404682a1ada216965651dd74b1d2d5ffd62e00e0837caab5c26
+ # via
+ # sigstore
+ # sigstore-models
+ # sigstore-rekor-types
+pydantic-core==2.50.1 \
+ --hash=sha256:0036473f5583e6a60e50b8b21651511564277a3f05cc5dab8cf579f552cd5f6c \
+ --hash=sha256:0048b6dddc8ef4b64fccaad878bd143b0c3882ea9936279dc11d613f6b7dd1bc \
+ --hash=sha256:009634b83993777ddcd69cad0ffcace43dabde692109528e35f0fde91e386a8b \
+ --hash=sha256:028e2f212273d4a39b1ec1e0de8166b1165a65fc0f1111452a9d94fc7c625c63 \
+ --hash=sha256:062e891facce5ca296a1c37098e5e466780457f86413894b399f0cf22934f769 \
+ --hash=sha256:06e01fbbfdb9be777b316a71b6c49efaf4a08b615d0a98d678cda3023f79d019 \
+ --hash=sha256:06ead20d39ffd6f2f6f2a8f8a6de67ff8bb1b4f14a8a30e058502514ee2ac685 \
+ --hash=sha256:0b3a6f334c6a2345ca15318ff894502a90012536404b37c844a976c76c846e0b \
+ --hash=sha256:0c003c3b7f49debb893d2d85ae099ac5959c9839e2f330fadb1fcdf7a6594482 \
+ --hash=sha256:131059670f1d2444269b8585cb888963994871932447c08b39ac6a51fcfef658 \
+ --hash=sha256:132529c83901437ff642f585216831bf5fd7a91df66829907e155192ead62498 \
+ --hash=sha256:17e722e156d0444ecaefbe640bdb60928752bf2013e2b7a11cdb099aaae19bec \
+ --hash=sha256:1a9006395dece0e32e704c315eff8a00bede494f6108546cfc5539c89fef4f9a \
+ --hash=sha256:1c8632d4ac04e6f91128fca584b3a8a507d81604c24eeaaad00d4be42765c32b \
+ --hash=sha256:1c96fd793b73d1b92e65570132505498fe7b21eaef73cdf74e67e5dfba7ac9e4 \
+ --hash=sha256:1cf41f1ae3fa155cf167a72689ad044bcc1e3c97e064123677149bdfb5dafc4a \
+ --hash=sha256:1deeacb112d14d3f4fcb16b165f7dbaf76c70ba6e82f37ba042bdab51970a0b8 \
+ --hash=sha256:1ef800dd7d85bcdadf4c3076e4c94e43939493558a3b69a1ea830c706d4617bb \
+ --hash=sha256:1fa4c8bc12c1354c5550c0c35c1852c8c1901e89e06561724e03f8d0342e1f87 \
+ --hash=sha256:2005207aafe1231315718bf6ed5d064a7300fb4772754af35ee72fc68159492e \
+ --hash=sha256:23923ab9292c40da026330b1ecf4dc2618c8e86e0422e5d1fbf50d94d64ca4f8 \
+ --hash=sha256:23edad659e8dbd8ca7e4e877fe6c81573abbdf215bd25a68b53e1272f58b80c7 \
+ --hash=sha256:2ab756b72bd5054e4c7ef3ded331b35786cbd3cf931531a508f79a9537517064 \
+ --hash=sha256:2cbd1b75b09e976ed0d6b6ca297675632ca35df86130088457cdc60ef36970ae \
+ --hash=sha256:2cf91809d0721ab81592ba67bea7694821679c10b1a2e3c3460082b286c1918a \
+ --hash=sha256:2df1ff41884de2bc4b307bafd7c40a691094fad2ff8e767e5b45a319257bcf4e \
+ --hash=sha256:2eb75304506894a281d346220a4f7481a1b8729577c5ed2a05395991966a8396 \
+ --hash=sha256:2eedf82ee4753cdab8e50044c6bd569577eebc3859b11fecf4eb9223761ff966 \
+ --hash=sha256:30ddf019d082c117b5d309e5b86710c2a78909907ec1a9381feec3eec02eca0b \
+ --hash=sha256:325c23f3e35cfbf0fe3486fa5f7260d1e45885173002d30a28ca019994124255 \
+ --hash=sha256:32fad3a91e51b6d2039c572db04a5a873260b399f6bd62c3552671fa7a4a2899 \
+ --hash=sha256:36c426eac0af8d1529ff8467e612b933346caec1fdc0d774f78f67a1a11e16c1 \
+ --hash=sha256:3a5fce22f1e87d181e924e12da7d81cfe031fb3881a5ddf26ad28f141756ca43 \
+ --hash=sha256:3aa9de446b793de2beb6fa2d9d0961803126c4e2a99c2f25ab59b9fd6ea125c0 \
+ --hash=sha256:3e46a9eb0a0901dd6275e6b06ac3a464885ef350ec4121fe486869de8053e4bb \
+ --hash=sha256:3fde4fdc6487a58d944ca87cf5adc95d5f266e872c19599f5f4c0a8a1b1f9f9f \
+ --hash=sha256:409e0ea40ec30d9158f33574fd758e689f6045a0f2596701828c27816ca9687d \
+ --hash=sha256:40f523349960fa30f3ea51404308ff50f9997a90df639590f47a057c1f32b415 \
+ --hash=sha256:41bc8237121bd8dc8d888dfd6279fc166ffc88c1f1bf3a8bf00869680533ca4c \
+ --hash=sha256:42b54c2c90ad348b5e3a85e03e715d572c1fde357ef104cdfe3b03b697a404ea \
+ --hash=sha256:455a773617b5913bf5c20d0692e5787b119e52c4d40ea644ca31f5758fd31be2 \
+ --hash=sha256:45b11cac094aa25725581d9304eee93c9028516b9ea80dd9e175e13a5a2c840e \
+ --hash=sha256:45c6266d071c241f2a168d45bf8c54344f0effce35e7e6b73afdec11f3687568 \
+ --hash=sha256:46b3301d3b5c886f77de7546e47274a5842c622ea2020b8c6524c6b66913b4a6 \
+ --hash=sha256:476f6ed8e43cd1e0b460920e23571700872b284e77331cb30c4faf459cf48a4b \
+ --hash=sha256:48569b0ade9edfbe065cad1d700175546592aebbb42f02adcebcc26e75b896fe \
+ --hash=sha256:49c2cbb2397fe4d0987e84606e691af6cb87bc0ee1bd3e7b737f7e10b4c142f9 \
+ --hash=sha256:4a53d13cdfbedbfa87f08b83c1a0a5efcc767d785a4b41934fa9cb672670493a \
+ --hash=sha256:4be846f55c9477f5f3ddde8f2ce941137e16862a56d018ed885d422bb6ae02f2 \
+ --hash=sha256:4df197990c15b5a37c5a277d131d9f2c67de6133f2e5dafd80d9bba4b99f46f9 \
+ --hash=sha256:4e834f6a8e4ff772dcc34f58ef5504147a3ea5b0f4eeb13b0f8eb2ca75ac57f1 \
+ --hash=sha256:57f51b31ff826e2859120cf4737c5a758a48d96f3e97da40ccee1796d58078ff \
+ --hash=sha256:5958c72adb417c39b12ac87525ac60b0d73315fcdc59e21f44ee4a5e2512c9ef \
+ --hash=sha256:5dfe41f232befddb9c4377f6cfc702b51595e2d78ed082672adf8758d2c4619f \
+ --hash=sha256:5f3cae32fc46121f787cb2486de9cf95a8bf72aec5cc78f64c606fa1735a6ef5 \
+ --hash=sha256:64f6047f62a6c5ae08d0a6afb035667aa2d97c3d20d69762e034c5ea144d92a5 \
+ --hash=sha256:6a733778df2f7087ec1100ed0b41533e4f3001976e99570fa34f57c66e7f8e3e \
+ --hash=sha256:6b20a4bffabdad0db2927ac034ae3b8a681b1f7a0182f3e60b479ad2fde21ebb \
+ --hash=sha256:6dbcbee53bf17196a7f745aa9bf5a9603953a1e365b1f020be3207c676a3e7c4 \
+ --hash=sha256:6ed4f3cef55164b026fefb41341b7754cc6b624c75dfe7142d2ecceb5ad21c87 \
+ --hash=sha256:704075d10b74f2f3c6e15407c696d88701df35fc8953f434a431add0d0074db0 \
+ --hash=sha256:739dc730e6be3bd5ec2f4ab5cfc7eb047cc45fc1497b3bafec74ff2ed07df597 \
+ --hash=sha256:7456d699b13954e9c0164dcb267250a10ae0dfb03e6e26d6796ab0d46e189c84 \
+ --hash=sha256:756d669f04e62ec4148ecfe22be6a4484d9b1181a6ef32e205ebfd200540858b \
+ --hash=sha256:7689580e72a642ab5ec64d5f55b2e33636fa43b4ebe63c0c2c965ef307c7d1aa \
+ --hash=sha256:76e2e83fa6ec8cdc972d438dafc2522b3a47bee4ec0ae668b29cfb1977ab5242 \
+ --hash=sha256:7816e98acc08119dc0f340ab167048ecc54126316330c1f0caf7c6756c88e28f \
+ --hash=sha256:79490e33c4c0fcb933bbbcfc3a62184d8803b99f535863dfbb925e1bcb6945ad \
+ --hash=sha256:7f476456ac2bb0d937f75191494a09c83a30765fea4f70f3b404942fe25f6cdf \
+ --hash=sha256:844b869f118e22a41a091bdcedda8a71bc1b0f62c38d1a0c3211cece47e1d8fc \
+ --hash=sha256:84bc765b282a9d5b7fe0348b8648904f25a6a04b2139da52b1dd30c8ac3a2c8f \
+ --hash=sha256:84f34323a61a365b4e9295de6028474754829aaddd59c7bf1a040e7487ef8f3c \
+ --hash=sha256:8812592c85d0edf423f10eadcef42716d71e8219085ad9e85b775057b7306133 \
+ --hash=sha256:88e492e8b9d0312e7dc13667c30222abf284dc3b79b5302b3607b41a5784ce61 \
+ --hash=sha256:8a6791afa2245e6c6b180122d105941644f5bd410bb18623b408808cc41a3102 \
+ --hash=sha256:8b4c3df25bd323bf1d36a648d563cf1fc69d717451569927151bdad7cad07a77 \
+ --hash=sha256:8daa7ee75245d43ad7d747e5c9ecc1b1d06552f72b14887e9276f787d57375f4 \
+ --hash=sha256:93ba4e9d8210d941c200431a56b2c0400b131865947903937ed3ec5404307d2e \
+ --hash=sha256:94845ff54dc5193f228cab81b2662a04bfbb892e95bdc15edf7399000ce57d54 \
+ --hash=sha256:94be440c03fede26969a5ce75468e0e6a9927a1b46d9b679ee8adc1b057b0350 \
+ --hash=sha256:9572c1369e9c9da2d64a7b7992c786d90ff295abc93964cfe3125e4290768070 \
+ --hash=sha256:983a662de2571cb2502fc8ff47b6770b03d025d2eb314c92f77b3f07c74720ed \
+ --hash=sha256:992c3514ec891fa7858099183e4d64e6bd5a5d4ff452fae29df22faa77a006bb \
+ --hash=sha256:99ba9bc2b8062ea0c326a990f7f00e6530c23579de66dd246e72c4cafef950a5 \
+ --hash=sha256:9d1bed94af6a63835461f3cf7502058eb166c58c4778e11d0f433cfb1bd69e19 \
+ --hash=sha256:9e4472072de0137ee0d8e72d6620e85939c271d2f90f6bbb4b15c24638b79f92 \
+ --hash=sha256:a27c09d86600f1bf2fe3f37e1ae697faf3143931c09322cd799da94deee923b5 \
+ --hash=sha256:a29a061fec0b4e2d714f277e70a3a18125ecff803f2fea6eade2f2e53711d112 \
+ --hash=sha256:a3cda0e538208e5d722bbf3698b24f19c0a7d05bc8d5f8a7f9b121ea7fa243d9 \
+ --hash=sha256:a44101320cfe99432db74237545a63057dc7a88dfe792cbcad0647f2af56cb81 \
+ --hash=sha256:a4aaaa791bdae1c972a7e81765f4f3571c926b8e0b9b6e47346499fb80079665 \
+ --hash=sha256:a51eee75939cf811ac09b278745a6cee7dc873ccfbc8b9af3cc88fe4b7ce25b5 \
+ --hash=sha256:a7c58106de36ac6a56314182958de20db8d3a29dfd5db527192cc754e4f8e7fb \
+ --hash=sha256:aa8224f10880d9bf1b5993988ba153d42a8b4f3f4f511f93b1f09c93ff613c72 \
+ --hash=sha256:acbf31f37c53a5ac0c34706c80b4f5107ba20b05fdd3816124bf236ef0c57dd2 \
+ --hash=sha256:adc06d218a1cadfd2ec4628424d7d79ce4eba69c2965e7e7b55106f0da5208c8 \
+ --hash=sha256:ae28183297fb0d2b8dc46a1f01d51f5e45825fc5afe76a835a6cb7fb34821295 \
+ --hash=sha256:b0135bcdcaa0f23573f286e4cb5e0fd2962700964ed13df085b85f2b97aeab9e \
+ --hash=sha256:b087b1c5be7ac687cf22eabfe4b6b608d40df23610651e93611e1f49118baf84 \
+ --hash=sha256:b0d955195bbbe489ad343fcc956eacea9357b79cb22192c66cacdefcbc14b32f \
+ --hash=sha256:b281a3b0f0822618fe5e3e0d8a2048b6356b14388505dc9374ccffeb69989713 \
+ --hash=sha256:b6d0c2183008c188e19f4906d426b293bdc4f67ab17df8e180fe16cda208fa71 \
+ --hash=sha256:bbce99252ba3167b2b6277f1829d5bf4b43b754524bddf7f944707c3db7d2253 \
+ --hash=sha256:bc1f08f68dac9f9e83845a8039880aba2ab553eb9b2259c3243a313182c253fe \
+ --hash=sha256:bc94f474417604bd383d2cd445d071b07dd55fedceed3ce33407bf1fcc107290 \
+ --hash=sha256:bed5163e03b98bc1fa2eb05d74c63d9c5c95d8ed6254985481640fbf5e237dea \
+ --hash=sha256:c17799a62c142d61b8a3c51752a7cbc87fe2ad4ccfab10e628a77b405075c662 \
+ --hash=sha256:c18db21573bd2c6489f9a544b7499f0df2853958c568e5e783536ee1f690af41 \
+ --hash=sha256:c3ede305158e75510be50869b319550ab072008c13d64d4ab1e094fb286b6f44 \
+ --hash=sha256:c516cc5367ca3448995d42cb994bf3f4c9002d2a7c22eac9622551269ad1b807 \
+ --hash=sha256:c531166c42ea7bdfecc8c50049581f05dd1993b09cc7c52bb36a14e96deaec7d \
+ --hash=sha256:c73622ef819328873b53109ee4f77ceb598bffedd02daf916102be3228866b78 \
+ --hash=sha256:c8dce1f1e0e5358b682a6ad3fa5e31b31d4560997b8e61417e9217c8d60f8a0c \
+ --hash=sha256:cb57f304525a5e3c13333b772bf9a473f36326e9c821b2e8e1b2fd36f80ae2c3 \
+ --hash=sha256:ce8c25ca38cc0e3d7753ba180808de2c0c8cb24eae0df64491e40921454e9831 \
+ --hash=sha256:ceff0acc940be2715bd6ad17b24c0e5304abf44f6efd0f81ee8499e640f9dc86 \
+ --hash=sha256:cf356f70551d40374eaffb1aa63f1eb6d2006681cbd7a9faea173ce0f4dd7cd2 \
+ --hash=sha256:d2d82aa62521c55ddfb000ae70f88cdd8de974078f6024e821dfe5addd0c818f \
+ --hash=sha256:d32f3acc081cc3923386d88f422cde8892335e95f034e0104bb4cf9310d9915f \
+ --hash=sha256:d4193206b6587047437f6f11d7e776df23e1c1e23af2a54d9347275614791e10 \
+ --hash=sha256:d5c0e32fdbce7f1e8ef4d11f655694bf5f4175c757a9f1dc2be09b8864e5bcf5 \
+ --hash=sha256:d5e062c01286d861fd6a1c4ff6e063547b3e713067f2df033c0ff97ac2ca006b \
+ --hash=sha256:d8f9e8a6c4ab04b78d61f78627370d834eb004b2869dcb28cfffa647b4ea1980 \
+ --hash=sha256:d939de9c82e2126f7f48a7e658f8a85ed46d57662d53f44c49b8895fe94a3eb7 \
+ --hash=sha256:de531ce1e2a3364e8767878b58f4ff728a434b4fde089781fe30b1e08e2396e0 \
+ --hash=sha256:e50d7b94baac6c7d09927fa5ca5800a0c7ee5015c7fcff65beb3a1931b5a6e09 \
+ --hash=sha256:e5faeaee74a57d32b3ab3aebad2e348f06d3ba946fc5d28c1728455f00a3d13a \
+ --hash=sha256:e6f0cc1bb9900dc558960894adeb30b0c083366fc1d69b856209fb2ca5c36fe5 \
+ --hash=sha256:e8e1d6ce820aa23317e8209a86bd65a540973c12dc7552b48a4f6c8e9926815e \
+ --hash=sha256:ed1e728b39a383c81035b2459cfcb35d99dfb01f7d6ebe3a913bc1cc5b81e459 \
+ --hash=sha256:ee6db2fbed51a7991302e8fac498cd67e336246026d0dfa84cf5166ce1412760 \
+ --hash=sha256:efbecf43d321f7b9281441f1f213f7c21c66988b0e06c2730ba13ed47a46bb08 \
+ --hash=sha256:f2c634642694e6a0dad2ab1d375589fa671fd442edd5caf7d9737b8f6ca22906 \
+ --hash=sha256:f3377c8c2b3ce898423c5e5dd94c7982e30aa7717a7e6ab2470b9de364963709 \
+ --hash=sha256:f5187624823423e1d1b82b1072ac41dc837389e18d3d0572cc19bbee46cd550a \
+ --hash=sha256:f77ac30b19221cd9bd3fcfa3d4614eff93140d0572ab730cded17b64adca05f3 \
+ --hash=sha256:fe90228920fd8ff2be62622b6bb8a2b11acd65046d50c6b130614b5879605a20
+ # via pydantic
+pygments==2.21.0 \
+ --hash=sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9 \
+ --hash=sha256:610ca751c9bc2492b38eb9a38a7fbc93edbbb2d7182edaf34e66ae493dee5c8c
+ # via rich
+pyjwt==2.15.1 \
+ --hash=sha256:42d59d631f7768a1028a64c7ff581a9bf7519804daf91fc5b6c56e30eec5e193 \
+ --hash=sha256:4f259e80cdfb6b3fc18a7de51fd1ef9ec79652f25019bae68975ca2468a34df8
+ # via sigstore
+pyopenssl==26.4.0 \
+ --hash=sha256:28dfcce0162b9211413e26dfbfdf1d24317fbeba18fc93c12400a1856b2a0bc7 \
+ --hash=sha256:f0eb0cb2d581d3ad2b9c489468485e7f2ab6727d08401bcf9d824c3caddf3c1c
+ # via sigstore
+requests==2.34.2 \
+ --hash=sha256:2a0d60c172f83ac6ab31e4554906c0f3b3588d37b5cb939b1c061f4907e278e0 \
+ --hash=sha256:f288924cae4e29463698d6d60bc6a4da69c89185ad1e0bcc4104f584e960b9ed
+ # via sigstore
+rfc3161-client==1.0.9 \
+ --hash=sha256:03be7ac7919c7f4c566076b07773b81b1f1b28d447fa91c6960fb5f82fac5bc1 \
+ --hash=sha256:0ac247d5aa22f3514d1e284bdc547d2ad5f101e1e5d7f6db25db2ab3a0c59f06 \
+ --hash=sha256:4d33f5aaec2974239e1c62a79a6fcf32506b09095482377a8b5be3a00fa67dfb \
+ --hash=sha256:5e619d7e28ffa3a46685923e6d6ba4ce2e74cb09a41c77995a0702cc1a533bc4 \
+ --hash=sha256:614da494c6f8850c5d6d98c23bc291a4e4dbf2c3c9082d9907fa156f9e4a75c6 \
+ --hash=sha256:66997415086d2c6e5d57a2d315157b32a9c3f4f1312877ca8eb55e2e0ddf8ce4 \
+ --hash=sha256:7b703b233dbee7228d117d5f1c118363c61d523fa6f018c9217c79e3c6684f86 \
+ --hash=sha256:8208999e94e1252e3f5f748f5efe59d3b9c308d04c7626be1becfbf3236c9de4 \
+ --hash=sha256:908f6a775da4bdce1d39f825a4431f389542696078ef3e4ed911a068bcaf1792 \
+ --hash=sha256:a7004edfbf1bb7ec7801978a39fa7a7fe385ca59673df90d7578079b6eba3b24 \
+ --hash=sha256:d3cbf1991b6f3457efcb25e1d31179cac556112e6d3e65ec9e0fd70c6e9af90d \
+ --hash=sha256:d4cf92f0e784ff02ff5ea1c574f8521f30953dc178092424126dbd8348034f93 \
+ --hash=sha256:fac3f440a507555e684dc5daba75e33dc08f0f45fdefa48448f19001233a6b21
+ # via sigstore
+rfc8785==0.1.4 \
+ --hash=sha256:520d690b448ecf0703691c76e1a34a24ddcd4fc5bc41d589cb7c58ec651bcd48 \
+ --hash=sha256:e545841329fe0eee4f6a3b44e7034343100c12b4ec566dc06ca9735681deb4da
+ # via sigstore
+rich==15.0.0 \
+ --hash=sha256:33bd4ef74232fb73fe9279a257718407f169c09b78a87ad3d296f548e27de0bb \
+ --hash=sha256:edd07a4824c6b40189fb7ac9bc4c52536e9780fbbfbddf6f1e2502c31b068c36
+ # via sigstore
+securesystemslib==1.5.1 \
+ --hash=sha256:4b8d00abd93707ead10b69eb2b8582376a1364de3b0a71077de534c2ef4985e0 \
+ --hash=sha256:ada8bdf817da29ece4ba91654f6a162ce7cfbadbc3ae3f840f7313f9d22675de
+ # via tuf
+sigstore==4.5.0 \
+ --hash=sha256:020d3e07f622b2916bf453e66ff6ff0711e1fdc5ab69e8bd8902f71d9fcb316f \
+ --hash=sha256:f045b207f2e12605cf775ec38e89c5eda625d71ffa7830477db65e47ec2bc8b2
+ # via -r .github/release-signing-requirements.in
+sigstore-models==0.0.6 \
+ --hash=sha256:5201a68f4d7d0f8bec1e2f4378eb646b084c52609a4e31db8c385095fff68b2e \
+ --hash=sha256:c766c09470c2a7e8a4a333c893f07e2001c56a3ff1757b1a246119f53169a849
+ # via sigstore
+sigstore-rekor-types==0.0.18 \
+ --hash=sha256:19aef25433218ebf9975a1e8b523cc84aaf3cd395ad39a30523b083ea7917ec5 \
+ --hash=sha256:b62bf38c5b1a62bc0d7fe0ee51a0709e49311d137c7880c329882a8f4b2d1d78
+ # via sigstore
+tuf==7.0.1 \
+ --hash=sha256:5ada1db78da3518fa851e28588f4b2249b8662a28ae528f54afa2a1de541fb31 \
+ --hash=sha256:d30434bda6e079ab303fb30d1b3006d939a10ca34783b1573d61cd9b802fa45c
+ # via sigstore
+typing-extensions==4.16.0 \
+ --hash=sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8 \
+ --hash=sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5
+ # via
+ # pydantic
+ # pydantic-core
+ # pyopenssl
+ # sigstore-models
+ # typing-inspection
+typing-inspection==0.4.4 \
+ --hash=sha256:547274fa6b0a561ccf549cc9524b999a578e737d015d8709d021f9d0d13bea47 \
+ --hash=sha256:65b8397ba37ccbce054456aaccddfc91e6e3083c92824df348d96ca832f3f147
+ # via pydantic
+urllib3==2.8.0 \
+ --hash=sha256:0cf3cae568d36aa9576b28dfb35f11328f1cb974ca7647d9475ebb86c75ac6e3 \
+ --hash=sha256:63bf2ead4c879426ebf22ef2a781eeb4aa3b4ae798a0435506f8687fd5bb9b63
+ # via
+ # id
+ # requests
+ # tuf
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index d8afd9dab..ccf6b152a 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -141,7 +141,9 @@ jobs:
needs: changes
if: needs.changes.outputs.python_required == 'true'
runs-on: ${{ matrix.os }}
- timeout-minutes: 20
+ # Windows runs real isolated update jobs before the complete compatibility
+ # suite; that suite was still progressing at the former 20-minute job cap.
+ timeout-minutes: ${{ matrix.os == 'windows-latest' && 30 || 20 }}
env:
PYTEST_ADDOPTS: "-o tmp_path_retention_policy=failed -p scripts.pytest_timing"
strategy:
@@ -152,22 +154,22 @@ jobs:
os: ubuntu-latest
python-version: "3.11"
coverage: false
- # CLI command tests assert exact Rich terminal output; run them
- # serially below so xdist cannot change terminal-width rendering.
- pytest_args: "-n auto --dist loadfile --ignore=tests/cli/test_commands.py"
+ # Keep exact Rich output and real prompt_toolkit pipes in a fresh
+ # CLI process: long-lived workers can exceed select()'s fd limit.
+ pytest_args: "-n auto --dist loadfile --ignore=tests/cli/test_commands.py --ignore=tests/cli/test_cli_input.py --ignore=tests/cli/test_desktop_target.py --ignore=tests/cli/test_desktop_target_entrypoints.py"
- name: latest, 3.14 + coverage
os: ubuntu-latest
python-version: "3.14"
coverage: true
- pytest_args: "-n auto --dist loadfile --ignore=tests/cli/test_commands.py"
+ pytest_args: "-n auto --dist loadfile --ignore=tests/cli/test_commands.py --ignore=tests/cli/test_cli_input.py --ignore=tests/cli/test_desktop_target.py --ignore=tests/cli/test_desktop_target_entrypoints.py"
- name: Windows, 3.14
os: windows-latest
python-version: "3.14"
coverage: false
- # Real PowerShell, browser-handoff, and process-tree tests run
- # serially so xdist workers do not compete for native processes.
- # Keep threaded storage work bounded without adding another runner.
- pytest_args: "-n 3 --dist loadfile --ignore=tests/cli/test_commands.py --ignore=tests/tools/test_exec_platform.py --ignore=tests/cli/test_wsl_browser.py"
+ # Process identities run serially; isolated update jobs use case-level
+ # scheduling below so one file cannot serialize all real venv work.
+ # Retain main's three-worker budget and the separate native-process job.
+ pytest_args: "-n 3 --dist loadfile --ignore=tests/cli/test_commands.py --ignore=tests/cli/test_cli_input.py --ignore=tests/cli/test_desktop_target.py --ignore=tests/cli/test_desktop_target_entrypoints.py --ignore=tests/tools/test_exec_platform.py --ignore=tests/cli/test_wsl_browser.py --ignore=tests/test_install_scripts.py --ignore=tests/test_update_jobs.py --ignore=tests/test_update_profiles.py"
steps:
- uses: actions/checkout@v4
@@ -200,6 +202,13 @@ jobs:
- name: Verify dependency consistency
run: uv pip check
+ - name: Install pipx for offline installer checks
+ if: runner.os == 'Linux'
+ shell: bash
+ run: |
+ uv tool install pipx==1.17.12
+ uv tool dir --bin >> "$GITHUB_PATH"
+
# Channel requirements live in manifests rather than uv.lock. Avoid a
# later uv run sync pruning the packages installed by the previous step.
- name: Lint with ruff
@@ -210,6 +219,27 @@ jobs:
if: matrix.coverage
run: uv run --no-sync basedpyright
+ - name: Check Windows update coordination before the full suite
+ if: runner.os == 'Windows'
+ run: >-
+ uv run --no-sync python -m pytest
+ tests/test_installation_lock.py
+ tests/test_update_profiles.py
+ tests/utils/test_helpers.py::test_atomic_record_reader_does_not_block_concurrent_replacement
+ tests/gateway/test_runtime.py::test_runtime_state_publish_keeps_existing_snapshot_readable
+ tests/gateway/test_runtime.py::test_runtime_state_reader_does_not_block_publish_while_decoding
+ -q --junitxml=test-results/coordination.xml --timing-report=test-results/coordination.json
+
+ # Each update job owns its venv, HOME, profile and lock directory. Preserve
+ # the real installation/restore checks, but avoid a loadfile straggler and
+ # disk contention with timing-sensitive runtime-registration checks.
+ - name: Run Windows isolated update jobs
+ if: runner.os == 'Windows'
+ run: >-
+ uv run --no-sync python -m pytest tests/test_update_jobs.py
+ -n 3 --dist load -vv --durations=25 --durations-min=1.0
+ --junitxml=test-results/update-jobs.xml --timing-report=test-results/update-jobs.json
+
- name: Run tests with coverage
if: matrix.coverage
run: >-
@@ -220,11 +250,12 @@ jobs:
--junitxml=test-results/main.xml --timing-report=test-results/main.json
--durations=25 --durations-min=1.0
- - name: Run serial CLI command tests with coverage
+ - name: Run serial CLI input and command tests with coverage
if: matrix.coverage
run: >-
uv run --no-sync python -m pytest
- tests/cli/test_commands.py
+ tests/cli/test_cli_input.py tests/cli/test_desktop_target.py
+ tests/cli/test_desktop_target_entrypoints.py tests/cli/test_commands.py
--cov=nanobot --cov-append --cov-report=term-missing:skip-covered
--junitxml=test-results/cli.xml --timing-report=test-results/cli.json
--durations=25 --durations-min=1.0
@@ -237,11 +268,12 @@ jobs:
--junitxml=test-results/main.xml --timing-report=test-results/main.json
--durations=25 --durations-min=1.0
- - name: Run serial CLI command compatibility tests
+ - name: Run serial CLI input and command compatibility tests
if: ${{ !matrix.coverage }}
run: >-
uv run --no-sync python -m pytest
- tests/cli/test_commands.py
+ tests/cli/test_cli_input.py tests/cli/test_desktop_target.py
+ tests/cli/test_desktop_target_entrypoints.py tests/cli/test_commands.py
--junitxml=test-results/cli.xml --timing-report=test-results/cli.json
--durations=25 --durations-min=1.0
@@ -293,6 +325,22 @@ jobs:
--junitxml=test-results/process.xml --timing-report=test-results/process.json
--durations=25 --durations-min=1.0
+ - name: Install pipx for offline installer checks
+ shell: bash
+ run: |
+ uv tool install pipx==1.17.12
+ uv tool dir --bin >> "$GITHUB_PATH"
+
+ # Installer subprocesses run here, parallel to the broad Windows suite.
+ # Each case owns an isolated manager/config root, so individual cases can
+ # run concurrently without sharing a console or package installation.
+ # Keep four workers: three exceed this job's budget on native Windows.
+ - name: Run Windows installer checks
+ run: >-
+ uv run --no-sync python -m pytest tests/test_install_scripts.py
+ -n 4 --dist load -x -vv --durations=10
+ --junitxml=test-results/installers.xml --timing-report=test-results/installers.json
+
- name: Upload Windows process test timings
if: always()
uses: actions/upload-artifact@v4
@@ -314,7 +362,7 @@ jobs:
- name: Set up Bun
uses: oven-sh/setup-bun@v2
with:
- bun-version: 1.3.6
+ bun-version: 1.3.13
- name: Verify npm lockfile
working-directory: webui
@@ -361,7 +409,7 @@ jobs:
- name: Set up Bun
uses: oven-sh/setup-bun@v2
with:
- bun-version: 1.3.6
+ bun-version: 1.3.13
- name: Install WebUI dependencies
working-directory: webui
@@ -391,10 +439,12 @@ jobs:
tui:
needs: changes
- if: needs.changes.outputs.tui_required == 'true'
+ if: needs.changes.outputs.tui_required == 'true' || needs.changes.outputs.python_required == 'true' || needs.changes.outputs.webui_required == 'true'
name: ${{ matrix.name }}
runs-on: ${{ matrix.os }}
- timeout-minutes: 10
+ # Native build + clean install + recovery/next-update journeys on Windows.
+ # Each subprocess is separately bounded by the acceptance harness.
+ timeout-minutes: 60
strategy:
fail-fast: false
matrix:
@@ -439,11 +489,10 @@ jobs:
working-directory: tui
run: python3 scripts/pty_smoke.py
- - name: Set up Python for ConPTY smoke test
- if: runner.os == 'Windows'
+ - name: Set up Python for native package acceptance
uses: actions/setup-python@v5
with:
- python-version: '3.13'
+ python-version: '3.11'
- name: Test TUI in a real ConPTY terminal
if: runner.os == 'Windows'
@@ -472,6 +521,58 @@ jobs:
bun scripts/release-notices.ts win32-x64
python scripts/package-release.py win32-x64
+ - name: Build and install the native application package
+ shell: bash
+ env:
+ NATIVE_TARGET: ${{ runner.os == 'Windows' && 'win32-x64' || 'linux-x64' }}
+ run: |
+ python -m pip install --disable-pip-version-check build
+ python -m build --outdir "$RUNNER_TEMP/python-dist"
+ # Archive verification shares the installed launcher's dependencies.
+ # Install the intermediate in this build environment, not the separate
+ # clean-home environment used by the public-installer acceptance probe.
+ python -m pip install --disable-pip-version-check "$(find "$RUNNER_TEMP/python-dist" -name '*.whl' -print -quit)"
+ python -m scripts.build_tui_wheels \
+ --wheel "$(find "$RUNNER_TEMP/python-dist" -name '*.whl' -print -quit)" \
+ --tui-dir tui/dist --target "$NATIVE_TARGET" --out-dir "$RUNNER_TEMP/native-wheel"
+ version="$(python -c 'import tomllib; print(tomllib.load(open("pyproject.toml", "rb"))["project"]["version"])')"
+ python -I scripts/verify_installed_release.py \
+ --install-wheel "$(find "$RUNNER_TEMP/native-wheel" -name '*.whl' -print -quit)" \
+ --version "$version" --commit "$(git rev-parse HEAD)" --gateway \
+ --report "$RUNNER_TEMP/native-install-report.json"
+
+ - name: Exercise updates with the default Windows path policy
+ if: runner.os == 'Windows'
+ shell: pwsh
+ run: |
+ # Only this disposable runner changes. Do not require users to enable
+ # machine-wide long paths for an ordinary update's atomic temp files.
+ $key = 'HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem'
+ Set-ItemProperty -Path $key -Name LongPathsEnabled -Value 0
+ if ((Get-ItemPropertyValue -Path $key -Name LongPathsEnabled) -ne 0) {
+ throw 'Native update acceptance requires LongPathsEnabled=0'
+ }
+ Write-Output 'Packaged update/recovery acceptance: LongPathsEnabled=0'
+
+ - name: Verify packaged upgrades and automatic service recovery
+ shell: bash
+ run: |
+ python -I scripts/verify_packaged_update.py \
+ --wheel "$(find "$RUNNER_TEMP/native-wheel" -name '*.whl' -print -quit)" \
+ --commit "$(git rev-parse HEAD)" --output "$RUNNER_TEMP/packaged-update"
+
+ - name: Retain the native package acceptance report
+ if: always()
+ uses: actions/upload-artifact@v4
+ with:
+ name: native-install-${{ runner.os }}-${{ github.run_id }}-${{ github.run_attempt }}
+ path: |
+ ${{ runner.temp }}/native-install-report.json
+ ${{ runner.temp }}/packaged-update/packaged-update-report.json
+ ${{ runner.temp }}/packaged-update/*/result.json
+ if-no-files-found: error
+ retention-days: 3
+
docker:
needs: changes
if: needs.changes.outputs.docker_required == 'true'
diff --git a/.github/workflows/release-approve.yml b/.github/workflows/release-approve.yml
new file mode 100644
index 000000000..7da55a5fb
--- /dev/null
+++ b/.github/workflows/release-approve.yml
@@ -0,0 +1,87 @@
+name: Approve Exact Release
+
+# No schedule, release trigger or PR token. Repository administrators must first
+# protect main and release-approval, then explicitly enable the repository var.
+# This produces a signature only: it never uploads release assets or writes a feed.
+on:
+ workflow_dispatch:
+ inputs:
+ version:
+ description: Exact previously tested version (without v)
+ required: true
+ type: string
+ manifest_sha256:
+ description: SHA-256 from the independently reviewed candidate evidence
+ required: true
+ type: string
+ source_commit:
+ description: Reviewed full source SHA
+ required: true
+ type: string
+ candidate_commit:
+ description: Tested full candidate SHA
+ required: true
+ type: string
+
+permissions: {}
+
+concurrency:
+ group: release-approval
+ cancel-in-progress: false
+
+jobs:
+ approve:
+ if: >-
+ github.repository == 'HKUDS/nanobot' && github.ref == 'refs/heads/main' &&
+ vars.NANOBOT_RELEASE_SIGNING_ENABLED == 'true'
+ environment: release-approval
+ runs-on: ubuntu-latest
+ timeout-minutes: 10
+ permissions:
+ contents: read
+ id-token: write
+ env:
+ RELEASE_VERSION: ${{ inputs.version }}
+ MANIFEST_SHA256: ${{ inputs.manifest_sha256 }}
+ SOURCE_COMMIT: ${{ inputs.source_commit }}
+ CANDIDATE_COMMIT: ${{ inputs.candidate_commit }}
+ steps:
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
+ with:
+ persist-credentials: false
+ - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
+ with:
+ python-version: '3.11'
+ - name: Install hash-locked signing tools, not the candidate
+ run: |
+ python -m pip install --require-hashes --only-binary=:all: -r .github/release-signing-requirements.txt
+ - name: Fetch only the proposed manifest
+ env:
+ GH_TOKEN: ${{ github.token }}
+ run: |
+ [[ "$RELEASE_VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+(\.dev[0-9]+|\.post[0-9]+)?$ ]]
+ gh release download "v$RELEASE_VERSION" --repo "$GITHUB_REPOSITORY" \
+ --pattern release-manifest.json --dir "$RUNNER_TEMP/approval"
+ - name: Bind the signature to reviewed evidence
+ run: |
+ python -m scripts.verify_release_approval \
+ --manifest "$RUNNER_TEMP/approval/release-manifest.json" \
+ --sha256 "$MANIFEST_SHA256" --version "$RELEASE_VERSION" \
+ --source-commit "$SOURCE_COMMIT" --candidate-commit "$CANDIDATE_COMMIT"
+ - name: Sign and verify the exact manifest
+ run: |
+ python -m sigstore sign --no-default-files \
+ --bundle "$RUNNER_TEMP/approval/release-manifest.json.sigstore.json" \
+ "$RUNNER_TEMP/approval/release-manifest.json"
+ python -m sigstore verify identity \
+ --cert-identity 'https://github.com/HKUDS/nanobot/.github/workflows/release-approve.yml@refs/heads/main' \
+ --cert-oidc-issuer 'https://token.actions.githubusercontent.com' \
+ --bundle "$RUNNER_TEMP/approval/release-manifest.json.sigstore.json" \
+ "$RUNNER_TEMP/approval/release-manifest.json"
+ - name: Retain small approval proof for the separate publication handoff
+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
+ with:
+ name: release-approval-${{ github.run_id }}-${{ github.run_attempt }}
+ path: ${{ runner.temp }}/approval/*
+ if-no-files-found: error
+ retention-days: 3
diff --git a/.github/workflows/release-candidate.yml b/.github/workflows/release-candidate.yml
new file mode 100644
index 000000000..4884b97bb
--- /dev/null
+++ b/.github/workflows/release-candidate.yml
@@ -0,0 +1,188 @@
+name: Verify Release Candidate
+
+# Preparation only: no cron, tags, GitHub Releases, PyPI or channel-feed writes.
+on:
+ workflow_dispatch:
+ inputs:
+ next_stable:
+ description: Next stable base (for example 0.3.6); must not have a stable tag
+ required: true
+ type: string
+ retain_installable:
+ description: Retain this exact installable candidate and source for 1 day (~400 MB); not publication
+ required: false
+ default: false
+ type: boolean
+
+permissions:
+ contents: read
+
+concurrency:
+ group: release-candidate
+ cancel-in-progress: false
+
+jobs:
+ candidate:
+ runs-on: ubuntu-latest
+ timeout-minutes: 45
+ env:
+ SOURCE_COMMIT: ${{ github.sha }}
+ NEXT_STABLE: ${{ inputs.next_stable }}
+ PREVIEW_SEQUENCE: ${{ github.run_number }}
+
+ steps:
+ - name: Set candidate directory
+ run: echo "CANDIDATE_DIR=$RUNNER_TEMP/candidate" >> "$GITHUB_ENV"
+
+ - uses: actions/checkout@v4
+ with:
+ fetch-depth: 0
+ persist-credentials: false
+
+ - uses: actions/setup-python@v5
+ with:
+ python-version: '3.11'
+
+ - uses: astral-sh/setup-uv@v4
+
+ - uses: oven-sh/setup-bun@v2
+ with:
+ bun-version: 1.3.13
+
+ - name: Install isolated build and verification tools
+ run: |
+ uv venv "$RUNNER_TEMP/release-tools"
+ uv pip install --python "$RUNNER_TEMP/release-tools/bin/python" -e '.[dev]' build twine
+ echo "$RUNNER_TEMP/release-tools/bin" >> "$GITHUB_PATH"
+
+ - name: Prepare an exact, separate candidate
+ run: |
+ python -m scripts.release_candidate prepare \
+ --source-commit "$SOURCE_COMMIT" --base "$NEXT_STABLE" \
+ --sequence "$PREVIEW_SEQUENCE" --output "$CANDIDATE_DIR" \
+ > "$RUNNER_TEMP/candidate.json"
+
+ - name: Verify packaging and selection contracts
+ working-directory: ${{ env.CANDIDATE_DIR }}
+ run: |
+ python -m pytest tests/test_release_candidate.py tests/test_releases.py \
+ tests/test_release_install_guide.py tests/test_installed_release_probe.py tests/cli/test_tui_wheels.py \
+ tests/cli/test_tui_release_packaging.py -q
+
+ - name: Check WebUI and build Python distributions
+ working-directory: ${{ env.CANDIDATE_DIR }}
+ run: |
+ cd webui
+ bun install --frozen-lockfile
+ bun run lint
+ bun run test
+ cd ..
+ uv build --out-dir "$RUNNER_TEMP/python-dist"
+
+ - name: Check and cross-build the five native targets
+ working-directory: ${{ env.CANDIDATE_DIR }}/tui
+ run: |
+ bun install --frozen-lockfile
+ bun run check
+ bun run test
+ for target in darwin-arm64 darwin-x64 linux-arm64 linux-x64 win32-x64; do
+ bun scripts/prepare-target.ts "$target"
+ bun run build -- "$target"
+ done
+
+ - name: Ad-hoc sign macOS arm64
+ uses: indygreg/apple-code-sign-action@44d0985b7f4363198e80b6fea63ac3e9dd3e9957
+ with:
+ input_path: ${{ env.CANDIDATE_DIR }}/tui/dist/nanobot-tui-darwin-arm64
+ rcodesign_version: 0.29.0
+
+ - name: Ad-hoc sign macOS x64
+ uses: indygreg/apple-code-sign-action@44d0985b7f4363198e80b6fea63ac3e9dd3e9957
+ with:
+ input_path: ${{ env.CANDIDATE_DIR }}/tui/dist/nanobot-tui-darwin-x64
+ rcodesign_version: 0.29.0
+
+ - name: Package licensed native archives
+ working-directory: ${{ env.CANDIDATE_DIR }}/tui
+ run: |
+ for target in darwin-arm64 darwin-x64 linux-arm64 linux-x64 win32-x64; do
+ bun scripts/prepare-target.ts "$target"
+ bun scripts/release-notices.ts "$target"
+ python scripts/package-release.py "$target"
+ done
+
+ - name: Assemble and verify the complete candidate
+ working-directory: ${{ env.CANDIDATE_DIR }}
+ run: |
+ version="${NEXT_STABLE}.dev${PREVIEW_SEQUENCE}"
+ python -m scripts.release_candidate assemble --source-commit "$SOURCE_COMMIT" \
+ --wheel "$RUNNER_TEMP/python-dist/nanobot_ai-${version}-py3-none-any.whl" \
+ --sdist "$RUNNER_TEMP/python-dist/nanobot_ai-${version}.tar.gz" \
+ --tui-dir tui/dist --output "$RUNNER_TEMP/release-artifacts"
+ python -m twine check "$RUNNER_TEMP/release-artifacts/"*.whl \
+ "$RUNNER_TEMP/release-artifacts/"*.tar.gz
+
+ - name: Install and probe the Linux wheel without frontend build tools
+ working-directory: ${{ env.CANDIDATE_DIR }}
+ run: |
+ version="${NEXT_STABLE}.dev${PREVIEW_SEQUENCE}"
+ uv_bin="$(command -v uv)"
+ uv venv --python 3.11 "$RUNNER_TEMP/installed-candidate"
+ mkdir "$RUNNER_TEMP/empty-install-path"
+ env PATH="$RUNNER_TEMP/empty-install-path" "$uv_bin" pip install \
+ --python "$RUNNER_TEMP/installed-candidate/bin/python" --only-binary :all: \
+ "$RUNNER_TEMP/release-artifacts/nanobot_ai-${version}-py3-none-manylinux_2_17_x86_64.whl"
+ uv pip check --python "$RUNNER_TEMP/installed-candidate/bin/python"
+ "$RUNNER_TEMP/installed-candidate/bin/python" -I scripts/verify_installed_release.py \
+ --version "$version" --commit "$(git rev-parse HEAD)" --gateway \
+ --report "$RUNNER_TEMP/installed-candidate-report.json"
+
+ - name: Generate the exact candidate installation handoff
+ working-directory: ${{ env.CANDIDATE_DIR }}
+ run: |
+ python -m scripts.release_candidate instructions --source-commit "$SOURCE_COMMIT" \
+ --artifacts "$RUNNER_TEMP/release-artifacts" \
+ --output "$RUNNER_TEMP/install-candidate.md"
+
+ - name: Verify packaged Linux upgrades and service recovery
+ working-directory: ${{ env.CANDIDATE_DIR }}
+ run: |
+ version="${NEXT_STABLE}.dev${PREVIEW_SEQUENCE}"
+ python -I scripts/verify_packaged_update.py \
+ --wheel "$RUNNER_TEMP/release-artifacts/nanobot_ai-${version}-py3-none-manylinux_2_17_x86_64.whl" \
+ --commit "$(git rev-parse HEAD)" --output "$RUNNER_TEMP/packaged-update"
+
+ # Keep the default preflight cheap: no ~400 MB archive upload per manual run.
+ # These reports are not installable releases or publication approvals.
+ - name: Retain identity, structural and native Linux probe reports
+ uses: actions/upload-artifact@v4
+ with:
+ name: candidate-report-${{ github.run_number }}-${{ github.run_attempt }}
+ path: |
+ ${{ runner.temp }}/candidate.json
+ ${{ runner.temp }}/release-artifacts/release-manifest.json
+ ${{ runner.temp }}/installed-candidate-report.json
+ ${{ runner.temp }}/packaged-update/packaged-update-report.json
+ ${{ runner.temp }}/install-candidate.md
+ if-no-files-found: error
+ retention-days: 3
+
+ # Explicit, short-lived release handoff only. This is the documented
+ # exception to report-only preflight; never enable it on a daily schedule.
+ - name: Preserve the verified bytes and independent candidate source
+ if: ${{ inputs.retain_installable }}
+ working-directory: ${{ env.CANDIDATE_DIR }}
+ run: |
+ python -m scripts.release_candidate retain --source-commit "$SOURCE_COMMIT" \
+ --artifacts "$RUNNER_TEMP/release-artifacts" \
+ --output "$RUNNER_TEMP/retained-candidate"
+
+ - name: Retain installable candidate for approved release handoff
+ if: ${{ inputs.retain_installable }}
+ uses: actions/upload-artifact@v4
+ with:
+ name: installable-candidate-${{ github.run_number }}-${{ github.run_attempt }}
+ path: ${{ runner.temp }}/retained-candidate
+ if-no-files-found: error
+ compression-level: 0
+ retention-days: 1
diff --git a/.github/workflows/tui-release.yml b/.github/workflows/tui-release.yml
index 43e4e0e23..b44d00048 100644
--- a/.github/workflows/tui-release.yml
+++ b/.github/workflows/tui-release.yml
@@ -92,5 +92,4 @@ jobs:
if [[ "$TARGET" == win32-* ]]; then asset="${asset}.exe"; fi
gh release upload "$TAG" \
"tui/dist/${asset}.zip" \
- "tui/dist/${asset}.zip.sha256" \
- --clobber
+ "tui/dist/${asset}.zip.sha256"
diff --git a/README.md b/README.md
index 016c61f23..fb648bc7a 100644
--- a/README.md
+++ b/README.md
@@ -77,7 +77,12 @@ You need **Python 3.11 or newer** and access to a [supported model provider or l
Choose the **stable release** for everyday use or **current source** for development and the latest features. This README describes current source; [published documentation](https://nanobot.wiki/docs/latest/getting-started/nanobot-overview) covers the released version.
-New to terminals or model credentials? Follow [Start Without Technical Background](./docs/start-without-technical-background.md). Updating an existing instance? Stop every old nanobot process using that workspace, back up its config directory and workspace, then update and restart through the original launcher or service. See [session storage and version changes](./docs/cli-reference.md#session-storage).
+New to terminals or model credentials? Follow [Start Without Technical Background](./docs/start-without-technical-background.md). Updating an existing instance? Follow [updates and recovery](./docs/updating.md) for your installation method, backup steps and restart checks.
+
+| Track | Install with | Update with | What runs |
+|---|---|---|---|
+| Stable | installer, `uv`, or pip | managed installer: WebUI update; other installs: original package tool | one released Python/WebUI/TUI version |
+| Current source | editable Git checkout | `git pull --ff-only` + editable dependency sync | Python, WebUI, and TUI from that checkout |
**Stable release: automatic setup (recommended)**
@@ -104,7 +109,9 @@ irm https://raw.githubusercontent.com/HKUDS/nanobot/main/scripts/install.ps1 | i
<details>
<summary>Installer details, preview, and script review</summary>
-The installer installs or upgrades `nanobot-ai` using an active virtual environment, `uv`, `pipx`, or a managed venv under `~/.nanobot/venv`. Fresh local desktops open the WebUI; SSH, headless, existing-config, and older-release paths use the terminal setup wizard. Keep the printed command: it identifies the environment that owns the installation.
+The default command installs or upgrades the stable PyPI release. Fresh installations use a dedicated environment under `~/.nanobot/venv`. On a fresh local desktop it opens the WebUI for model setup. That gateway keeps running after the browser or terminal closes; use the printed `gateway stop` command to stop it. SSH, headless, existing-config and older-release installs use terminal setup.
+
+Existing installations keep their package manager, extras and constraints. An active ordinary venv remains an explicit target, not an installer-managed environment. The installer avoids system-wide pip and prints the command to reuse if `nanobot` is not on `PATH`.
To preview the plan without changing your environment, pass `--dry-run`.
@@ -197,7 +204,7 @@ Verify the install:
nanobot --version
```
-If `nanobot` is not on `PATH`, invoke it through the method that installed it: reuse the recommended installer's command, use `uv tool run --from nanobot-ai nanobot ...` or `pipx run --spec nanobot-ai nanobot ...`, or use the Python executable from the environment where pip installed the package.
+If `nanobot` is not on `PATH`, reuse the installer's printed command or run the Python executable from the existing installation with `-I -m nanobot`. For uv/pipx, locate that environment with the original manager. Do not use a temporary tool environment to manage an existing installation.
</details>
@@ -308,7 +315,9 @@ After model setup, keep channels and automations running when interactive launch
nanobot gateway --background
```
-This starts or promotes the shared gateway to a detached process. From the TUI, `/detach` does the same before closing that client. Background mode does not configure startup after a machine reboot or restart after a crash; use an [OS-managed service](./docs/deployment.md#switch-an-existing-gateway-to-a-service) for that. Interrupted subagent tasks are not automatically relaunched after a restart, and missed scheduled times are not replayed; see [subagent recovery](./docs/concepts.md#subagents) and [automation delivery](./docs/automations.md#delivery-and-reliability).
+This starts or promotes the shared gateway to persistent background mode. Fresh official-installer environments already use that lifetime when you open `nanobot webui`; other Python installations can explicitly use `nanobot webui --detach`. Channels and automations remain active after local clients exit. Complete first-time model setup in the WebUI, and use the gateway commands below to manage the same instance.
+
+From the TUI, `/detach` does the same before closing that client. Background mode does not configure startup after a machine reboot or restart after a crash; use an [OS-managed service](./docs/deployment.md#switch-an-existing-gateway-to-a-service) for that. Interrupted subagent tasks are not automatically relaunched after a restart, and missed scheduled times are not replayed; see [subagent recovery](./docs/concepts.md#subagents) and [automation delivery](./docs/automations.md#delivery-and-reliability).
Manage the background gateway with:
diff --git a/docs/README.md b/docs/README.md
index a53d6a384..e24103836 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -58,6 +58,7 @@ For shorter, outcome-focused walkthroughs, browse the [task guide index](./guide
| Need | Read |
|---|---|
| Commands and flags | [CLI Reference](./cli-reference.md) |
+| Update an installation or recover an interrupted update | [Updating nanobot](./updating.md) |
| In-chat slash commands | [In-Chat Commands](./chat-commands.md) |
| Config, workspace, gateway, sessions, tools, and memory in plain language | [Concepts](./concepts.md) |
| Provider/model matching and selection | [Providers and Models](./providers.md) |
@@ -90,5 +91,7 @@ These pages explain implementation and extension points. You do not need them to
| Set up a development environment | [Development](./development.md) and [CONTRIBUTING.md](../CONTRIBUTING.md) |
| Add a channel package | [Channel Package Guide](./channel-package-guide.md) |
| Build the WebUI source | [WebUI Development](../webui/README.md) |
+| Change update APIs, execution or recovery | [Update protocol](./update-protocol.md) |
+| Prepare and publish a release | [Release checklist](./releasing.md) |
If a command or screen no longer matches these docs, please [open an issue](https://github.com/HKUDS/nanobot/issues) with your nanobot version, operating system, and the page that needs correction.
diff --git a/docs/cli-reference.md b/docs/cli-reference.md
index 17528dca4..e628a5fb4 100644
--- a/docs/cli-reference.md
+++ b/docs/cli-reference.md
@@ -7,6 +7,7 @@ Use this page when you know what you want to run and need the command shape. For
| Goal | Command | Notes |
|---|---|---|
| Check the install | `nanobot --version` | If this fails, try `python -m nanobot --version` |
+| Update an ordinary Python venv | `nanobot update` | Latest stable PyPI release; use the [installation-specific route](./updating.md#installation-owners) for other methods |
| Create or refresh config | `nanobot onboard` | Creates `~/.nanobot/config.json` and `~/.nanobot/workspace/` |
| Refresh config non-interactively | `nanobot onboard --refresh` | Preserves existing values and adds missing default fields without prompting |
| Use guided setup | `nanobot onboard --wizard` | Best when you prefer prompts over hand-editing JSON |
@@ -52,6 +53,27 @@ Desktop-only distributions use the narrow `nanobot-desktop-tui` entrypoint insid
## Common Patterns
+### Updating
+
+```bash
+nanobot update --check # Check the latest stable PyPI release; do not install
+nanobot update # Install it in an ordinary Python venv
+nanobot update --dev # Update source and prepare its matching interfaces
+nanobot update --plan # Save an exact review; do not install or restart
+```
+
+The first two commands target stable PyPI releases, not the saved Preview subscription. `--dev` (`--update-dev`) selects source, not Preview. `--plan --channel stable` or `--plan --channel preview` inspects that channel without changing the subscription; `--channel` requires `--plan`. Saved plans are not executed by `nanobot update`.
+
+Before an in-place update, back up configuration, workspace files and chat history, then stop all processes sharing that Python environment. New versions may migrate stored data. Use the original [installation-specific route](./updating.md#installation-owners) for uv, pipx, containers, system packages and Desktop; do not overwrite a manager-owned environment with pip. Already-satisfying dependencies remain installed.
+
+Source updates require Git. Existing editable checkouts fast-forward their current branch to its upstream; resolve local changes, detached HEADs and divergence manually. Updating a package with `--dev` creates an editable checkout under `~/.nanobot/src/` on the official `main` branch. nanobot downloads its pinned Bun when needed; Node is not required. To return to a release, install it in a separate environment and launch outside the checkout; in-place source-to-release switching is refused.
+
+After installation, restart nanobot and verify the **running** gateway's version and behavior. The CLI checks the installation, not the live process. Downgrading requires `--allow-downgrade` and compatible data; back up before using it.
+
+In-place CLI updates have no automatic rollback. A failed or interrupted installation leaves an incomplete-update marker under `~/.nanobot/run/`. Stop nanobot and retry the same update from that environment. On Windows, stop processes holding installation files and retry with that environment's `python -m nanobot update` (add `--dev` for source).
+
+The WebUI's **Settings → About** uses a separate reviewed update-and-restart flow for supported installations and shows owner-specific instructions for others. See [Updating nanobot](./updating.md) for Preview selection, recovery and permission limits. Source updates remain CLI-only. To inspect a saved WebUI job, use `nanobot update --job <plan-id>`; [explicit handoff retry](./updating.md#explicit-recovery-before-package-mutation) requires additional consent and an intact installation, not a post-install repair.
+
Most day-to-day commands use the default config and workspace. Advanced or multi-instance runs usually pass both paths explicitly:
```bash
@@ -141,17 +163,19 @@ Interactive mode exits with `exit`, `quit`, `/exit`, `/quit`, `:q`, or `Ctrl+D`.
| Command | Description |
|---|---|
-| `nanobot webui` | Create config/workspace if needed, enable the local WebUI channel after confirmation, start the gateway, open `http://127.0.0.1:8765`, and follow new gateway logs |
+| `nanobot webui` | Prepare local WebUI settings and open the browser; installer-managed environments launch persistently, other installations remain attached and follow gateway logs |
+| `nanobot webui --detach` | Explicitly start or join a persistent gateway, open the browser and return control to the terminal |
| `nanobot webui --background` | Deprecated; prints the equivalent explicit `nanobot gateway --background` command and exits |
| `nanobot webui --dev` | Start the gateway and Vite together at `http://127.0.0.1:5173`, with live frontend updates |
| `nanobot webui --no-open` | Prepare and start the WebUI without opening a browser |
+| `nanobot webui --no-dock` | Suppress the macOS Dock icon; detached mode remembers this choice until the next WebUI launch |
| `nanobot webui --port <port>` | Set the WebUI/WebSocket port |
| `nanobot webui --gateway-port <port>` | Override the gateway health port |
| `nanobot webui --yes` | Apply safe localhost WebUI defaults without confirmation; configure provider credentials in **Settings → Models** |
First-run WebUI setup binds to `127.0.0.1` by default. Use manual configuration and a WebUI password before exposing the WebSocket channel beyond localhost.
-`--dev` is a foreground source-checkout workflow. For shell-based lifecycle management, use `nanobot gateway --background` (or `/detach` from an interactive TUI); `nanobot webui --background` prints migration guidance instead of silently changing process ownership. It installs frontend dependencies when `webui/node_modules` is missing, proxies to the configured WebSocket channel port, and stops Vite when the launcher exits. The shared on-demand gateway stops only when no other interactive client still holds it.
+`--dev` is a foreground source-checkout workflow and cannot be combined with `--detach`. It installs frontend dependencies when `webui/node_modules` is missing, proxies to the configured WebSocket channel port, and stops Vite when the launcher exits. The shared on-demand gateway stops only when no other interactive client still holds it. Installer-managed normal WebUI launches and explicit `--detach` use the gateway's persistent lifecycle; manage that same instance with the `gateway` commands below. The old `webui --background` spelling remains deprecated and prints migration guidance.
## Gateway
diff --git a/docs/quick-start.md b/docs/quick-start.md
index 1438c5032..96630cb7c 100644
--- a/docs/quick-start.md
+++ b/docs/quick-start.md
@@ -12,7 +12,7 @@ These repository docs describe `main`, which can be newer than the released pack
- Access to one supported AI provider, company endpoint, or local model server.
- The credential, endpoint URL, and model ID required by that service. Local providers such as Ollama may not require a key.
-Git and [Bun](https://bun.sh/) are only needed if you want to install from editable source code. The published installer supports macOS 13+ (Apple Silicon and Intel), Linux with glibc 2.17+ (ARM64 and x64), and Windows x64. On other platforms, use the WebUI or `nanobot --classic`. See the [terminal requirements](./cli-reference.md#agent-cli) for native TUI availability and the [release notes](https://nanobot.wiki/docs/latest/getting-started/quick-start) for package details.
+Official platform packages include the WebUI and matching native TUI for macOS 13+ (Apple Silicon and Intel), glibc 2.17+ Linux (ARM64 and x64), and Windows x64; no frontend build tools are needed. Other platforms can use the WebUI or `nanobot --classic`; see [terminal requirements](./cli-reference.md#agent-cli). Source installs need Git and use Bun, which nanobot downloads when needed.
## 1. Install nanobot
@@ -30,13 +30,13 @@ curl -fsSL https://raw.githubusercontent.com/HKUDS/nanobot/main/scripts/install.
irm https://raw.githubusercontent.com/HKUDS/nanobot/main/scripts/install.ps1 | iex
```
-The installer chooses an active virtual environment, `uv`, `pipx`, or a managed environment under `~/.nanobot/venv`. It installs the stable PyPI release. At the end it prints the exact command it used to run nanobot; if `nanobot` is not on `PATH`, reuse that full command in the examples below.
+A fresh install uses a dedicated environment under `~/.nanobot/venv`, even if uv or pipx is on PATH. Existing installations keep their original manager; an active ordinary virtual environment remains an explicit target and is not adopted. The installer installs the stable PyPI release and prints the exact command it used to run nanobot. If `nanobot` is not on `PATH`, reuse that full command below.
If you prefer to inspect the scripts first, open [`install.sh`](../scripts/install.sh) or [`install.ps1`](../scripts/install.ps1).
## 2. Configure Your Model
-Keep the installer terminal open. The browser opens the local WebUI; go to **Settings → Models** and:
+Wait for installation and startup to finish. The browser opens the local WebUI; go to **Settings → Models** and:
1. Choose **New preset** and give it a name. If **Convert to presets** appears, choose it first.
2. Open **Provider** and select your provider. To add one, choose **Add provider** from the same menu, then enter and save its connection details or complete sign-in.
@@ -79,7 +79,7 @@ Most other providers can say `not set`. This command validates local setup but d
## 4. Get the First Reply
-If the installer-started WebUI is no longer running, run `nanobot webui` again. Leave that launcher open; the first-run WebUI is bound to localhost, so other devices on your network cannot reach it.
+If the installer-started WebUI is no longer running, run `nanobot webui` again. The first-run WebUI is bound to localhost, so other devices on your network cannot reach it.
Send:
@@ -89,7 +89,9 @@ Hello!
Any normal assistant answer is success. It proves that nanobot can load the config, reach the selected model, use the workspace, and serve the browser UI.
-Interactive WebUI and TUI launchers share one on-demand gateway. Closing one launcher leaves it running for the others; closing the last launcher stops it. If you prefer a persistent background process, press `Ctrl+C`, then run:
+Fresh official-installer environments start a persistent gateway: closing the browser or terminal does not stop it. Other installations keep their on-demand lifetime unless you explicitly use `nanobot webui --detach` or the gateway command below. An attached on-demand launcher must stay open; closing its last local client stops that gateway.
+
+To start or inspect a persistent gateway:
```bash
nanobot gateway --background
@@ -163,7 +165,7 @@ If pip reports `externally-managed-environment`, use the recommended installer,
**Current source**
-Clone the repository and install it in editable mode. Bun is required so the checkout can run its matching native TUI instead of mixing current Python with an older release binary.
+Clone the repository and install it in editable mode. nanobot downloads the pinned Bun runtime to run the checkout's matching TUI; Node is not required.
```bash
git clone https://github.com/HKUDS/nanobot.git
@@ -180,15 +182,19 @@ nanobot webui
The source path follows current `main` and can be newer than the published package. The editable install keeps Python pointed at the checkout; `nanobot` runs `tui/` with Bun, and `nanobot webui` automatically rebuilds `webui/` when its bundled assets are stale. All normal commands remain the same as a stable install. For development details, follow [`../CONTRIBUTING.md`](../CONTRIBUTING.md).
-If the package is installed but the shell cannot find `nanobot`, use the runner that owns the installation. The recommended installer prints the exact command to reuse. Common forms are:
+If the shell cannot find `nanobot`, reuse the installer's printed command or run Python from the existing installation. For uv or pipx, locate that environment with the original manager; do not start a temporary tool environment to manage it. The official installer's default paths are:
```bash
-uv tool run --from nanobot-ai nanobot --version
-pipx run --spec nanobot-ai nanobot --version
-~/.nanobot/venv/bin/python -m nanobot --version
+~/.nanobot/venv/bin/python -I -m nanobot --version
+```
+
+Windows PowerShell:
+
+```powershell
+& "$HOME\.nanobot\venv\Scripts\python.exe" -I -m nanobot --version
```
-On Windows, the managed-environment form is `& "$HOME\.nanobot\venv\Scripts\python.exe" -m nanobot --version`. Replace `--version` with `webui`, `onboard --wizard`, or any other arguments you need. Use plain `python -m nanobot` only when that Python executable belongs to the environment where nanobot was installed.
+Replace `--version` with `webui`, `onboard --wizard`, or the arguments you need. Use plain `python -m nanobot` only when that Python belongs to the installed environment.
## Manual Configuration Fallback
@@ -227,26 +233,16 @@ Replace the provider, endpoint, and model together. Do not pair a credential fro
## Updating
-Upgrade with the same method you used to install:
+Open **Settings → About → Update**. Supported installations can update and restart there; others show instructions for their original package manager or deployment. Follow [Updating nanobot](./updating.md) for Preview selection, backups and recovery. Do not switch installation methods to work around an error.
-```bash
-# Recommended installer
-curl -fsSL https://raw.githubusercontent.com/HKUDS/nanobot/main/scripts/install.sh | sh
-
-# Or one of these
-uv tool upgrade nanobot-ai
-pipx upgrade nanobot-ai
-python -m pip install -U nanobot-ai
-```
-
-For a source checkout:
+For an ordinary Python virtual environment, the [CLI updater](./cli-reference.md#updating) is also available:
```bash
-git pull --ff-only
-python -m pip install -e .
+nanobot update --check
+nanobot update
```
-Because the install is editable, normal source changes are visible immediately. Re-running the install synchronizes any changed Python dependencies; the TUI and WebUI refresh their own dependencies/assets when launched. Then check `nanobot --version`. Run `nanobot onboard --refresh` when you want to add newly introduced default fields while preserving existing settings.
+Stop affected processes and back up configuration and data first; restart and verify the running version afterward. Source checkouts should preserve local changes and follow the [development instructions](../CONTRIBUTING.md).
## If the First Reply Fails
diff --git a/docs/releasing.md b/docs/releasing.md
index 7be416529..875c00eda 100644
--- a/docs/releasing.md
+++ b/docs/releasing.md
@@ -1,29 +1,74 @@
# Release checklist
-Use this checklist with the [Release Packaging Contract](../CONTRIBUTING.md#release-packaging-contract). Preparing a release does not publish it. Pushing a Git tag, publishing a GitHub Release, uploading to PyPI, and deploying the documentation are separate operations.
+Use this checklist with the [Release Packaging Contract](../CONTRIBUTING.md#release-packaging-contract). Preparation does not authorize publication. Pushing tags, publishing GitHub Releases, uploading to PyPI and deploying documentation are separate operations.
+
+## Release cadence
+
+Stable is the default feed; Preview is opt-in. Both use one update flow and require confirmation before installation. Neither a faster cadence nor a subscription permits stopping tasks or restarting a gateway automatically. See [Updating nanobot](./updating.md) for user instructions.
+
+| Release | When to prepare it | Public destination | User experience |
+| --- | --- | --- | --- |
+| Stable feature release | At the planned feature milestone | Final GitHub Release and PyPI; also index its manifest for Preview subscribers | Normal update notice |
+| Stable patch | When a reviewed fix or small, compatible improvement is ready; do not wait for the next monthly milestone | Same stable destinations and checks | Normal update notice, no Preview opt-in required |
+| Preview | On maintainer request, from reviewed changes with passing checks; potentially daily | GitHub prerelease and protected `release-index` catalogue; not PyPI | Same update notice for subscribers, with risk shown before installation |
+
+Packaging is maintainer-triggered, not scheduled or push-triggered. Record the requested channel, exact source and candidate identity; preparation does not authorize publication. Unchanged source, failed checks, missing assets, incomplete acceptance or absent approval leaves the last verified release in place. There is no daily-release promise. Acceptance must cover the supported stable baseline and an earlier Preview, including skipped previews, not just the previous build.
+
+### Stable patch procedure
+
+1. Select the supported stable baseline and reviewed fixes. If `main` contains unfinished features, branch from that baseline and backport only the required fixes. Do not relabel an unverified Preview as stable.
+2. Allocate an unused final version, update both version declarations, and follow **Prepare a candidate**. Patches require the same packaging, licensing, native startup, data-preservation and update/recovery gates as feature releases.
+3. Publish approved immutable files in order: GitHub, PyPI, public-download checks, then the catalogue's `stable` pointer. Preserve `preview` and withdrawal history. A stable patch older than an installed Preview must not be offered as a downgrade.
+4. Publish concise fix notes and required operator actions. Users without this updater need their original installation method for the first upgrade; external package/deployment owners retain their route.
+
+### Maintainer-triggered Preview procedure
+
+1. Select an exact reviewed `main` commit with passing required CI; skip it if its source SHA matches the last accepted candidate. Record the next unreleased stable base and an unused increasing Preview sequence.
+2. Run **Verify Release Candidate** for that ref and base. It prepares a version-only candidate, builds the WebUI and five native TUI bundles, and verifies the package set without publication. Users receive built packages, not a checkout requiring Bun.
+3. Select `retain_installable` and preserve the handoff before expiry. Complete native and packaged old-to-new update/recovery acceptance against those exact bytes. Keep candidate SHA, manifest hash, coverage, known issues and source-offer approval together; CI reports alone are neither installable artifacts nor publication consent.
+4. With separate approval, publish immutable `v<version>` at the **candidate** commit and a GitHub prerelease, never the latest stable release. Upload the complete verified set, manifest and notes; make the pinned installer source publicly reachable.
+5. Verify all public sizes/hashes and clean public install/update acceptance before advancing `preview` with a new catalogue generation. Validate against the latest catalogue, preserve `stable` and withdrawals, and serialize stable, Preview and withdrawal writes. A stale publisher must reread and revalidate.
+6. After partial upload, leave the feed unchanged and resume only from the original verified files. Lost or changed bytes require a new version and repeated acceptance. Withdraw unsafe candidates with a reason and offer a newer fix; never rewind the feed or restore user data.
+
+Use Python version ordering: `0.3.6.dev42 < 0.3.6.dev43 < 0.3.6 < 0.3.7.dev1` (illustrative versions). Once a final base ships, previews need a later base; allocate it after accounting for stable patches. The workflow uses `github.run_number` for `N` in `X.Y.Z.devN`; do not reset the sequence without checking published versions. Reruns cannot replace published bytes. Rebuild and test final releases under their final identity; never rename `.devN` wheels.
+
+### Launch gates and automation boundary
+
+Before offering public Preview, obtain approval for index ownership/protection, publication credentials, source retention and exact packaged/public-download acceptance. Candidate preparation does not activate a public channel, schedule, protected publisher or PyPI upload. Preserve approved release bytes and source outside expiring CI storage for their required lifetime.
+
+Automate steps within an explicitly requested run, not the decision to build or publish. Keep builds read-only, publication permissions in a protected stage, the last accepted source/version recorded and one serialized catalogue writer. Announce Preview availability only after verifying its public feed. Any discovery hint must be dismissible; do not show an update badge for an unavailable channel or enroll users merely because they check.
## Prepare a candidate
-1. Choose the previous release and the exact candidate commit. Work in a clean worktree; do not include local configuration, session data, credentials, or unrelated changes.
-2. Update `project.version` in `pyproject.toml` and the final source-only fallback in `nanobot/__init__.py`. Private WebUI/TUI package versions are not the Python release version.
-3. Review the changes since the previous tag. Write highlights, upgrade and rollback guidance, contributor acknowledgements, and the full changelog. Verify counts against the final range; commit counts are not merged-PR counts. Coordinate security disclosures separately.
-4. Run the Python, WebUI, and TUI checks from CI. Confirm the final commit's CI status, not just an earlier PR head. Review installation, configuration, session, and API changes.
-5. Build in a clean output directory with `uv build --out-dir <artifact-directory>`. Do not set `NANOBOT_SKIP_WEBUI_BUILD`. The build hook bundles the WebUI in the sdist and wheel; the wheel is built from the sdist.
-6. Check the intermediate distributions with `twine check`, inspect their contents, and record SHA-256 hashes. Test installation in an isolated environment outside the source checkout, then test upgrading from the previous stable version using disposable configuration and sessions. Do not use a maintainer's live workspace for migration tests.
-7. Prepare the matching documentation PR in `Re-bin/nanobot-web`, following its `MAINTAINING.md`. Review English and all nine translations, preserve Nightly and previous releases, update the latest-version redirects, and run the complete site quality gate. Pin source links to the checked candidate commit; confirm those source files match the eventual tag before deploying. Never advertise an unpublished version as publicly available.
-8. Review the pinned Bun/OpenTUI licenses, corresponding-source materials, and relinking instructions now, not after pushing the tag. Verify the exact upstream revisions are retrievable and the runtime versions match the lockfile and notices. Obtain the maintainer's commitment to honor `tui/SOURCE_OFFER.md` for its entire stated period; tests cannot grant it.
-9. Build all five native TUI targets using the same scripts as the publication workflow. Include ad-hoc signatures for macOS before packaging. Verify every archive's checksum, manifest, executable architecture, required notices/licenses, and embedded source contents. Run platform-specific smoke tests where supported; record cross-compiled-only targets as such and link exact-head CI evidence instead of claiming native execution everywhere. Bundle these archives into the five platform wheels using the command below. Check all final wheels with `twine check`, validate their RECORDs, tags and installed executable permissions, and test first launch with an empty cache and `NANOBOT_TUI_NO_DOWNLOAD=1`. The installed executable must come from `site-packages/nanobot/tui/bin/`, not the checkout or a cache.
-10. Merge the release-preparation PR only after its current checks and reviews pass. Confirm the merged source tree matches the tested candidate; if it does not, rebuild and recheck before tagging. Reconcile the final changelog and documentation source references. The tag must point to this verified commit, not an unchecked later `main` tip.
+1. Choose the previous release and exact candidate commit. Use a clean worktree without local configuration, sessions, credentials or unrelated changes.
+2. Update `project.version` in `pyproject.toml` and the final source-only fallback in `nanobot/__init__.py`. Private WebUI/TUI versions are not the Python release version.
+3. Review the final tag range; prepare highlights, upgrade/rollback guidance, acknowledgements and full changelog. Verify counts: commits are not merged PRs. Coordinate security disclosures separately.
+4. Run Python, WebUI and TUI CI checks against the final commit, not an earlier PR head. Review installation, configuration, session and API changes.
+5. Run `uv build --out-dir <artifact-directory>` in a clean output directory without `NANOBOT_SKIP_WEBUI_BUILD`. The build hook bundles WebUI in sdist and wheel; the wheel is built from the sdist.
+6. Run `twine check` on intermediates, inspect contents and record SHA-256 hashes. Test installation in an isolated environment outside the checkout and upgrade from previous stable with disposable configuration/sessions, never a maintainer's live workspace.
+7. Prepare the documentation PR in `Re-bin/nanobot-web` under its `MAINTAINING.md`: review English and all nine translations, preserve Nightly and previous releases, update latest-version redirects and run the full site quality gate. Pin source links to the candidate and confirm they match the eventual tag. Do not advertise an unpublished version.
+8. Review pinned Bun/OpenTUI licenses, corresponding source and relinking instructions. Check upstream revision availability and runtime/lockfile/notice agreement. Obtain the maintainer's commitment to the [source offer](../tui/SOURCE_OFFER.md) for its full stated period, at least three years after release; tests cannot grant it.
+9. Build all five native targets with publication scripts, ad-hoc signing macOS before packaging.
+ - Verify archive checksums, manifests, architecture, licenses/notices and embedded source. Run supported native smoke tests, record coverage and exact-head CI evidence, and label cross-compiled-only targets.
+ - Build platform wheels below, check them with `twine check`, validate RECORDs/tags/permissions and test pip selection on all five platforms.
+ - Test first launch with an empty cache and `NANOBOT_TUI_NO_DOWNLOAD=1`; the executable must come from `site-packages/nanobot/tui/bin/`, not checkout or cache.
+10. Merge release preparation only after current checks/reviews pass. Compare the merged source tree with the tested candidate; rebuild/recheck changes. Reconcile changelog and documentation links, then tag the verified commit, not an unchecked later `main` tip.
+
+### Protected updater handoff compatibility
+
+Restart-capable packages include `nanobot/update_contract.json`: schema version 1, with `handoff_protocols` listing positive integer protocol IDs. Protocol 1's request, protected startup and activation requirements are defined in the [update protocol](./update-protocol.md), independently of package and WebUI versions.
+
+Before advertising protocol 1, run preparation, frozen-worker and actual-gateway restart tests against packaged code; verify the declaration is in both sdist and wheel. Retain an ID only while its entire contract is supported; incompatible request, startup or activation behavior needs a new ID. Older updaters may install a future package only if protocols overlap. Missing, malformed or non-overlapping declarations must be refused before shutdown and require the installation owner's external update route.
### OpenAI API selector compatibility window
-The temporary `providers.openai.apiType` / `api_type` conversion is supported for exactly two consecutive releases: the first release containing `nanobot/config/provider_api_migration.py` and the next release. Record the first release tag and the final supported tag in release notes. Config saves write the new `api` declaration; there is no legacy runtime selector.
+The temporary `providers.openai.apiType` / `api_type` conversion lasts exactly two consecutive releases: the first containing `nanobot/config/provider_api_migration.py` and the next. Record the first and final supported tags in release notes. Config saves write `api`; there is no legacy runtime selector.
-Before publishing the third release, remove `provider_api_migration.py`, its import and `ProvidersConfig._migrate_legacy_api_type`, and the legacy settings query conversion in `nanobot/webui/settings_models.py`. Remove the migration-specific tests and update the configuration documentation and release notes to require the current format. Keep the current-format routing, settings, and persistence regressions.
+Before the third release, remove `provider_api_migration.py`, its import, `ProvidersConfig._migrate_legacy_api_type`, the legacy settings query conversion in `nanobot/webui/settings_models.py` and migration-specific tests. Update configuration docs and release notes to require the current format. Keep current-format routing, settings and persistence regressions.
### TUI preflight without a release tag
-Use Bun 1.3.13 and a clean checkout. The local build and packaging scripts do not require a tag or GitHub Release. Run targets sequentially because native dependency preparation modifies the shared `node_modules` directory:
+Use Bun 1.3.13 and a clean checkout; no tag or GitHub Release is required. Run targets sequentially because native dependency preparation modifies shared `node_modules`:
```bash
cd tui
@@ -35,11 +80,11 @@ bun scripts/release-notices.ts <target>
python3 scripts/package-release.py <target>
```
-Repeat for `darwin-arm64`, `darwin-x64`, `linux-arm64`, `linux-x64`, and `win32-x64`. On macOS, use `codesign --force --sign - <binary>` and verify the signature. The publication workflow uses pinned `rcodesign` on Linux. Keep the ten `.zip`/`.zip.sha256` outputs in a candidate-specific directory, alongside the Python build intermediates and provenance manifest. Do not include local configuration, instance backups, or test environments in upload selections.
+Repeat for `darwin-arm64`, `darwin-x64`, `linux-arm64`, `linux-x64` and `win32-x64`. On macOS, run `codesign --force --sign - <binary>` and verify it; the publication workflow uses pinned `rcodesign` on Linux. Keep the ten `.zip`/`.zip.sha256` files with Python intermediates and provenance manifest in a candidate-specific directory, excluding configuration, backups and test environments from upload selections.
### Build the PyPI platform wheels
-From the exact release checkout, after `uv build` and the native archive checks:
+After `uv build` and native archive checks, from the exact release checkout:
```bash
uv run python -m scripts.build_tui_wheels \
@@ -48,23 +93,170 @@ uv run python -m scripts.build_tui_wheels \
--out-dir <final-wheels>
```
-The script verifies the Python version and RECORD, native checksums, architecture, notices and embedded source against the checkout, then writes five wheels with complete TUI bundles and regenerated RECORDs. It refuses to overwrite an existing candidate. `--target <target>` builds one platform for a targeted check. Minimum tags are macOS 13, manylinux glibc 2.17 and Windows x64; x64 builds use Bun's baseline (SSE4.2) runtime instead of requiring AVX2. Recheck both Bun and OpenTUI when upgrading either dependency. No musl or Windows ARM64 wheel is provided. Native execution checks must still validate the actual binaries; tags alone do not prove compatibility. Test pip selection for all five supported platforms.
+The script checks Python version/RECORD and native checksums, architecture, notices and source against the checkout, then writes five bundled wheels with regenerated RECORDs. It refuses existing candidates; `--target <target>` selects one platform. Minimum tags are macOS 13, manylinux glibc 2.17 and Windows x64; x64 uses Bun's baseline SSE4.2 runtime, not AVX2. Recheck Bun/OpenTUI requirements when upgrading either. There are no musl or Windows ARM64 wheels; tags do not substitute for native execution.
-The final PyPI upload set is **five platform wheels plus one source distribution**. Do not upload the intermediate `py3-none-any.whl` or native ZIPs to PyPI. Keep the source distribution produced by the same build; it remains usable for Python/classic and WebUI installations on other platforms.
+PyPI receives **five platform wheels and one sdist**, not the intermediate universal wheel or native ZIPs. Keep the same build's platform-neutral sdist for Python/classic and WebUI on other platforms. Record source commit, version, files, hashes, checks and remaining gates; source changes require rebuilding and rechecking.
-Keep an artifact manifest with the source commit, version, filenames, hashes, checks performed, and any remaining release gates. Rebuild and recheck if the packaged source changes.
+Final releases also require `release-manifest.json` for `stable`. Run `scripts.release_candidate assemble` as shown below from the clean final-version checkout, using that final commit as `--source-commit` without Preview preparation. GitHub receives the same wheels/sdist, ten archive/checksum files and manifest; PyPI receives only wheels/sdist. Verify final source and public bytes before catalogue advancement. A TUI-only GitHub Release cannot deliver the final release to Preview subscribers.
## Publish, with maintainer approval
-1. Confirm all pre-tag gates above are complete. Create and push exactly `vX.Y.Z`; do not move or reuse a published version tag.
-2. Create the matching GitHub Release. A draft may be used while assembling its attachments. Pushing the tag alone does not run `Publish Terminal UI` or upload anything to PyPI.
-3. Attach the already verified five TUI archives and their `.sha256` files, after confirming the tag's packaged sources match the artifact manifest. Verify the uploaded bytes match their preflight hashes; never upload a naked executable.
-4. If instead rebuilding through **Publish Terminal UI**, use `tag=vX.Y.Z` and confirm the already completed compliance review. Wait for all five targets and repeat artifact checks on those new outputs. Do not substitute their new bytes under the old artifact hashes.
-5. Make the GitHub Release and all TUI attachments publicly available. Verify their public downloads for fallback/source-built installations. Supported platform-wheel installs do not need these downloads to start the TUI.
-6. Upload only the checked `nanobot_ai-X.Y.Z.tar.gz` and the five final platform wheels to PyPI. Do not upload the intermediate universal wheel or stale files from a shared `dist/` directory. This repository has no automatic PyPI publication workflow.
-7. Verify installation from PyPI, bundled WebUI startup, and bundled TUI startup without downloads in clean environments. Merge the prepared wiki PR only when the stable package is available: merging its `main` deploys the site automatically. Confirm all localized `/docs/latest/` routes select the new version and old version links still work.
-8. Publish the release announcement and add the dated entry to [Release Archive](./release-archive.md). Complete any coordinated advisory publication and reporter notification. Record links and completion status in the release tracking issue.
+### Release approval proof
+
+Both Stable and Preview automatic installs require `release-manifest.json.sigstore.json` beside the manifest on the exact GitHub release. Clients verify Sigstore's production certificate chain/transparency proof and accept only `HKUDS/nanobot`'s manual `release-approve.yml` on `main`. The signed manifest must match version, wheel size/digest and, for Preview, catalogue commit/manifest binding. Verification runs before download and before shutdown, with no unsigned fallback. Unsigned historical releases remain discoverable but cannot be automatically installed; existing installations keep running.
+
+Before setting the repository variable `NANOBOT_RELEASE_SIGNING_ENABLED=true`, an administrator must protect `main` and the `release-approval` environment: require independent review, prevent self-review, allow deployment only from `main`, and restrict bypass and changes to the workflow/signing requirements. Signing is disabled without that variable. No long-lived signing key or Apple Developer ID is required.
+
+After candidate tests and dependency review, take version, manifest SHA-256, source SHA and candidate SHA from retained acceptance evidence, not public downloads. Upload the proposed manifest through the separately authorized release handoff, then manually run **Approve Exact Release** from `main` with those values and obtain environment review. The hash-locked job checks/signs the exact manifest without installing candidate code or writing releases, PyPI or the catalogue. Separately authorize attaching its proof, verify the public proof before advancing either channel, and preserve it with candidate evidence before its three-day CI expiry.
+
+Regenerate the signing lock only in a reviewed dependency update:
+
+```bash
+uv pip compile .github/release-signing-requirements.in --python-version 3.11 \
+ --python-platform x86_64-manylinux_2_17 --generate-hashes --no-header \
+ --output-file .github/release-signing-requirements.txt
+```
+
+Review resolved dependencies; hashes are not malware review. Before the first release, prove a supported real old updater can install the signed candidate and that the candidate can install the next signed version. Private packaged recovery fixtures substitute publication authority and are not signature evidence.
+
+The proof authenticates release approval, not reproducible builds or harmless code. Compromised authorized workflows/reviewers, malicious source that passes review and compromised runtime dependencies remain risks. The signing lock does not lock runtime resolution, which retains the installation owner's policy. A reviewed runtime dependency inventory, public signed upgrade continuity and verified repository protection settings remain security-release gates; do not claim comprehensive supply-chain protection without them. The first installer and checksum source also need a trusted distribution channel.
+
+1. Complete pre-tag gates, then create and push exactly `vX.Y.Z`; never move or reuse a published tag.
+2. Create the matching GitHub Release. A tag push alone runs neither **Publish Terminal UI** nor PyPI publication.
+3. Attach five platform wheels, sdist, five TUI archives, their `.sha256` files and `release-manifest.json`. Confirm tag sources match the manifest and uploaded hashes match preflight. Complete approval proof before offering automatic updates; never upload a naked executable.
+4. If rebuilding via **Publish Terminal UI**, use `tag=vX.Y.Z` with compliance review confirmed. Wait for all five targets, recheck outputs, and assemble/recheck wheels and manifest from those exact archives. Never mix rebuilt archives with old wheel bytes/hashes; replacing public assets requires a new version.
+5. Make the release and complete artifact set public. Verify every file against the accepted manifest, including native fallback/source-install archives. Platform-wheel TUI startup must not need downloads.
+6. Upload only the checked `nanobot_ai-X.Y.Z.tar.gz` and five final wheels to PyPI, not the universal intermediate or stale shared `dist/` files. There is no automatic PyPI publication workflow.
+7. Verify clean PyPI installation, bundled WebUI and download-free TUI startup. After all public GitHub/PyPI files pass, advance `stable`, preserving Preview and withdrawals; check discovery for both subscriptions. Only then merge the wiki PR: its `main` deploys automatically. Confirm all localized `/docs/latest/` routes select the new version and old-version links still work.
+8. Announce the release, add its dated [Release Archive](./release-archive.md) entry, complete coordinated advisories/reporter notifications, and record links/status in the release tracking issue.
## If a gate fails
-Do not publish to PyPI while a required TUI artifact or verification is missing. Keep the documentation's public `latest` on the previous stable version until the new version is usable. If a published package needs a correction, prepare a new version; do not silently replace the code behind an existing release tag. Stop all old processes and follow the documented session rollback procedure before downgrading a migrated installation.
+Do not publish to PyPI with missing TUI artifacts or verification. Keep public documentation's `latest` on the usable stable version. Correct published packages with a new version, never replacement code behind an existing tag. Before downgrading a migrated installation, stop all old processes and follow the documented session rollback procedure.
+
+## Installer identity checks
+
+Fresh base-package installs use the official installer's dedicated venv regardless of optional managers on PATH. `nanobot-install.json` is written before venv/download work so failed first installs retain their owner; it is not readiness proof. Existing venv/uv/pipx installations are not adopted or moved. The receipt records extras for update planning and opts `webui` into persistent background launch; unrecorded installs retain their lifecycle. Include this distinction and the instance-specific stop command in release notes.
+
+Linux/Windows native CI builds a platform wheel and runs the public installer in a private home without Bun/Node/Git on PATH, then checks the managed receipt, installed WebUI, native TUI and gateway. Python/WebUI changes also require these jobs. CI retains small reports, not candidate binaries. Startup probes and offline installer fixtures do not replace packaged upgrade/recovery or public-download acceptance.
+
+Run `pytest tests/test_install_scripts.py` with `uv` and `pipx` available. It uses private homes, offline fixture wheels and real managers, without a gateway or real application install: `install.sh` on Unix and Windows PowerShell with `install.ps1` on Windows. CI provisions pipx outside application dependencies. Verify these owner-preservation requirements:
+
+- Launch the selected persistent environment's isolated Python, not `pipx run`, disposable tools or an arbitrary PATH executable. Existing recognized installations take priority over newly available managers; multiple recognized installs require explicit choice. An ordinary active venv is explicit; uv/pipx environments must use their manager.
+- Preserve uv constraints. Generic pipx upgrades can drop constraints/options; the installer must refuse pipx records with those settings, lock workflows or unconfirmed sources. The owner must review and preserve them. Exact wheels may replace a wheel source, not registry constraints/options; pipx upgrades must retain requested extras and refuse wheels missing recorded extras.
+- A failed selected manager must not fall through to another installation, even on first install. Verify the exact persistent package version before onboarding: a successful pinned/locked skip is not target installation. Restarted gateway identity is a separate check.
+
+Verify the exact-handoff options against the pinned installer, not an older script: `install.sh --wheel <path> --sha256 <published-hash>` / `install.ps1 -Wheel <path> -Sha256 <published-hash>`, or `install.sh --release <version> --manifest-sha256 <trusted-manifest-hash>` / `install.ps1 -Release <version> -ManifestSha256 <trusted-manifest-hash>`. Wheel mode verifies checksum/package/version; release mode selects one of five native tags for the target Python and verifies size/hash/identity before invoking the original owner. No frontend toolchain or extra selector package is installed; the manager still checks Python/dependencies. Hashes must come from trusted metadata, not an unknown publisher.
+
+Release downloads use official GitHub HTTPS hosts and configured HTTPS proxy; retain wheel sources at their recorded paths, including `~/.nanobot/downloads/releases` or `NANOBOT_RELEASE_CACHE`. Failed partial downloads are removed. Wheel-mode `--dry-run` / `-DryRun` verifies without installation/setup; release-mode dry-run checks only the manifest, creating no wheel/cache/environment/setup and proving neither wheel bytes nor dependency resolution.
+
+These exact-version handoffs do not discover Preview, change subscriptions, stop gateways or back up data. Require stopped writers and backup first. Review extras and recorded options for plain pip, suffixed/custom installs and external owners; see the [user guide](./updating.md) and [update protocol](./update-protocol.md). Installer fixtures alone do not establish live maintenance, backup or restart safety.
+
+### Packaged upgrade and recovery acceptance
+
+Linux/Windows native CI runs `scripts/verify_packaged_update.py` against its wheel; manual candidate preparation uses the assembled Linux wheel. Run macOS acceptance against the candidate's macOS wheel:
+
+```bash
+<build-tools-python> -I scripts/verify_packaged_update.py \
+ --wheel <exact-native-wheel> --commit <candidate-commit> \
+ --output <new-private-acceptance-directory>
+```
+
+Build tools need project Python dependencies. The probe creates disposable venv/account/configuration/workspace and loopback gateways, without maintainer data, models or credentials. It records the unchanged healthy target's SHA-256 and candidate commit; faulted private wheels must never be uploaded.
+
+On a local macOS desktop, add `--dock` to verify the real AppKit helper alongside these journeys. The managed receipt must make `nanobot webui --yes --no-open` detach automatically; each applicable running version must have one helper, preserve desktop intent through upgrade/recovery and a second start, and remove its helper on stop. Historical packages without Dock support gain the icon only after their first healthy upgrade and an explicit WebUI launch. This is process/lifecycle acceptance, not a visual Dock-click test; do not enable it on headless CI or claim native Windows/Linux icon coverage.
+
+Require normal and consecutive upgrades, skipped Preview, import/startup failure, backup failure after shutdown, worker termination, partial metadata loss and interruption between program-restoration renames. Each successful journey must show the expected version in a new gateway run, a retained verified backup, authenticated history reads, continued writes and a second ordinary start. Each recovered service must then update to the healthy target with the same account/conversations. Faults affect the first job; backup failure must survive its automatic retry, while a separately confirmed next update can make a healthy backup. The instrumented intermediate Preview's second hop installs the unchanged final wheel.
+
+Compare configuration, retained legacy-source bytes, canonical SQLite records, WebUI transcripts and pending `delivery/outbox.sqlite3` records separately. Cover canonical-only, display-only and mixed history without inventing canonical records for display-only chats; SQLite checkpoint byte changes alone are not data loss. Retain the protocol-1 parked-gateway regression across old/new protected-store inventories: no outbox initialization, migration or writes outside the old grant before activation. See the [update protocol](./update-protocol.md) for scope and lease requirements.
+
+Default baselines are labelled target-derived fixtures, not historical compatibility evidence. For release acceptance, add `--baseline-wheel <previously-accepted-wheel>` and repeat with supported stable and older Preview packages, including skipped Preview. Baseline feed transport is instrumented; the healthy target is unchanged. Include a retained pre-SQLite updater to check JSONL migration's canonical message bodies separately from display history. If recovery restores JSONL code, mark SQLite checks not applicable, not passed. Packages without this updater need separately recorded installation-owner bootstrap acceptance.
+
+Exercise consecutive updates in the same disposable account with existing conversations through each applicable owner: official installer, uv tool, pipx, ordinary pip venv and source. Check recorded constraints/options before/after, execute the offered command, verify the restarted gateway, append a message and start again. Policy refusal must leave installation unchanged; custom owner-reviewed updates do not prove automatic recovery. Container replacement requires a real engine and retained data volumes, not a mocked marker.
+
+For installer-owned background recovery, verify one exact-target repair, then original-program restoration only before activation and only with unchanged protected data, including restart/health verification without browser or terminal intervention. Data changes, activation, live owners or changed installation ownership must prevent unsafe rollback. Other owners retain their repair route. Never delete jobs/fences or automatically restore old configuration/chat data. Exercise native Windows locks/renames. Loss of both supervisor and worker, permanent storage damage and incompatible data writes are not automatically recoverable; retain these limits in release notes and the operator guide.
+
+Keep private evidence until review; it can contain program generations/backups and is not an upload set. CI retains small reports, including completed cases after a later failure; only all selected journeys passing produces aggregate success. Partial reports or a timeout are not an overall pass. Record actual native OS/CPU coverage separately from installer/startup fixtures: Linux x64, Windows x64 and macOS arm64 do not establish macOS x64 or Linux arm64 coverage. Controlled release transport and fault injection prove neither public downloads nor interactive UI; complete those gates before claiming them.
+
+## Stable and Preview subscriptions
+
+Use [Updating nanobot](./updating.md) for Settings → About and CLI instructions. Release acceptance must preserve opt-in consent: Preview is off even on development builds; switching saves/checks a feed, not installation approval. Require separate exact-version confirmation and a Preview risk warning. Profiles sharing an environment/account share its subscription; other installations/accounts do not. Environment replacement may require reselection; browser storage is not authoritative.
+
+| Current install / requested channel | Required acceptance result |
+| --- | --- |
+| Stable → Preview, a newer verified preview exists | Offer that exact preview; install only after confirmation. |
+| Preview → Preview | Offer only a higher verified version, including a final release. |
+| Preview → Stable, stable is newer | Offer the final release; keep Stable selected. |
+| Preview → Stable, stable is older | Save Stable and wait for a newer final release; keep running the preview. |
+| Preview subscriber installs a final release | Keep Preview selected for the next development cycle. |
+| Current preview was withdrawn | Warn even without a safe newer replacement; never silently downgrade. |
+| Feed offline, incomplete, missing or incompatible | Return non-success; retain subscription and allow rechecking. |
+
+Stable checking/planning requires complete PyPI wheels/sdist. Preview uses `release-index/catalogue.json` and exact GitHub manifests, never PyPI `--pre` or arbitrary branches. Validate targets against the gateway interpreter/platform, not the browser. Index final releases for Preview subscribers too; advance only after verifying all referenced public assets.
+
+Versions, tags and manifest hashes are immutable. Increment generation; never rewind or clear published pointers, remove withdrawals or reuse bad versions. To stop offering a version, retain its pointer and withdraw it. Serialize writers and validate `ReleaseCatalogue.validate_successor(previous)` against the latest catalogue. Clients reject rewrites relative to their last accepted catalogue; that check is not cryptographic signing.
+
+Acceptance must invalidate reviews on every channel change, including Stable → Preview → Stable; cancel inactive staged work through normal stop checks and retain diagnostics. Active preparation, committed shutdown, admitted installation or failed mutation blocks switching until settled/recovered. Reject stale-tab writes and reread after lost responses, never automatically retry installation. Detailed transaction rules belong in the [update protocol](./update-protocol.md).
+
+Discovery grants no installation authority. Only the official managed venv and supported POSIX uv transactions support the reviewed stop/install/restart flow; pipx, source, container, system-managed, unsupported uv/platform and desktop distributions retain their owner/distributor route. Remote browsers without package-install permission may read status but not change subscription. Older clients must get actionable failures for unrepresentable statuses, never false “up to date.” Verify these boundaries before announcing a public channel.
+
+## Non-publishing preview preflight
+
+**Verify Release Candidate** is manual, read-only preparation: no tags/releases, PyPI or catalogue writes. It builds/checks five platform wheels, sdist and licensed fallback archives. Cross-compilation is neither native execution nor release approval.
+
+Default retention is small identity/manifest/probe reports and installation guide for **three days**, without installable binaries. `retain_installable` preserves those exact checked artifacts plus a self-contained shallow Git repository for **one day** (about 400 MB). Keep this storage exception off for routine preflight or schedules; assess storage and call it out explicitly in workflow-change PRs before merge. Preserve approved handoffs before expiry; rebuilding expired files cannot reuse their verification. The source contains only candidate/source-parent history, not configuration or untracked files. `handoff.json` is written only after copied artifacts verify; interruption is not an accepted handoff.
+
+After assembly, the workflow installs the Linux x64 wheel and binary dependencies into a separate venv without Bun/Node/Git on the install PATH. Isolated Python checks version/commit/import identity, all Vite-manifest assets including lazy chunks through the installed handler, and bundled TUI `--desktop-protocol` with downloads disabled and empty private HOME. With `--gateway`, it starts a private foreground CLI gateway with no provider/MCP configuration, disabled heartbeat and two loopback ports, then checks readiness, protected version identity, HTML and process/listener cleanup. Unix shutdown must be graceful; Windows termination is labelled, not graceful-shutdown evidence. No model task or external channel is exercised.
+
+On another supported platform, check a disposable native installation without changing its package:
+
+```bash
+<installed-venv-python> -I scripts/verify_installed_release.py \
+ --version <candidate-version> --commit <candidate-commit> \
+ --gateway --report <new-report-path>
+```
+
+Use the candidate commit, not its parent. The probe rejects checkout imports/unisolated invocation and avoids user configuration/credentials. Omit `--gateway` for assets/TUI only. Reports identify OS/CPU/probes and are success-only, never overwritten; failure cleans up children and prints a bounded redacted log tail. This is package/startup evidence, not interactive UI, managed restart, migration, public-download or five-platform E2E acceptance.
+
+For local preparation, use a full source SHA and new output outside the checkout (illustrative base/sequence):
+
+```bash
+python -m scripts.release_candidate prepare \
+ --source-commit <full-commit-sha> --base 0.3.6 --sequence 42 \
+ --output <new-candidate-directory>
+```
+
+Preparation leaves the checkout untouched and deterministically creates a version-only commit for identical inputs. Build Python distributions and all native targets from it, then run from the candidate:
+
+```bash
+python -m scripts.release_candidate assemble --source-commit <original-source-sha> \
+ --wheel <intermediates>/nanobot_ai-0.3.6.dev42-py3-none-any.whl \
+ --sdist <intermediates>/nanobot_ai-0.3.6.dev42.tar.gz \
+ --tui-dir tui/dist --output <new-artifact-directory>
+```
+
+Assembly refuses existing output and emits the manifest only after complete-set, version/commit, WebUI, RECORD, native/source and permissions checks. It compares sdist sources/resources against tracked candidate files with packaging exclusions, and all wheels' application/WebUI bytes against the sdist. Commit markers and RECORDs alone are insufficient; these comparisons do not prove reproducible frontend/native compilation. Recheck with `python -m scripts.release_candidate verify --source-commit <original-source-sha> --artifacts <artifact-directory>`; it may reuse an identical manifest, never replace different bytes.
+
+Generate the handoff from the same candidate:
+
+```bash
+python -m scripts.release_candidate instructions --source-commit <original-source-sha> \
+ --artifacts <artifact-directory> --output <new-install-guide-path.md>
+```
+
+The generator rechecks artifacts/manifest and writes a non-overwriting guide outside the immutable upload directory. When both installers match the supported implementation, commands fetch the exact candidate's installer with the retained manifest hash for automatic platform selection; older candidates keep manual commands, never mutable `main` or assumed flags. Publication must make pinned installer source reachable.
+
+The guide records version, source/candidate commits, five hash-bound wheel URLs and separate new/existing base-package commands for uv, pipx and pip venv. Commands verify local size/SHA-256 with the standard library before manager invocation; URL hash fragments alone are insufficient for the tested uv commands. Retain wheel paths recorded by managers. Manual commands move to an advanced section when automatic entry is supported; no new manifest schema or installer executable is introduced.
+
+Before offering the guide, publish/verify exact public files and add release changes, native coverage, migration/recovery instructions and stop/backup prerequisites. Review extras and locked/suffixed/external-owner options; independently verify installed version and restarted gateway. Manager fixtures do not prove restart/migration, and the guide is neither publication approval nor channel selection.
+
+The candidate clone borrows source Git objects; preserve its source repository until retained in an approved permanent ref. Partial assembly has no accepted manifest and must not be uploaded. Source-offer commitment, native launch, clean install, upgrade/recovery and publication gates still apply. Missing public assets must be recovered from original verified files, never overwritten by rebuilds.
+
+Retain an exact local handoff outside temporary build storage:
+
+```bash
+python -m scripts.release_candidate retain --source-commit <original-source-sha> \
+ --artifacts <verified-artifact-directory> --output <new-retained-directory>
+```
+
+Only `artifacts/` is the upload set; `source.git/`, `install.md` and `handoff.json` are maintenance evidence, not PyPI packages. Restore with `git clone --no-local <retained>/source.git <new-checkout>`, check HEAD against `handoff.json`, and rerun `release_candidate verify` on retained artifacts before separately approved publication. Keep native reports and release notes alongside them; retention adds no native, migration, interactive UI or public-download evidence.
diff --git a/docs/start-without-technical-background.md b/docs/start-without-technical-background.md
index ba1215d01..5889adbc2 100644
--- a/docs/start-without-technical-background.md
+++ b/docs/start-without-technical-background.md
@@ -102,13 +102,13 @@ If the installer finishes without opening the browser and `nanobot` is available
nanobot webui
```
-If the terminal cannot find `nanobot`, take the exact command printed by the installer and replace its final arguments with `webui`. That command may begin with `uv tool run`, `pipx run`, or the full path to nanobot's private Python environment.
+If the terminal cannot find `nanobot`, take the exact command printed by the installer and replace its final arguments with `webui`. It uses the Python executable from the persistent installation, not a temporary tool environment.
On SSH, a computer without a desktop, an existing configuration, or an older nanobot release, the installer may open the terminal wizard instead. Choose **Quick Start** there and follow its prompts.
## 5. Get the First Reply
-Leave the WebUI terminal open. If the browser did not open automatically, copy the complete login link printed in that terminal, including everything after `#`, into your browser. The bare `http://127.0.0.1:8765` address does not sign a new browser in. Keep the login link private: it contains a credential.
+Wait for the startup summary. If the browser did not open automatically, copy the complete login link printed in that terminal, including everything after `#`, into your browser. The bare `http://127.0.0.1:8765` address does not sign a new browser in. Keep the login link private: it contains a credential. Fresh official-installer environments keep running in the background; if the launcher remains attached, leave that terminal open.
Send this message:
@@ -137,7 +137,7 @@ You can also follow the steps yourself using the controls and guides below. Add
Repository docs show the current development version. If your stable package does not yet show **Channels**, use the [Chat Apps guide](./chat-apps.md) or update to a release that includes it.
-Some runtime changes ask you to restart nanobot. Use the restart action shown by the WebUI, or return to the terminal, press `Ctrl+C`, and run `nanobot webui` again.
+Some runtime changes ask you to restart nanobot. Use the restart action shown by the WebUI or `nanobot gateway restart` for a background gateway. For an attached on-demand launcher, press `Ctrl+C` and run `nanobot webui` again.
For a chat platform's account, bot, token, or permission prerequisites, use the [Chat Apps guide](./chat-apps.md). For local models and provider-specific recipes, use the [Provider Cookbook](./provider-cookbook.md).
@@ -166,7 +166,7 @@ nanobot agent -m "Hello!"
| `nanobot: command not found` | Reuse the exact nanobot command printed by the installer; it points to the isolated environment that contains the package |
| `401`, unauthorized, or invalid API key | The key is wrong, expired, or belongs to a different provider |
| Model not found | The model ID is misspelled or unavailable to your provider account |
-| Browser does not open | Copy the complete login link printed by the launcher, including the fragment after `#`, and keep the terminal running |
+| Browser does not open | Copy the complete login link printed by the launcher, including the fragment after `#`; keep the terminal open if the launcher is attached |
| Browser opens but messages fail | Test `nanobot agent -m "Hello!"` to separate a model problem from a WebUI problem |
| A change was saved but nothing changed | Restart nanobot so the running process reloads the config |
@@ -182,4 +182,4 @@ Run:
nanobot webui
```
-Leave that launcher open while you use nanobot. Pressing `Ctrl+C` disconnects it; the shared gateway stops when it was the last local WebUI or TUI client. After the normal foreground start and model setup work, use `nanobot gateway --background` when you want the gateway to stay online with no clients; then manage it with `nanobot gateway status`, `logs`, `restart`, and `stop`.
+A fresh official-installer environment starts a background gateway and returns control to the terminal. Closing the browser does not stop it. Manage it with `nanobot gateway status`, `logs`, `restart`, and `stop`; use the exact commands printed for your instance. Other installation methods keep their attached on-demand launch: leave that launcher open, or explicitly use `nanobot webui --detach` after setup. The last attached client stops an on-demand gateway, not a background gateway. See [updates and recovery](./updating.md) for the matching installation method.
diff --git a/docs/update-protocol.md b/docs/update-protocol.md
new file mode 100644
index 000000000..bf4474ef0
--- /dev/null
+++ b/docs/update-protocol.md
@@ -0,0 +1,88 @@
+# Update protocol
+
+This document is for gateway, client and updater maintainers. For installation choices, WebUI steps and recovery commands, see the [user update guide](updating.md). Release approval, catalogue and artifact schemas belong to the [release contract](releasing.md).
+
+## Ownership and approval boundaries
+
+The gateway owns policy, installation inspection and durable update state; clients present reviews and explicit consent. Reviewing a release, preparing files, approving shutdown, admitting package mutation and activating a gateway are separate decisions. None can be inferred from another's progress, a lost response or elapsed time.
+
+An [immutable plan](../nanobot/update_plan.py) binds an exact release artifact to the interpreter/environment snapshot, ownership receipts, extras, channel revision and known gateway profiles. Its lifetime is at most fifteen minutes. Preparation and shutdown preflight revalidate that target, never substitute a new latest version. Changed environment metadata, ownership, profiles, channel revision, expiry or release eligibility blocks progress. Planning and preflight share the installation's `releases` history: catalogue rollback or changed contents under the same generation must not become acceptable through a fresh per-job cache. A network failure is not a fresh successful check. See [release discovery](../nanobot/release_feed.py) and the [release contract](releasing.md) for approval and download rules.
+
+[Manager policy](../nanobot/update_manager.py) comes from the owner's receipt, not dependency-based guesses. Its hash binds the complete private settings; the review uses a credential-free summary of extras, constraints, source, pins/locks and additional package names. An absent `owner_restriction` is not execution eligibility. Supported pipx receipt schemas are `0.5` and `0.12`; reading them does not enable pipx execution or newer manager flags. The native uv transaction is limited to compatible POSIX uv `0.11.16` registry tools and preserves receipt policy. Unfrozen external resolver policy requires the owner's workflow. A plain-venv transaction requires explicit extras, including `[]` for the base package; installer- or manager-recorded extras cannot be replaced by a client.
+
+## Client interface
+
+Capabilities are optional additions to the [WebUI contract](../nanobot/webui/client_contract.py), not package-version comparisons or a higher protocol floor. Action names below have the prefix `settings.nanobot.update.`; read paths have the prefix `/api/settings/nanobot-update/`.
+
+| Capability | Interface |
+| --- | --- |
+| `webui.update-plans.v1` | `plan`; `GET plan?id=<id>` |
+| `webui.update-jobs.read.v1` | `GET job?id=<id>` |
+| `webui.update-jobs.prepare.v1` | `prepare`, `settle` for interrupted preparation |
+| `webui.update-jobs.execute.v1` | `execute` |
+| `webui.update-jobs.retry-handoff.v1` | `retry` |
+| `webui.update-jobs.settle-handoff.v1` | `settle` also retires inactive, uncommitted handoffs |
+| `webui.update-channels.v1` | `channel` with the saved revision |
+| `webui.update-flow.v1` | Client flow using review, preparation, execution and reconnection |
+
+All routes require authentication. Actions require an authenticated WebSocket; plain HTTP cannot create plans or mutate jobs. Preparation, settlement, execution, retry and channel changes also require the existing local-browser or explicit remote package-install permission and runtime admission checks. Review does not require installation permission. Desktop's native surface retains its distributor's updater. [Transport routing](../nanobot/webui/settings_routes.py) and the [settings handler](../nanobot/webui/settings_system.py) own these checks; update responses are `no-store`.
+
+`plan` accepts only `channel`, `restart_running` (default `false`) and optional `extras`. The default channel is the installation preference, or Stable when absent. It cannot accept a download URL, command, environment path or caller-supplied plan. `restart_running=true` selects known running background gateways with explicit lifetime and cooperative shutdown support, not stopped profiles or unknown supervisors. Inline eligibility requires the requesting gateway and every running peer in the reviewed stop/restart selection, with no unconfirmed owner.
+
+The review separates `installation_allowed` (caller policy) from `execution_available` and `execution_blocked_reason` (exact-plan eligibility). Neither authorizes execution. `validity` is a local snapshot result: `current`, `expired`, `installation_changed`, `profiles_changed` or `channel_changed`. Reading a saved review can inspect the current installation and profiles, but does not contact the release feed or choose another target.
+
+Job actions use `id`; execution additionally requires `confirm_restart: true`, and retry requires `previous_confirmation_id`. A job read returns durable facts including `recorded_phase`, `attempt`, `mutation_started`, `updated_at` and `execution_confirmation_id`, not worker liveness or permission to retry. Missing jobs return 404, invalid identifiers 400, and corrupt or misbound records 409. Reads do not start the installation's Python, contact release services or take its runtime lease; an active writer or incomplete-install marker does not hide history. Environment-path scoping can retain history after a reinstall, but does not authorize resuming the predecessor's job. Raw logs, resolver credentials and diagnostic messages are not exposed. Recovery flags distinguish automatic recovery selection, supervisor ownership and restored service. A returned recovery command is display-only.
+
+[Record publication](../nanobot/utils/atomic_file.py) is atomic, never delete-then-copy. Windows snapshot readers share deletion so polling can coexist with POSIX-style replacement on supported filesystems. Sharing and permission failures remain errors, not permission to publish partial records.
+
+Channel changes use revision checks, invalidate old reviews and retire only safely settled inactive jobs. They never install, downgrade or discard active work. Consumers recover lost preparation/execution responses by reading the same job; a missing journal or transport timeout alone is not authority to submit a replacement operation.
+
+## Preparation leases and settlement
+
+[Preparation](../nanobot/update_jobs.py) saves the immutable plan and a preparation journal before native inspection or resolution. It compares fresh environment metadata before and after staging, verifies the exact nanobot wheel and stages the resolved dependency transaction without changing installed files. Pip preparation retains its configured package-source trust policy; credential-bearing resolver files remain private and temporary. There is no source-build or global-manager fallback. For uv, a sealed private preparation cache and recorded dependency versions bind the offline transaction without rewriting the shared cache or saved policy.
+
+The frozen worker and helpers are standard-library-only and stored outside the installation. [Preparation children](../nanobot/update_process.py) start with `-I -S`, acquire their own runtime and native-preparation leases, validate the preparation generation, then initialize the target's site. Those leases cover `.pth`/site hooks, the actual probe or pip command and `atexit` cleanup, even if the parent disappears. Python commands run in the lease-owning process on POSIX and Windows. Native uv uses POSIX `exec` with retained descriptors; inherited handles do not transfer Windows byte-range lock ownership. Failed `exec` restores descriptor inheritance flags. These leases do not contain arbitrary descendants spawned by custom hooks.
+
+Cancellation does not release preparation ownership until native work actually returns. An orphan native child blocks another preparation and coordinated shutdown. A `preparing` record alone proves neither liveness nor completion. Settlement requires both parent and native preparation leases, revokes that generation and records `preparation_failed`; it neither deletes staging nor starts an install. Late children from the revoked generation cannot run. Older parent-only lease records cannot establish this proof. Retrying preparation must retain the same immutable plan; changed consent needs a new ID.
+
+The immutable `request.json`, written after inputs and initial status are flushed, is the preparation commit record. A `ready` journal alone is insufficient. Preparation grants no package-mutation authority.
+
+## Confirmation generations and offline execution
+
+The [job service](../nanobot/update_service.py) persists execution confirmation before launching a detached owner. Each confirmation may claim the operation once. Replaying execute, repeating a retry or presenting a stale predecessor returns history, not another attempt. Explicit retry replaces exactly `previous_confirmation_id` while worker and preflight leases are free; delayed launchers with the replaced confirmation cannot start. The original target, artifacts, plan expiry, release checks and selected runtime identities still apply. Retry cannot extend the review or repair mutation.
+
+Confirmation identity and expiry are separate checks. Launch consent is short-lived and bound to the immutable request. Under its lease, the supervisor validates that identity before publishing even its first journal or launching work. Completion and bounded recovery, including restoration, retain the same identity without reapplying the launch-window expiry. Fresh local repair can renew approval only for an already admitted exact job, not prepared files alone; it rechecks inputs and environment, preserves and verifies the original backup once created, and never resolves or downloads a release.
+
+The [offline worker](../nanobot/update_worker.py) uses the base Python with `-I -S`. Its actual installer child owns exclusive installation/data leases before target site initialization and rechecks ownership, environment, inputs and approval before mutation. Pip's CLI runs in that same single-use Python process on both POSIX and Windows, retaining locks through exit cleanup. It accepts only staged wheels with network resolution, builds and destination/configuration overrides disabled. Native uv retains its leases through POSIX `exec` and applies the sealed transaction offline.
+
+A pending-install fence and data reservation survive interrupted mutation. Repair cannot overwrite unrelated package changes or a different target installed by another updater. Restart-phase recovery retries restart, not installation. Installed-package verification uses a separately lease-owning child and a completion checkpoint: the target must import from the correct environment, application files including bundled assets must match the wheel, and dependency checks must pass. Without restart participants the result is `installed`, not a verified running gateway.
+
+## Shutdown and maintenance
+
+[Installation leases](../nanobot/installation_lock.py) are account-scoped by the real environment path, independent of profile home and symlink aliases. Cooperating runtimes hold shared OS locks; mutation needs exclusive access. Lock files must never be removed or replaced: a PID file is not ownership. Ordinary startup refuses an active updater or pending-install fence. These leases do not discover older runtimes, arbitrary imports, other accounts or external supervisors.
+
+The detached owner's [old-runtime preflight](../nanobot/update_handoff.py) owns a shared lease before application imports, revalidates the exact release using shared release history, closes the release client and requests [cooperative shutdown](../nanobot/update_stop.py). Every selected gateway must hold its idle admission gate before any stop is committed. Refusal before commit reopens intake; a durable commit is irrevocable and is not undone by a later failure. The owner waits for actual gateway and preflight process exit, not inactive receipts, before acquiring exclusive installation/data leases and admitting installation. Shutdown consent alone is not mutation approval.
+
+[Runtime admission](../nanobot/runtime_admission.py) accounts for accepted and detached work through cleanup without cancelling active tasks. Channel setup and provider sign-in owners must stay busy until native workers, callbacks and cleanup actually exit; cancelling an awaiter, expiring a flow or returning a QR/browser response does not establish idle. Failed cleanup retains ownership for retry. See the [connector lifecycle](../nanobot/channels/connect.py) and [sign-in registry](../nanobot/webui/settings_services.py). A loaded connector without that lifecycle cannot claim coordinated-update idleness.
+
+Handoff settlement requires free worker, preflight and stop-coordinator leases and refuses committed shutdown, installation admission or mutation. It records `cancelled` without deleting saved files or launching work; repeated settlement is safe. An uncertain response is resolved by reading the old job.
+
+## Data protection and protected restart
+
+[Profile receipts](../nanobot/update_profiles.py) preserve known stopped profiles for backup and retain original launch selectors, paths and process/run identities, not configuration contents or arbitrary environment variables. A PID alone is not liveness. A new run, changed inventory or unconfirmed owner invalidates review; inventory does not authorize stopping a supervisor or starting a previously stopped profile.
+
+[Data leases](../nanobot/data_access.py) protect overlapping named stores even across cooperating Python installations. Reservations bind the exact job and scope across crashes. [Backups](../nanobot/update_backup.py) cover recorded nanobot stores and required receipts, not entire homes, arbitrary projects or external services. Redirected paths, symlinks/reparse points, special files, changing data or insufficient space block backup. The original backup is verified and retained across retries, never replaced by post-mutation data. Automatic data rollback is unavailable.
+
+[Protected restart](../nanobot/update_restart.py) launches only reviewed participants through lease-owning frozen entrypoints using their saved selectors. A startup grant permits initialization of one participant's exact reserved data scope, not agent/tool/scheduler work or broader paths; its bearer is removed before normal runtime configuration. Grants cannot expand an older updater's reservation. For protocol-1 grants predating the lazy delivery store, that store takes an ordinary lease and cannot initialize, migrate or write before activation.
+
+Gateways remain in maintenance until their actual run identities, target versions and readiness are verified. Durable activation names those exact runs; a generic HTTP success or receipt is insufficient. Verification after intake opens precedes fence/reservation cleanup and `succeeded`. A crash during finalization resumes cleanup only, not reinstall or activation. Clients additionally require authenticated reconnection to the target-running gateway before reporting update completion.
+
+The optional macOS Dock helper belongs to the gateway, starts only after activation and exits when its owner stops. It holds no installation/data lease and is not loaded by the frozen updater or recovery supervisor. Its instance-scoped visibility intent survives reviewed restart/recovery; the helper does not own update execution or completion.
+
+## Recovery and compatibility limits
+
+For installer-owned dedicated venvs with selected background participants, [automatic recovery](../nanobot/update_fallback.py) preserves a verified sibling program/dependency snapshot before mutation. An independent supervisor can try the already admitted exact target once, then restore only the original program before candidate activation and only if protected user-file contents still match the original backup. Backup failure before mutation can restart the intact original program. Restoration uses journaled same-filesystem renames, retains the failed generation and replays one transient filesystem failure; duplicate launches do not gain another recovery budget.
+
+Restored service is not update success: the wire result remains `failed` for older clients and adds `service_restored`. Successful upgrades may remove their redundant program snapshot but retain the data backup. Changed data or durable activation forbids older-program restoration; only same-target completion remains safe. Corrupt snapshots, changed ownership, persistent filesystem faults, missing base Python or loss of both supervisor and worker can require operator recovery. This is neither malware remediation nor an OS boot-time recovery service.
+
+Compatibility is explicit, not inferred from versions. Protocol 1 covers worker request schema 4, frozen `-I -S` startup with child-owned installation leases, scoped data-startup grants and activation bound to the exact restarted run. The target must declare a supported protected-handoff contract; see [release compatibility](releasing.md#protected-updater-handoff-compatibility) for its schema and publication requirements. External managers, unsupported layouts and older jobs are not silently adopted. Hosts without settlement/retry capabilities retain their existing status/recovery route rather than accepting unsupported actions. The [standalone launcher](../nanobot/update_recovery.py) uses the saved worker and original base Python independently of a broken application environment; user commands and operational limits remain in the [update guide](updating.md).
diff --git a/docs/updating.md b/docs/updating.md
new file mode 100644
index 000000000..ebc3fa5e0
--- /dev/null
+++ b/docs/updating.md
@@ -0,0 +1,109 @@
+# Updating nanobot
+
+Use the update method that owns your installation. If your version does not include the WebUI updater, first upgrade through the original installer or package manager. This does not convert an existing installation into an installer-managed one.
+
+## Update from the WebUI
+
+1. Open the blue update entry in the sidebar or **Settings → About → Update**. Opening the dialog only checks the installation; it does not install or restart anything.
+2. Review the exact version and affected gateways. Active work must finish before shutdown. Gateways that were already stopped are not started by the update.
+3. Choose **Update & restart**. nanobot downloads and verifies the required files, backs up affected profiles, installs the update, and restarts the selected background gateways—not your computer or browser.
+4. Wait for **Update complete**, which requires a reconnected gateway running the target version. Choose **Done** to reload the updated interface. If you hide the dialog, reopen it through **Settings → About → View details**.
+
+Inline updates support fresh official-installer environments and compatible POSIX uv 0.11.16 registry tool installations running a background gateway. Other installations show their own update instructions in the dialog; see [Installation owners](#installation-owners). Remote browsers need the gateway's explicit package-install permission.
+
+On a local macOS desktop, the background WebUI's Dock icon stays available after closing the terminal and disappears when the gateway stops. A restarted or restored gateway recreates it after activation; it may disappear during package replacement and is not an update progress indicator. `--no-dock` remembers your choice for that instance. See the [Dock controls](webui.md#macos-dock-icon).
+
+Automatic installation requires official release approval and verified package checksums for both Stable and Preview. If verification fails, keep using the current version, retry later, and report persistent errors to a maintainer. Do not disable verification or install a replacement file from an error message. Verification confirms release approval; it is not a guarantee that all application or dependency code is harmless.
+
+## Stable and Preview
+
+**Settings → About → Receive preview updates** is off by default. Enable it to try new features earlier, with a higher risk of bugs. The preference applies to this installation, not just the browser; changing it requires the same local or remote permission as installing packages. It never downloads, installs, or restarts on its own.
+
+Turn it off to receive only stable updates. If your Preview is newer than the latest stable release, nanobot keeps it until a newer stable release is available; it does not downgrade or restore old data. Installing a final release while Preview is enabled keeps Preview enabled for the next development cycle. You can skip intermediate previews.
+
+Stable fixes can arrive between feature releases. Preview availability depends on verified publication, not a promise of daily updates. Package-manager commands outside nanobot do not read this preference; choose their version or channel explicitly.
+
+## Installation owners
+
+When inline installation is unavailable, the update dialog identifies the installation method and guides you through its update. Run copied commands **on the gateway computer, as the original installation account**. For containers, use the deployment host rather than treating a container path as a host path.
+
+| Installation | Update route |
+| --- | --- |
+| Fresh official installer | Use WebUI **Update & restart** for a compatible release. Existing unrecorded environments are not automatically adopted. |
+| uv registry tool | Use the supported inline flow above, or `uv tool upgrade nanobot-ai` in its original environment. Keep recorded extras, constraints and additional packages; a pin needs an explicitly reviewed new constraint. |
+| pipx | Use `pipx upgrade nanobot-ai` only for an unconstrained registry install without recorded pip options. Otherwise preserve the original requirement, index/options, suffix and injected packages through the owner's workflow. |
+| Ordinary pip venv | Use that environment's Python with `-m pip install --upgrade 'nanobot-ai[<your existing extras>]'`; omit brackets for the base package. Do not guess optional extras. |
+| Source checkout | Preserve local changes, update the selected ref and environment, and follow the [development instructions](../CONTRIBUTING.md). Source is not the Preview release channel. |
+| Docker / Compose | Pull or build the selected image and recreate the service with its existing data volumes. Do not pip-install into a running container. |
+| OS package, service manager or Desktop | Use the distributor or deployment's updater and launcher. |
+
+For an external update, stop all affected writers, back up configuration and data, update through the original installation method, then restart the same profiles through their original launcher. New versions may migrate stored data. Verify the **running** version in **About** and check that configuration and conversations remain available. Package-manager success alone does not verify the gateway, and manual updates do not inherit the managed updater's automatic recovery.
+
+Do not switch package managers to work around an error. Fixed wheel sources, locked requirements and custom installations need their original settings reviewed. If a fresh official installation fails, fix the reported prerequisite or network error and rerun the same installer command.
+
+## Recover an interrupted update
+
+Refreshing restores saved progress, **not installation consent**. A staged update may ask you to review and confirm it again. A disconnected page cannot tell whether the worker stopped: do not start another installation while it reconnects. Closing the browser does not stop the managed update or its recovery.
+
+**Check again** only reads saved status. **Review update** asks the gateway to settle an interrupted preparation or failed handoff before opening a fresh review. Settlement is refused while an owner is active or the operation has progressed too far to discard safely. It does not prepare or install another update; that requires a separate **Update & restart** confirmation.
+
+If settlement is refused or its response is lost, the saved job remains available for status checks and recovery. A timeout or missing response is not permission to create a second update. After package changes have begun, use recovery rather than trying another installation.
+
+## Automatic service recovery
+
+For installer-owned dedicated environments with supported background gateways, the update confirmation also authorizes bounded recovery of that exact operation. nanobot retains a separate copy of the original program and dependencies before changing packages; insufficient space aborts installation.
+
+If installation fails, recovery tries the already approved target once using saved files. If that also fails before the new gateway is activated, it can restore the original program and restart the reviewed gateways **only if protected user data is unchanged**. The dialog reports **Previous version restored**, not update success. A restored service needs a fresh review before another update.
+
+Recovery never replaces current configuration or conversations with an old backup. Changed user data, missing or corrupt saved files, changed installation ownership, persistent disk errors, a missing base Python, or loss of both recovery processes can require operator help. Keep the saved job and backup; do not delete recovery markers or install over them. This is not recovery after every power loss or a guarantee against malicious code. Other installation methods retain their original recovery route.
+
+## Standalone recovery
+
+When automatic recovery is unavailable or reports failure, the WebUI can show a repair command containing the saved job ID and exact Python and launcher paths. Copy that command and run it **on the gateway computer, as the original OS user**. It does not require a working nanobot environment, but it does need the original base Python.
+
+The following examples assume the gateway uses your terminal's normal home directory and a Python 3.11+ command. Prefer the exact paths shown by the WebUI when they differ.
+
+macOS / Linux:
+
+```sh
+python3 -I -S ~/.nanobot/updates/recover.py <job-id>
+python3 -I -S ~/.nanobot/updates/recover.py <job-id> --repair
+```
+
+Windows PowerShell:
+
+```powershell
+python -I -S "$env:USERPROFILE\.nanobot\updates\recover.py" <job-id>
+python -I -S "$env:USERPROFILE\.nanobot\updates\recover.py" <job-id> --repair
+```
+
+The first command only inspects the job. `--repair` shows its saved version, environment and backup, then asks for confirmation; `--yes` skips that prompt only when used with `--repair`. Repair reuses the same verified files without downloading another release. If installation finished but restart failed, it retries restart rather than reinstalling packages. Merely preparing files does not make a job eligible for repair.
+
+Keep the original job directory and backup until recovery is verified. Missing or changed files and an independently modified environment require operator repair. Do not restore backups over live data. Downgrading and restoring user data are separate, owner-managed operations.
+
+## Review an exact release
+
+```bash
+nanobot update --plan
+nanobot update --plan --channel preview
+```
+
+These commands save a plan showing the installation method, installed and running versions, exact target, download details and expected action. They may write plan and metadata-cache files, but do not install, stop tasks or restart gateways. `--channel` is a one-time inspection; it does not change your saved subscription.
+
+Plans expire after fifteen minutes. Execution rechecks the reviewed release and refuses changed installations, withdrawn releases or changed artifacts. A plan is not installation permission. The separate `nanobot update`, `--check` and `--dev` commands do not execute saved plans; see the [CLI reference](cli-reference.md#updating).
+
+## Explicit recovery before package mutation
+
+If shutdown failed **before package changes began** and the application environment is still intact, you can inspect the saved job and explicitly retry its reviewed operation:
+
+```bash
+nanobot update --job <plan-id>
+nanobot update --job <plan-id> --retry-handoff \
+ --previous-confirmation <execution-confirmation-id> --confirm-restart
+```
+
+Read the saved facts and original plan before running the second command: it approves shutdown, installation and restart, not just a connection check. The same plan must still be valid, and live owners prevent retry. An accepted request is not proof of completion; check the saved result and running gateway.
+
+These commands cannot repair a broken installation or packages already changed by an interrupted update. Use [standalone recovery](#standalone-recovery) instead.
+
+For contributor-facing APIs, ownership and execution rules, see [Update protocol](update-protocol.md). Maintainers should use the [release checklist](releasing.md).
diff --git a/docs/webui.md b/docs/webui.md
index 5e3ca5aa7..f9c8942ad 100644
--- a/docs/webui.md
+++ b/docs/webui.md
@@ -16,17 +16,17 @@ Use the launcher:
nanobot webui
```
-`nanobot webui` asks for one confirmation on a new installation, creates the config/workspace, enables the local WebSocket channel, and generates a WebUI bootstrap secret when one is missing. It starts or joins the same on-demand gateway used by the native TUI and opens the browser. With a fresh config, it can open before a model is configured so you can finish setup in **Settings → Models**. The first-run path binds the WebUI to `127.0.0.1` by default, so it is not available from other devices on your LAN. The startup summary groups the login link, model setup guidance, config, and exit controls with blank lines. While attached, the launcher displays new gateway warnings and errors; use the printed logs command for full output.
+`nanobot webui` asks for one confirmation on a new installation, creates the config/workspace, enables the local WebSocket channel, and generates a WebUI bootstrap secret when one is missing. It starts or joins the same gateway used by the native TUI and opens the browser. Fresh official-installer environments start it persistently and return control to the terminal; other installations keep the attached on-demand launch. With a fresh config, it can open before a model is configured so you can finish setup in **Settings → Models**. The first-run path binds the WebUI to `127.0.0.1` by default, so it is not available from other devices on your LAN. The startup summary groups the login link, model setup guidance, config, and exit controls with blank lines. While attached, the launcher displays new gateway warnings and errors; use the printed logs command for full output.
-After model setup, explicitly promote the shared gateway when you do not want to keep a client open:
+Outside an installer-managed environment, use `nanobot webui --detach` to open the browser and keep the gateway running after the terminal closes. Alternatively, start or promote the same shared gateway explicitly:
```bash
nanobot gateway --background
```
-`nanobot webui --background` is retained only to print migration guidance. This keeps one unambiguous owner for persistent process lifecycle.
+`nanobot webui --background` remains deprecated and prints migration guidance. All launch routes use the same gateway lifecycle owner and state.
-Each foreground WebUI or TUI launcher releases only its own client. The last interactive launcher stops an on-demand gateway. `nanobot gateway --background` makes the gateway persistent; manage it with `nanobot gateway status`, `nanobot gateway logs`, `nanobot gateway restart`, and `nanobot gateway stop`.
+Each foreground WebUI or TUI launcher releases only its own client. The last interactive launcher stops an on-demand gateway, but not a persistent one. Manage the persistent gateway with `nanobot gateway status`, `nanobot gateway logs`, `nanobot gateway restart`, and `nanobot gateway stop`. Use the printed instance-specific commands when you selected a custom config or workspace. `--detach --dev` is unsupported; development remains attached.
The browser signs in automatically using the generated credential in the launch URL. The terminal also prints the complete login link: if automatic opening fails, copy that link into your browser, including the fragment after `#`. In WSL, the launcher opens your Windows default browser through Windows PowerShell; an explicit `BROWSER` setting takes precedence. If Windows integration is unavailable, open the printed link in your Windows browser. The plain page address does not sign in a new browser. Treat the login link as a credential and do not share it.
@@ -56,6 +56,16 @@ Manual config still works. Same-machine localhost WebUI access can run without a
The WebUI is served by the WebSocket channel on port `8765` by default. The gateway health endpoint, `18790` by default, is not the browser UI.
+### macOS Dock icon
+
+In a local macOS desktop session, `nanobot webui` shows the nanobot cat in the Dock. Click it to open the current local WebUI in your default browser. `--no-open` keeps the icon but does not open a page automatically. SSH, headless, Windows and Linux launches keep their existing behavior. A one-shot connection to an unmanaged gateway does not leave an icon behind.
+
+Ordinary foreground launchers for the same instance, browser address and installation share an icon. The last WebUI launcher removes it when it exits, including after a terminal crash. For `--detach` and official-installer automatic background launch, the gateway owns the icon instead: closing the terminal does not remove it. An ordinary restart, successful update or supported automatic restoration shows it again once that gateway is activated. The icon can disappear while the service is stopped for an update; it is not an update-progress indicator. `nanobot gateway stop` removes it without changing configuration or chats.
+
+Use `--no-dock` to disable the icon for a launcher. In detached mode this also remembers the choice for that instance's later restarts; running `nanobot webui` without it enables the background icon again. The request is stored beside the runtime state as a small `.dock` file, without a URL or credentials. Choosing **Hide Dock Icon** or quitting the icon hides only this shortcut, not the gateway or its tasks. It stays hidden until another explicit launch or service restart. The icon is not a standalone launcher to keep pinned when nanobot is stopped.
+
+The helper uses the installed Python and macOS frameworks, with no Xcode, extra Python dependency, executable download or separate updater. Its temporary application wrapper is private to the OS user. The login URL stays in memory and a private socket, never in process arguments or a file. The helper holds no installation or data lease, and protected restart does not start it until activation. A missing image or unavailable desktop does not prevent WebUI startup, updates or independent recovery. Non-loopback browser addresses continue to use the normal browser launcher.
+
## Navigate a long conversation
On wide screens, use the message rail on the left to browse saved prompts; click one to jump to it. You can also search prompt summaries from the header. The WebUI loads messages near the selected prompt rather than the entire conversation. Scroll backward or forward to browse, or use the bottom arrow to return to the latest messages. If loading fails, your current content stays visible and you can retry. Older compatible hosts may only support navigation among messages that are already loaded.
diff --git a/hatch_build.py b/hatch_build.py
index 3bec76066..881621fdd 100644
--- a/hatch_build.py
+++ b/hatch_build.py
@@ -15,8 +15,8 @@ WebUI behavior:
- Skips when `NANOBOT_SKIP_WEBUI_BUILD=1` is set.
- Reuses `nanobot/web/dist/` only when it is already fresh, unless
`NANOBOT_FORCE_WEBUI_BUILD=1` is set.
-- Uses `bun` when available, otherwise falls back to `npm`. The chosen tool
- performs `install` followed by `run build`.
+- Uses `bun` when available, otherwise falls back to `npm`, or provisions Bun
+ when neither is available. Bun builds use `--bun` so Node is not required.
"""
from __future__ import annotations
diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.py
index 1b7a09d8d..ae1d56e99 100644
--- a/nanobot/agent/loop.py
+++ b/nanobot/agent/loop.py
@@ -65,6 +65,7 @@ from nanobot.events import NO_EVENTS, AgentEvent, EventSink
from nanobot.llm_usage.context import source_from_request
from nanobot.providers.base import LLMProvider, LLMUsage, ProviderConversationState
from nanobot.providers.factory import ProviderSnapshot
+from nanobot.runtime_admission import RuntimeMaintenanceError
from nanobot.runtime_context import (
RUNTIME_CONTEXT_HISTORY_META,
RUNTIME_CONTEXT_MESSAGE_META,
@@ -970,13 +971,14 @@ class AgentLoop:
async def discard_session(self, key: str) -> None:
"""Stop active work for *key* and forget its cached session."""
- self._discarding_sessions.add(key)
- try:
- await self.sessions.state.discard(key)
- await self._cancel_active_tasks(key)
- finally:
- self.discard_session_file_state(key)
- self._discarding_sessions.discard(key)
+ with self.bus.admission.activity():
+ self._discarding_sessions.add(key)
+ try:
+ await self.sessions.state.discard(key)
+ await self._cancel_active_tasks(key)
+ finally:
+ self.discard_session_file_state(key)
+ self._discarding_sessions.discard(key)
def discard_session_file_state(self, key: str) -> None:
"""Forget ephemeral file-read state for a reset or removed session."""
@@ -1393,16 +1395,19 @@ class AgentLoop:
async def _check_expired_sessions_if_due(self) -> None:
"""Scan idle sessions without blocking the event loop."""
+ if self.bus.admission.paused:
+ return
now = time.monotonic()
if now < self._next_idle_compact_check_at:
return
self._next_idle_compact_check_at = now + self._idle_compact_check_interval_s
try:
- await self.auto_compact.check_expired(
- self.schedule_background,
- self.runtime_for_session,
- active_session_keys=self._pending_queues.keys(),
- )
+ with self.bus.admission.activity():
+ await self.auto_compact.check_expired(
+ self.schedule_background,
+ self.runtime_for_session,
+ active_session_keys=self._pending_queues.keys(),
+ )
except SessionOperationQueueFullError:
logger.debug("Skipping idle archival while session storage is busy")
@@ -1414,7 +1419,10 @@ class AgentLoop:
while self._running:
try:
- msg = await asyncio.wait_for(self.bus.consume_inbound(), timeout=1.0)
+ # Keep dequeue and admission in this task. wait_for would
+ # dequeue in another task, leaving a false-idle handoff gap.
+ async with asyncio.timeout(1.0):
+ msg = await self.bus.consume_inbound()
except asyncio.TimeoutError:
await self._check_expired_sessions_if_due()
continue
@@ -1431,14 +1439,15 @@ class AgentLoop:
logger.warning("Error consuming inbound message: {}, continuing...", e)
continue
- try:
- await self._dispatch_inbound(msg)
- except (SessionOperationQueueFullError, SessionConflictError) as exc:
- key = self._effective_session_key(msg)
- logger.warning("Session input rejected for {}: {}", key, exc)
- if msg.is_user_input:
- delivery = self.turn_delivery_factory.unrouted(msg, key)
- await delivery.fail(publish_completion=key not in self._pending_queues)
+ with self.bus.admission.activity():
+ try:
+ await self._dispatch_inbound(msg)
+ except (SessionOperationQueueFullError, SessionConflictError) as exc:
+ key = self._effective_session_key(msg)
+ logger.warning("Session input rejected for {}: {}", key, exc)
+ if msg.is_user_input:
+ delivery = self.turn_delivery_factory.unrouted(msg, key)
+ await delivery.fail(publish_completion=key not in self._pending_queues)
finally:
await self.aclose()
@@ -1491,6 +1500,23 @@ class AgentLoop:
return
await self._enqueue_session_message(routed_msg)
+ def maintenance(self) -> AbstractContextManager[None]:
+ """Close task intake only when this runtime's accepted work is finished.
+
+ The gateway shares the bus gate with cron and local trigger intake.
+ This does not stop other processes or channel/configuration writes;
+ those must be shut down before an updater takes a data backup.
+ """
+ return self.bus.admission.pause_if_idle(self._has_pending_work)
+
+ def _has_pending_work(self) -> bool:
+ return bool(
+ self.bus.inbound_size or self._pending_queues or self._deferred_automation_turns
+ or self.bus.has_pending_events or self._active_tasks or self._background_tasks
+ or self._close_lock.locked()
+ or self.subagents.has_pending_work or self._exec_session_manager.has_pending_work
+ )
+
def preserve_inflight_turns_on_shutdown(self) -> None:
"""Keep durable checkpoints when the owning gateway exits.
@@ -1523,6 +1549,7 @@ class AgentLoop:
async def _enqueue_session_message(self, msg: InboundMessage) -> None:
"""Admit session work without waiting for its execution or result."""
+ self.bus.admission.check()
session_key = self._effective_session_key(msg)
if not self.subagents.accepts_result(msg, session_key):
return
@@ -1808,6 +1835,11 @@ class AgentLoop:
def schedule_background(self, coro: Coroutine[Any, Any, Any]) -> None:
"""Schedule a coroutine as a tracked background task (drained on shutdown)."""
+ try:
+ self.bus.admission.check()
+ except RuntimeMaintenanceError:
+ coro.close()
+ raise
task = asyncio.create_task(coro)
self._background_tasks.add(task)
task.add_done_callback(self._background_task_done)
@@ -2657,53 +2689,54 @@ class AgentLoop:
)
# Share the dispatch lock so direct calls serialize with bus turns.
lock = self._get_session_lock(session_key)
- temporary_parent = False
- try:
- async with lock:
- kwargs: dict[str, Any] = {
- "session_key": session_key,
- "on_progress": on_progress,
- "on_stream": on_stream,
- "on_stream_end": on_stream_end,
- "ephemeral": ephemeral,
- }
- if _session_policy is not None:
- # Isolate per-run state before any early save or checkpoint;
- # the cached conversation must survive a temporary SDK turn.
- session = (await self.sessions.state.read(session_key) or Session(key=session_key)
- if not _session_policy.persist
- else await self.sessions.state.get(session_key))
- temporary_parent = not _session_policy.persist and not session.persisted
- session.policy = SessionPolicy(
- persist=session.policy.persist and _session_policy.persist,
- log_content=session.policy.log_content and _session_policy.log_content,
- disabled_tools=session.policy.disabled_tools | _session_policy.disabled_tools,
- )
- kwargs["session"] = session
- if _run_extra_hooks_for_ephemeral:
- kwargs["run_extra_hooks_for_ephemeral"] = True
- if hooks is not None:
- kwargs["hooks"] = hooks
- if hook_factories is not None:
- kwargs["hook_factories"] = hook_factories
- if tools is not None:
- kwargs["tools"] = tools
- if runtime is not None:
- kwargs["runtime"] = runtime
- if on_runtime_admitted is not None:
- kwargs["on_runtime_admitted"] = on_runtime_admitted
- if attributes is not None:
- kwargs["attributes"] = dict(attributes)
- try:
- return await self._process_message(msg, **kwargs)
- finally:
- if temporary_parent:
- parent = self.sessions.state.peek_header(session_key)
- if parent is not None and not parent.policy.persist:
- await self.sessions.state.delete(session_key, expected_generation=parent.generation)
- finally:
- await self.runtime_event_publisher.run_status_changed(msg, session_key, "idle")
- self.runtime_event_publisher.clear_turn(session_key)
+ with self.bus.admission.activity():
+ temporary_parent = False
+ try:
+ async with lock:
+ kwargs: dict[str, Any] = {
+ "session_key": session_key,
+ "on_progress": on_progress,
+ "on_stream": on_stream,
+ "on_stream_end": on_stream_end,
+ "ephemeral": ephemeral,
+ }
+ if _session_policy is not None:
+ # Isolate per-run state before any early save or checkpoint;
+ # the cached conversation must survive a temporary SDK turn.
+ session = (await self.sessions.state.read(session_key) or Session(key=session_key)
+ if not _session_policy.persist
+ else await self.sessions.state.get(session_key))
+ temporary_parent = not _session_policy.persist and not session.persisted
+ session.policy = SessionPolicy(
+ persist=session.policy.persist and _session_policy.persist,
+ log_content=session.policy.log_content and _session_policy.log_content,
+ disabled_tools=session.policy.disabled_tools | _session_policy.disabled_tools,
+ )
+ kwargs["session"] = session
+ if _run_extra_hooks_for_ephemeral:
+ kwargs["run_extra_hooks_for_ephemeral"] = True
+ if hooks is not None:
+ kwargs["hooks"] = hooks
+ if hook_factories is not None:
+ kwargs["hook_factories"] = hook_factories
+ if tools is not None:
+ kwargs["tools"] = tools
+ if runtime is not None:
+ kwargs["runtime"] = runtime
+ if on_runtime_admitted is not None:
+ kwargs["on_runtime_admitted"] = on_runtime_admitted
+ if attributes is not None:
+ kwargs["attributes"] = dict(attributes)
+ try:
+ return await self._process_message(msg, **kwargs)
+ finally:
+ if temporary_parent:
+ parent = self.sessions.state.peek_header(session_key)
+ if parent is not None and not parent.policy.persist:
+ await self.sessions.state.delete(session_key, expected_generation=parent.generation)
+ finally:
+ await self.runtime_event_publisher.run_status_changed(msg, session_key, "idle")
+ self.runtime_event_publisher.clear_turn(session_key)
def _get_session_lock(self, session_key: str) -> asyncio.Lock:
"""Return the shared lock while allowing idle session entries to expire."""
diff --git a/nanobot/agent/subagent.py b/nanobot/agent/subagent.py
index 084899127..20d9d177f 100644
--- a/nanobot/agent/subagent.py
+++ b/nanobot/agent/subagent.py
@@ -544,6 +544,7 @@ class SubagentManager:
runtime: LLMRuntime | None, *, announce: bool, origin_turn_id: str | None,
session_policy: SessionPolicy | None,
) -> _SubagentTask:
+ self.bus.admission.check()
if runtime is None:
runtime = self._compat_spawn_runtime()
if temperature is not None:
@@ -1003,6 +1004,11 @@ class SubagentManager:
"""Return the number of currently running subagents."""
return len(self._running_tasks)
+ @property
+ def has_pending_work(self) -> bool:
+ """Completed turns may still own exec cleanup, including failed cleanup."""
+ return bool(self._tasks) or self._exec_session_manager.has_pending_work
+
def get_running_count_by_session(self, session_key: str) -> int:
"""Return the number of currently running subagents for a session."""
return sum(
diff --git a/nanobot/agent/tools/exec_session.py b/nanobot/agent/tools/exec_session.py
index dce775e88..6e4022ece 100644
--- a/nanobot/agent/tools/exec_session.py
+++ b/nanobot/agent/tools/exec_session.py
@@ -238,7 +238,10 @@ class _ExecSession:
finally:
stopped.cancel()
await asyncio.gather(stopped, return_exceptions=True)
- from nanobot.agent.tools.shell import ExecTool, _reap_pid # pyright: ignore[reportPrivateUsage]
+ from nanobot.agent.tools.shell import (
+ ExecTool,
+ _reap_pid, # pyright: ignore[reportPrivateUsage]
+ )
ExecTool._release_process_tree(self.process) # pyright: ignore[reportPrivateUsage]
_reap_pid(self.process.pid)
@@ -253,6 +256,18 @@ class _ExecSession:
self._state_changed.clear()
await self._state_changed.wait()
+ @property
+ def has_pending_work(self) -> bool:
+ """Include pipe draining and failed/in-flight process-tree cleanup."""
+ cleanup = self._kill_task
+ return (
+ self.finished_at is None
+ or not self._stdout_task.done() or not self._stderr_task.done()
+ or (cleanup is not None and (
+ not cleanup.done() or cleanup.cancelled() or cleanup.exception() is not None
+ ))
+ )
+
async def _watch_timeout(self) -> None:
"""Supervise execution budgets independently of tool waits and log reads."""
while not self._completion_task.done():
@@ -371,13 +386,16 @@ class _ExecSession:
await asyncio.shield(self._completion_task)
async def _begin_stop(self, reason: FinishReason) -> None:
- if self.finished_at is not None:
+ if not self.has_pending_work:
return
if self._execution_exited and self._stop_reason is None:
return
if self._stop_reason is None:
self._stop_reason = reason
- if self._kill_task is None:
+ if self._kill_task is None or (
+ self._kill_task.done()
+ and (self._kill_task.cancelled() or self._kill_task.exception() is not None)
+ ):
self.cleanup_error = None
self._kill_task = asyncio.create_task(self._kill())
self._kill_task.add_done_callback(self._on_kill_done)
@@ -391,8 +409,8 @@ class _ExecSession:
logger.opt(exception=error if tool_log_content_allowed() else False).error(
"Failed to terminate exec session {}", self.session_id,
)
- if (task.cancelled() or error is not None) and self._kill_task is task:
- self._kill_task = None
+ # Retain failed cleanup as unsettled work, even if the parent exited.
+ # kill() replaces it on an explicit retry.
async def _kill(self) -> None:
from nanobot.agent.tools.shell import ExecTool
@@ -410,9 +428,18 @@ class ExecSessionManager:
self.result_retention = result_retention
self._sessions: dict[str, _ExecSession] = {}
self._starting: dict[str, tuple[str | None, asyncio.Task[_ExecSession]]] = {}
+ self._stopping_launches: set[asyncio.Task[_ExecSession]] = set()
self._lock = asyncio.Lock()
self._closed = False
+ @property
+ def has_pending_work(self) -> bool:
+ """Inspect owned work without polling, terminating or removing sessions."""
+ return bool(
+ self._lock.locked() or self._starting or self._stopping_launches
+ or any(s.has_pending_work for s in self._sessions.values())
+ )
+
async def start(
self,
*,
@@ -574,7 +601,6 @@ class ExecSessionManager:
async with self._lock:
self._closed = True
sessions: list[_ExecSession] = list(self._sessions.values())
- self._sessions.clear()
launches = [task for _, task in self._starting.values()]
self._starting.clear()
return await self._stop_owned(sessions, launches, "shutdown")
@@ -583,9 +609,9 @@ class ExecSessionManager:
"""Terminate all sessions owned by owner_session_key. Returns count."""
async with self._lock:
victims: list[_ExecSession] = []
- for sid, s in list(self._sessions.items()):
+ for s in self._sessions.values():
if s.owner_session_key == owner_session_key:
- victims.append(self._sessions.pop(sid))
+ victims.append(s)
launches = [
task for owner, task in self._starting.values() if owner == owner_session_key
]
@@ -598,6 +624,10 @@ class ExecSessionManager:
self, sessions: list[_ExecSession], launches: list[asyncio.Task[_ExecSession]],
reason: FinishReason,
) -> int:
+ # Removed startup reservations must stay visible until cancellation drains.
+ self._stopping_launches.update(launches)
+ for task in launches:
+ task.add_done_callback(self._stopping_launches.discard)
results: list[None | BaseException] = list(await asyncio.gather(
*(session.kill(reason) for session in sessions),
self._cancel_launches(launches),
@@ -609,10 +639,10 @@ class ExecSessionManager:
for session, result in zip(sessions, results, strict=True)
if isinstance(result, BaseException)
]
- if failures:
- async with self._lock:
- for session, _ in failures:
- self._sessions[session.session_id] = session
+ async with self._lock:
+ for session, result in zip(sessions, results, strict=True):
+ if not isinstance(result, BaseException):
+ self._sessions.pop(session.session_id, None)
errors = [result for _, result in failures]
if isinstance(startup_error, BaseException):
errors.append(startup_error)
diff --git a/nanobot/bun.py b/nanobot/bun.py
new file mode 100644
index 000000000..ebf04f6a7
--- /dev/null
+++ b/nanobot/bun.py
@@ -0,0 +1,122 @@
+"""Provision the Bun runtime used by source installations and package builds."""
+
+from __future__ import annotations
+
+import hashlib
+import io
+import os
+import platform
+import shutil
+import subprocess
+import tempfile
+import urllib.request
+import zipfile
+from collections.abc import Callable, Generator
+from contextlib import contextmanager
+from pathlib import Path
+
+from filelock import FileLock
+
+BUN_VERSION = "1.3.13"
+# SHA-256 of the official bun-v1.3.13 release archives.
+_ARCHIVES = {
+ "linux-x64-baseline": "9d8a24292a7068090205daac0a5a223f5f69736f5287e37bf88d3b4031edc750",
+ "linux-x64-musl-baseline": "88ca7c7ad235b498f549eea2f770f434e9f0f5e9ba95168a2d3a1f235184c394",
+ "linux-aarch64": "70bae41b3908b0a120e1e58c5c8af30e74afae3b8d11b0d3fdd8e787ddfb4b22",
+ "linux-aarch64-musl": "5385e978107ce4934298d8d6afe9bfbb898683f6cc23e6753a0da60bc60c5b81",
+ "darwin-x64-baseline": "a98ba6a480f22fda9b343626b906a4e26aa53618bf85d2bc5928ecf2ba45f0ed",
+ "darwin-aarch64": "5467e3f65dba526b9fea98f0cce04efafc0c63e169733ec27b876a3ad32da190",
+ "windows-x64-baseline": "c68c7903c1190101590cc1b2129835f47211b3b37ae87759f2b97d6534aa3ad1",
+}
+
+
+class BunUnavailableError(RuntimeError):
+ """The required runtime could not be prepared for this platform."""
+
+
+@contextmanager
+def bun_environment(executable: str) -> Generator[dict[str, str]]:
+ """Run lifecycle scripts' `node` commands with Bun, without a global Node shim."""
+ env = os.environ.copy()
+ runtime = Path(shutil.which(executable) or executable).resolve()
+ if os.name == "nt" and runtime.suffix.lower() in {".cmd", ".bat"}:
+ runtime = Path(subprocess.check_output(
+ [str(runtime), "-p", "process.execPath"], text=True, timeout=10,
+ ).strip())
+ # `bun --bun install` does not alias node in dependency lifecycle scripts.
+ # Only this subprocess tree sees the alias; Windows hardlinks need no admin rights.
+ with tempfile.TemporaryDirectory(prefix="nanobot-bun-") as temporary:
+ node = Path(temporary) / ("node.exe" if os.name == "nt" else "node")
+ try:
+ node.hardlink_to(runtime)
+ except OSError:
+ shutil.copy2(runtime, node)
+ env["PATH"] = os.pathsep.join((temporary, str(runtime.parent), env.get("PATH", "")))
+ yield env
+
+
+def _matches_version(executable: str) -> bool:
+ try:
+ result = subprocess.run(
+ [executable, "--version"], capture_output=True, text=True, timeout=10,
+ )
+ return result.returncode == 0 and result.stdout.strip() == BUN_VERSION
+ except (OSError, subprocess.TimeoutExpired):
+ return False
+
+
+def _target() -> str:
+ system = {"Linux": "linux", "Darwin": "darwin", "Windows": "windows"}.get(
+ platform.system(), "unknown",
+ )
+ arch = {"x86_64": "x64", "amd64": "x64", "arm64": "aarch64", "aarch64": "aarch64"}.get(
+ platform.machine().lower(), "unknown",
+ )
+ musl = system == "linux" and (
+ platform.libc_ver()[0] == "musl" or any(Path("/lib").glob("ld-musl-*.so.1"))
+ )
+ target = f"{system}-{arch}" + ("-musl" if musl else "")
+ if arch == "x64":
+ target += "-baseline"
+ if target not in _ARCHIVES:
+ raise BunUnavailableError(f"Automatic Bun setup is not supported on {system}/{arch}.")
+ return target
+
+
+def ensure_bun(
+ *, cache_dir: Path | None = None, output: Callable[[str], None] = print,
+) -> str:
+ """Return the pinned runtime, downloading a verified executable when missing."""
+ existing = shutil.which("bun")
+ if existing and _matches_version(existing):
+ return existing
+ target = _target()
+ root = cache_dir or Path.home() / ".nanobot" / "tools" / "bun"
+ directory = root / BUN_VERSION / target
+ executable = directory / ("bun.exe" if os.name == "nt" else "bun")
+ directory.mkdir(parents=True, exist_ok=True)
+ with FileLock(str(directory / "install.lock"), timeout=180):
+ if executable.is_file() and _matches_version(str(executable)):
+ return str(executable)
+ output(f"Downloading Bun {BUN_VERSION} ({target})…")
+ url = f"https://github.com/oven-sh/bun/releases/download/bun-v{BUN_VERSION}/bun-{target}.zip"
+ try:
+ with urllib.request.urlopen(url, timeout=60) as response:
+ raw = response.read(128 * 1024 * 1024 + 1)
+ if hashlib.sha256(raw).hexdigest() != _ARCHIVES[target]:
+ raise BunUnavailableError("Bun download failed checksum verification. Retry the download.")
+ with zipfile.ZipFile(io.BytesIO(raw)) as archive:
+ member = archive.getinfo(f"bun-{target}/{executable.name}")
+ if member.file_size > 256 * 1024 * 1024:
+ raise BunUnavailableError("Bun archive contains an oversized executable.")
+ content = archive.read(member)
+ with tempfile.TemporaryDirectory(prefix=".install-", dir=directory) as temporary:
+ candidate = Path(temporary) / executable.name
+ candidate.write_bytes(content)
+ candidate.chmod(0o755)
+ if not _matches_version(str(candidate)):
+ raise BunUnavailableError("Downloaded Bun cannot run on this system.")
+ os.replace(candidate, executable)
+ except (OSError, ValueError, KeyError, zipfile.BadZipFile) as exc:
+ raise BunUnavailableError(f"Could not prepare Bun {BUN_VERSION}: {exc}") from exc
+ return str(executable)
diff --git a/nanobot/bus/queue.py b/nanobot/bus/queue.py
index 8a344a82a..cfe216e1c 100644
--- a/nanobot/bus/queue.py
+++ b/nanobot/bus/queue.py
@@ -11,6 +11,7 @@ from loguru import logger
from nanobot.bus.events import InboundMessage, OutboundMessage
from nanobot.bus.outbound_events import outbound_message_for_event
from nanobot.events import AgentEvent
+from nanobot.runtime_admission import RuntimeAdmission
_EventT = TypeVar("_EventT", bound=AgentEvent)
EventHandler = Callable[[AgentEvent], Awaitable[None] | None]
@@ -28,7 +29,8 @@ class MessageBus:
``publish_event``. Local state transitions never wait for network sends.
"""
- def __init__(self):
+ def __init__(self, *, admission: RuntimeAdmission | None = None):
+ self.admission = admission if admission is not None else RuntimeAdmission()
self.inbound: asyncio.Queue[InboundMessage] = asyncio.Queue()
self.outbound: asyncio.Queue[OutboundMessage] = asyncio.Queue()
self._handlers: list[EventHandler] = []
@@ -37,7 +39,9 @@ class MessageBus:
async def publish_inbound(self, msg: InboundMessage) -> None:
"""Publish a message from a channel to the agent."""
- await self.inbound.put(msg)
+ self.admission.check()
+ # This queue is unbounded. Admission and enqueue must not yield apart.
+ self.inbound.put_nowait(msg)
async def consume_inbound(self) -> InboundMessage:
"""Consume the next inbound message (blocks until available)."""
@@ -81,6 +85,11 @@ class MessageBus:
"""Number of pending outbound messages."""
return self.outbound.qsize()
+ @property
+ def has_pending_events(self) -> bool:
+ """Scheduled local subscribers may still start agent background work."""
+ return bool(self._pending)
+
@overload
def subscribe(
self, handler: Callable[[_EventT], Awaitable[None] | None],
diff --git a/nanobot/channels/base.py b/nanobot/channels/base.py
index a9466c46e..ea4a6dde2 100644
--- a/nanobot/channels/base.py
+++ b/nanobot/channels/base.py
@@ -107,6 +107,16 @@ class BaseChannel(ABC):
"""
pass
+ @property
+ def has_pending_delivery(self) -> bool:
+ """Whether delivery outlives an awaited ``send``/streaming call.
+
+ The manager already accounts for awaited sends and retries. Channels
+ that enqueue their own writes must expose that work here, including
+ transport cleanup, before a gateway can be considered idle.
+ """
+ return False
+
def progress_transport_defaults(self) -> tuple[bool, bool] | None:
"""Return channel-owned defaults for progress and tool-hint messages.
diff --git a/nanobot/channels/connect.py b/nanobot/channels/connect.py
index 92d411e78..96850a593 100644
--- a/nanobot/channels/connect.py
+++ b/nanobot/channels/connect.py
@@ -3,10 +3,32 @@
from __future__ import annotations
from collections.abc import Mapping
+from typing import Any, Protocol, runtime_checkable
QueryParams = Mapping[str, list[str]]
+class ChannelConnector(Protocol):
+ """Channel-owned setup actions called by the settings request owner."""
+
+ async def handle(self, action: str, query: QueryParams) -> dict[str, Any]: ...
+
+
+@runtime_checkable
+class ManagedChannelConnector(ChannelConnector, Protocol):
+ """Setup whose detached work can participate in gateway maintenance.
+
+ The synchronous property must stay true through awaited cleanup. ``close``
+ returns only after owned writers have stopped; failure retains ownership.
+ Settings requests account for their own awaited work separately.
+ """
+
+ @property
+ def has_pending_work(self) -> bool: ...
+
+ async def close(self) -> None: ...
+
+
class ChannelConnectError(Exception):
"""User-facing channel connection failure."""
@@ -21,4 +43,6 @@ def query_first(query: QueryParams, key: str) -> str | None:
return values[0] if values else None
-__all__ = ["ChannelConnectError", "QueryParams", "query_first"]
+__all__ = [
+ "ChannelConnectError", "ChannelConnector", "ManagedChannelConnector", "QueryParams", "query_first",
+]
diff --git a/nanobot/channels/feishu/connect.py b/nanobot/channels/feishu/connect.py
index b41e57fae..14e9fa5df 100644
--- a/nanobot/channels/feishu/connect.py
+++ b/nanobot/channels/feishu/connect.py
@@ -46,6 +46,20 @@ class FeishuConnectStore:
self._sessions: dict[str, FeishuConnectSession] = {}
self._completion_lock = threading.Lock()
+ @property
+ def has_pending_work(self) -> bool:
+ # Registration only advances inside an owned settings request. Expired
+ # QR records have no listener or detached writer to keep alive.
+ now = time.monotonic()
+ return any(session.deadline > now for session in tuple(self._sessions.values()))
+
+ async def close(self) -> None:
+ def clear() -> None:
+ with self._completion_lock:
+ self._sessions.clear()
+
+ await asyncio.to_thread(clear)
+
async def handle(self, action: str, query: QueryParams) -> dict[str, Any]:
"""Handle one generic settings connection action."""
if action == "start":
diff --git a/nanobot/channels/feishu/tests/test_connect.py b/nanobot/channels/feishu/tests/test_connect.py
index 433a8db0b..67f8884f2 100644
--- a/nanobot/channels/feishu/tests/test_connect.py
+++ b/nanobot/channels/feishu/tests/test_connect.py
@@ -11,8 +11,10 @@ from nanobot.channels.feishu.connect import FeishuConnectStore
@pytest.mark.asyncio
[email protected]("shutdown", [False, True])
async def test_feishu_cancel_wins_over_inflight_confirmation(
monkeypatch: pytest.MonkeyPatch,
+ shutdown: bool,
) -> None:
poll_started = threading.Event()
release_poll = threading.Event()
@@ -52,15 +54,20 @@ async def test_feishu_cancel_wins_over_inflight_confirmation(
store = FeishuConnectStore()
started = await store.handle("start", {})
+ assert store.has_pending_work is True
query = {"session_id": [started["session_id"]]}
poll_task = asyncio.create_task(store.handle("poll", query))
assert await asyncio.to_thread(poll_started.wait, 5)
- cancelled = await store.handle("cancel", query)
+ if shutdown:
+ await store.close()
+ else:
+ cancelled = await store.handle("cancel", query)
+ assert cancelled["status"] == "cancelled"
release_poll.set()
completed = await poll_task
- assert cancelled["status"] == "cancelled"
+ assert store.has_pending_work is False
assert completed["status"] == "cancelled"
assert saved_results == []
diff --git a/nanobot/channels/linear/connect.py b/nanobot/channels/linear/connect.py
index ced9e8713..d69c3a39d 100644
--- a/nanobot/channels/linear/connect.py
+++ b/nanobot/channels/linear/connect.py
@@ -28,9 +28,10 @@ class LinearConnectSession:
flow: LinearOAuthFlow
config: LinearConfig
state: LinearStateStore
- server: LinearServerLease
+ server: LinearServerLease | None
completion_lock: asyncio.Lock = field(default_factory=asyncio.Lock, repr=False)
result: dict[str, Any] | None = None
+ expiry_task: asyncio.Task[None] | None = None
class LinearConnectStore:
@@ -39,6 +40,16 @@ class LinearConnectStore:
def __init__(self) -> None:
self._sessions: dict[str, LinearConnectSession] = {}
+ @property
+ def has_pending_work(self) -> bool:
+ # A deadline alone does not close the callback/webhook listener. Cached
+ # success, however, is retained only after releasing that listener.
+ return any(session.server is not None for session in self._sessions.values())
+
+ async def close(self) -> None:
+ for session_id in tuple(self._sessions):
+ await self.cancel(session_id)
+
async def handle(self, action: str, query: QueryParams) -> dict[str, Any]:
await self._cleanup()
if action == "start":
@@ -103,12 +114,19 @@ class LinearConnectStore:
f"Unable to start the Linear callback listener on {config.host}:{config.port}: {exc}",
status=502,
) from exc
- self._sessions[flow.session_id] = LinearConnectSession(
+ session = LinearConnectSession(
flow=flow,
config=config,
state=state,
server=lease,
)
+ self._sessions[flow.session_id] = session
+ session.expiry_task = asyncio.create_task(
+ self._expire_session(session), name=f"linear-connect-expire-{flow.session_id}",
+ )
+ session.expiry_task.add_done_callback(
+ lambda task: task.exception() if not task.cancelled() else None,
+ )
return {
"session_id": flow.session_id,
"status": "pending",
@@ -129,6 +147,7 @@ class LinearConnectStore:
if self._sessions.get(session_id) is not session:
return _terminal(session_id, "cancelled", "Linear authorization cancelled.")
if session.result is not None:
+ await self._release_listener(session)
return dict(session.result)
flow = session.flow
if time.monotonic() >= flow.deadline:
@@ -169,8 +188,7 @@ class LinearConnectStore:
}
# A browser may miss the first successful poll while switching tabs.
# Retain its result until the session expires, but release the callback listener.
- OAUTH_FLOWS.remove(flow)
- await asyncio.to_thread(session.server.close)
+ await self._release_listener(session)
return dict(session.result)
async def cancel(self, session_id: str) -> dict[str, Any]:
@@ -291,11 +309,26 @@ class LinearConnectStore:
await self.cancel(session_id)
async def _close_session(self, session_id: str) -> None:
- session = self._sessions.pop(session_id, None)
+ session = self._sessions.get(session_id)
if session is None:
return
+ expiry_task = session.expiry_task
+ if expiry_task is not None and expiry_task is not asyncio.current_task():
+ expiry_task.cancel()
+ await asyncio.gather(expiry_task, return_exceptions=True)
+ await self._release_listener(session)
+ self._sessions.pop(session_id, None)
+
+ async def _expire_session(self, session: LinearConnectSession) -> None:
+ await asyncio.sleep(max(0, session.flow.deadline - time.monotonic()))
+ await self.cancel(session.flow.session_id)
+
+ @staticmethod
+ async def _release_listener(session: LinearConnectSession) -> None:
OAUTH_FLOWS.remove(session.flow)
- await asyncio.to_thread(session.server.close)
+ if session.server is not None:
+ await asyncio.to_thread(session.server.close)
+ session.server = None
def _load_linear_config() -> LinearConfig:
diff --git a/nanobot/channels/linear/server.py b/nanobot/channels/linear/server.py
index 1d0992627..4415d27f0 100644
--- a/nanobot/channels/linear/server.py
+++ b/nanobot/channels/linear/server.py
@@ -37,7 +37,8 @@ class LinearWebhookError(ValueError):
class _ReusableThreadingHTTPServer(ThreadingHTTPServer):
allow_reuse_address = True
- daemon_threads = True
+ # server_close() must join request writers, not only stop accepting sockets.
+ daemon_threads = False
class SharedLinearHttpServer:
@@ -65,6 +66,10 @@ class SharedLinearHttpServer:
class Handler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
+ def setup(self) -> None:
+ super().setup()
+ self.connection.settimeout(5)
+
def do_GET(self) -> None: # noqa: N802
parsed = urlparse(self.path)
if parsed.path == owner.config.oauth_callback_path:
@@ -99,6 +104,7 @@ class SharedLinearHttpServer:
self.send_response(status.value)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(body)))
+ self.send_header("Connection", "close")
self.send_header("Cache-Control", "no-store")
self.send_header("X-Content-Type-Options", "nosniff")
self.end_headers()
@@ -124,7 +130,7 @@ class SharedLinearHttpServer:
self._server.server_close()
self._server = None
if self._thread is not None and self._thread.is_alive():
- self._thread.join(timeout=2)
+ self._thread.join()
self._thread = None
def _handle_oauth_callback(
@@ -192,10 +198,11 @@ class LinearServerLease:
self._closed = False
def close(self) -> None:
- if self._closed:
- return
- self._closed = True
- _release_server(self._server)
+ with _SERVER_GUARD:
+ if self._closed:
+ return
+ _release_server(self._server)
+ self._closed = True
_SERVER_GUARD = threading.RLock()
@@ -222,10 +229,10 @@ def _release_server(server: SharedLinearHttpServer) -> None:
with _SERVER_GUARD:
if _shared_server is not server:
return
- server._references -= 1 # pyright: ignore[reportPrivateUsage]
- if server._references <= 0: # pyright: ignore[reportPrivateUsage]
+ if server._references == 1: # pyright: ignore[reportPrivateUsage]
server.close()
_shared_server = None
+ server._references -= 1 # pyright: ignore[reportPrivateUsage]
def _handler_response(
@@ -237,6 +244,7 @@ def _handler_response(
handler.send_response(status.value)
handler.send_header("Content-Type", content_type)
handler.send_header("Content-Length", str(len(body)))
+ handler.send_header("Connection", "close")
handler.send_header("Cache-Control", "no-store")
handler.send_header("X-Content-Type-Options", "nosniff")
handler.end_headers()
diff --git a/nanobot/channels/linear/tests/test_linear.py b/nanobot/channels/linear/tests/test_linear.py
index c4f3a6cc8..7b3160f63 100644
--- a/nanobot/channels/linear/tests/test_linear.py
+++ b/nanobot/channels/linear/tests/test_linear.py
@@ -6,6 +6,7 @@ import hmac
import http.client
import json
import socket
+import threading
import time
from dataclasses import replace
from datetime import datetime, timezone
@@ -287,12 +288,14 @@ def test_oauth_callback_does_not_report_cancelled_authorization_as_connected(
lease.close()
[email protected]("concurrent", [False, True])
[email protected]("concurrent, close_fails_once", [(False, False), (True, False), (False, True)])
async def test_successful_authorization_survives_repeated_polls(
- tmp_path: Path, monkeypatch: pytest.MonkeyPatch, concurrent: bool,
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, concurrent: bool, close_fails_once: bool,
) -> None:
state = LinearStateStore(tmp_path / "linear.sqlite3")
lease = Mock(spec=LinearServerLease)
+ if close_fails_once:
+ lease.close.side_effect = [RuntimeError("listener close failed"), None]
async def exchange_code(_code: str, _verifier: str) -> LinearInstallation:
await asyncio.sleep(0)
@@ -310,11 +313,16 @@ async def test_successful_authorization_survives_repeated_polls(
store = linear_connect.LinearConnectStore()
started_at = time.monotonic()
started = await store.handle("start", {})
+ assert store.has_pending_work is True
session_id = started["session_id"]
query = {"session_id": [session_id]}
oauth_state = parse_qs(urlparse(started["authorization_url"]).query)["state"][0]
try:
assert OAUTH_FLOWS.complete(oauth_state, code="authorization-code", error=None)
+ if close_fails_once:
+ with pytest.raises(RuntimeError, match="listener close failed"):
+ await store.handle("poll", query)
+ assert store.has_pending_work is True
if concurrent:
first, repeated = await asyncio.gather(
store.handle("poll", query), store.handle("poll", query),
@@ -323,11 +331,12 @@ async def test_successful_authorization_survives_repeated_polls(
first = await store.handle("poll", query)
repeated = await store.handle("poll", query)
assert first["status"] == "succeeded"
+ assert store.has_pending_work is False
assert repeated == first
assert (await store.handle("poll", query)) == first
assert state.has_installations("client-id")
client.exchange_code.assert_awaited_once()
- lease.close.assert_called_once()
+ assert lease.close.call_count == (2 if close_fails_once else 1)
assert (await store.handle("poll", {"session_id": ["unknown"]}))["status"] == "expired"
monkeypatch.setattr(
@@ -340,6 +349,73 @@ async def test_successful_authorization_survives_repeated_polls(
await store.cancel(session_id)
+async def test_connect_shutdown_joins_real_webhook_writer(tmp_path, monkeypatch) -> None:
+ port = _free_port()
+ state = LinearStateStore(tmp_path / "linear.sqlite3")
+ write_entered, allow_write, listener_stopped = threading.Event(), threading.Event(), threading.Event()
+ enqueue = state.enqueue_webhook
+ monkeypatch.setattr(linear_connect, "_load_linear_config", lambda: _config(port))
+ monkeypatch.setattr(linear_connect, "LinearStateStore", lambda: state)
+
+ def enqueue_after_release(delivery, payload):
+ write_entered.set()
+ assert allow_write.wait(3)
+ return enqueue(delivery, payload)
+
+ monkeypatch.setattr(state, "enqueue_webhook", enqueue_after_release)
+ store = linear_connect.LinearConnectStore()
+ started = await store.start()
+ lease = store._sessions[started["session_id"]].server
+ server = lease._server._server
+ shutdown_listener = server.shutdown
+
+ def shutdown_and_signal():
+ shutdown_listener()
+ listener_stopped.set()
+
+ monkeypatch.setattr(server, "shutdown", shutdown_and_signal)
+ request = asyncio.create_task(asyncio.to_thread(_post_webhook, port, _agent_webhook()))
+ closing = None
+ try:
+ assert await asyncio.to_thread(write_entered.wait, 1)
+ closing = asyncio.create_task(store.close())
+ assert await asyncio.to_thread(listener_stopped.wait, 1)
+ assert not closing.done()
+ assert store.has_pending_work is True
+ finally:
+ allow_write.set()
+ response = await request
+ if closing is not None:
+ await closing
+ else:
+ await store.close()
+ assert response[0] == 200
+ assert store.has_pending_work is False
+ assert not store._sessions
+
+
+async def test_abandoned_authorization_releases_listener_without_poll(tmp_path, monkeypatch) -> None:
+ state = LinearStateStore(tmp_path / "linear.sqlite3")
+ lease = Mock(spec=LinearServerLease)
+ monkeypatch.setattr(linear_connect, "_load_linear_config", _config)
+ monkeypatch.setattr(linear_connect, "LinearStateStore", lambda: state)
+ monkeypatch.setattr(linear_connect, "acquire_http_server", lambda *_args: lease)
+ monkeypatch.setattr("nanobot.channels.linear.oauth.FLOW_TTL_SECONDS", 0.02)
+ store = linear_connect.LinearConnectStore()
+ started = await store.start()
+ task = store._sessions[started["session_id"]].expiry_task
+ assert task is not None
+ try:
+ await asyncio.wait_for(asyncio.shield(task), timeout=1)
+ assert store.has_pending_work is False
+ assert not store._sessions
+ lease.close.assert_called_once()
+ finally:
+ await store.close()
+
+
@pytest.mark.asyncio
async def test_connect_store_lists_and_disconnects_workspaces(
tmp_path: Path,
diff --git a/nanobot/channels/linear/tests/webui/LinearPanel.test.tsx b/nanobot/channels/linear/tests/webui/LinearPanel.test.tsx
index a8e0b5dbc..02be7a010 100644
--- a/nanobot/channels/linear/tests/webui/LinearPanel.test.tsx
+++ b/nanobot/channels/linear/tests/webui/LinearPanel.test.tsx
@@ -787,7 +787,7 @@ describe("Linear channel UI", () => {
fireEvent.click(await screen.findByRole("menuitem", { name: "Remove workspace" }));
const confirm = await screen.findByRole("alertdialog", { name: "Remove nanobot?" });
fireEvent.click(within(confirm).getByRole("button", { name: "Remove workspace" }));
- expect(await screen.findByRole("button", { name: "Connect Linear" })).toBeEnabled();
+ await waitFor(() => expect(screen.getByRole("button", { name: "Connect Linear" })).toBeEnabled());
expect(screen.queryByText("Linear authorization cancelled.")).not.toBeInTheDocument();
expect(screen.queryByRole("link", { name: "Continue in Linear" })).not.toBeInTheDocument();
});
diff --git a/nanobot/channels/manager.py b/nanobot/channels/manager.py
index 1f21b7d5b..6700f69cb 100644
--- a/nanobot/channels/manager.py
+++ b/nanobot/channels/manager.py
@@ -152,8 +152,11 @@ class ChannelManager:
self._channel_errors: dict[str, str] = {}
self._channel_tasks: dict[str, asyncio.Task[None]] = {}
self._dispatch_task: asyncio.Task[None] | None = None
+ self._restart_notice_task: asyncio.Task[None] | None = None
self._outbound_tasks: dict[asyncio.Task[None], tuple[str, str]] = {}
self._outbound_tails: dict[tuple[str, str], asyncio.Task[None]] = {}
+ self._outbound_pending: list[OutboundMessage] = []
+ self._outbound_dispatching = False
self._outbound_slots = asyncio.Semaphore(_OUTBOUND_PENDING_LIMIT)
self._outbound_sends = asyncio.Semaphore(_OUTBOUND_CONCURRENCY)
self._stopping_channels: set[str] = set()
@@ -161,9 +164,12 @@ class ChannelManager:
self._origin_reply_fingerprints: OrderedDict[tuple[str, str, str], str] = OrderedDict()
self._outbox = DeliveryOutbox(self._config_path.parent / "delivery" / "outbox.sqlite3")
self._scheduled_deliveries: set[str] = set()
- self.bus.outbound_recorder = self._outbox.record
+ self.bus.outbound_recorder = self._record_scheduled
self._init_channels()
+ self._remove_delivery_check: Callable[[], None] | None = (
+ self.bus.admission.register_pending_work(lambda: self.has_pending_delivery)
+ )
def _channel_section(
self,
@@ -404,6 +410,8 @@ class ChannelManager:
errors = self._channel_errors = {}
errors.pop(name, None)
try:
+ if name != "websocket":
+ await self.bus.admission.wait_until_open()
await channel.start()
except asyncio.CancelledError:
raise
@@ -624,6 +632,10 @@ class ChannelManager:
async def start_all(self) -> None:
"""Start all channels and the outbound dispatcher."""
+ if self._remove_delivery_check is None:
+ self._remove_delivery_check = self.bus.admission.register_pending_work(
+ lambda: self.has_pending_delivery,
+ )
if not self.channels:
logger.warning("No channels enabled")
return
@@ -647,7 +659,8 @@ class ChannelManager:
notice = consume_restart_notice_from_env()
if not notice:
return None
- return asyncio.create_task(self._send_restart_notice_when_started(notice))
+ self._restart_notice_task = asyncio.create_task(self._send_restart_notice_when_started(notice))
+ return self._restart_notice_task
async def _send_restart_notice_when_started(
self,
@@ -657,6 +670,7 @@ class ChannelManager:
poll_s: float = _RESTART_NOTICE_START_POLL_S,
) -> None:
"""Deliver a restart notice after the target channel starts."""
+ await self.bus.admission.wait_until_open()
loop = asyncio.get_running_loop()
deadline = loop.time() + timeout_s
target = self.channels.get(notice.channel)
@@ -703,9 +717,18 @@ class ChannelManager:
with suppress(asyncio.CancelledError):
await self._dispatch_task
+ if self._restart_notice_task:
+ self._restart_notice_task.cancel()
+ with suppress(asyncio.CancelledError):
+ await self._restart_notice_task
+ self._restart_notice_task = None
+
# Stop all channels
for name in list(self.channels):
await self._stop_channel(name)
+ if self._remove_delivery_check is not None:
+ self._remove_delivery_check()
+ self._remove_delivery_check = None
@staticmethod
def _fingerprint_content(content: str) -> str:
@@ -745,6 +768,25 @@ class ChannelManager:
return False
+ def _record_scheduled(self, msg: OutboundMessage) -> None:
+ if msg.delivery is not None:
+ with self.bus.admission.activity():
+ self._outbox.record(msg)
+
+ @property
+ def has_pending_delivery(self) -> bool:
+ """A synchronous idle check, including channel-owned transport queues.
+
+ Read on the gateway event loop immediately before closing admission.
+ This is delivery liveness, not proof that every channel writer stopped.
+ """
+ return bool(
+ self.bus.outbound_size or self._outbound_pending or self._outbound_dispatching
+ or self._outbound_tasks
+ or (self._restart_notice_task is not None and not self._restart_notice_task.done())
+ or any(channel.has_pending_delivery for channel in self.channels.values())
+ )
+
async def _cancel_outbound(self, channel: str | None = None) -> None:
tasks = [task for task, key in self._outbound_tasks.items()
if channel is None or key[0] == channel]
@@ -839,15 +881,17 @@ class ChannelManager:
self._outbox.finish(msg, "sent")
async def _recover_scheduled(self) -> None:
- for msg in self._outbox.ready():
- channel = self.channels.get(msg.channel)
- if channel is None:
- self._outbox.finish(msg, "failed", "channel_disabled")
- else:
- await self._queue_outbound(channel, msg)
+ with self.bus.admission.activity():
+ for msg in self._outbox.ready():
+ channel = self.channels.get(msg.channel)
+ if channel is None:
+ self._outbox.finish(msg, "failed", "channel_disabled")
+ else:
+ await self._queue_outbound(channel, msg)
async def _dispatch_outbound(self) -> None:
try:
+ await self.bus.admission.wait_until_open()
await self._dispatch_outbound_loop()
finally:
await self._cancel_outbound()
@@ -858,11 +902,12 @@ class ChannelManager:
# Buffer for messages that couldn't be processed during delta coalescing
# (since asyncio.Queue doesn't support push_front)
- pending: list[OutboundMessage] = []
+ pending = self._outbound_pending
next_recovery = 0.0
while True:
try:
+ await self.bus.admission.wait_until_open()
if time.monotonic() >= next_recovery:
next_recovery = time.monotonic() + RETRY_SECONDS
try:
@@ -873,10 +918,15 @@ class ChannelManager:
if pending:
msg = pending.pop(0)
else:
- msg = await asyncio.wait_for(
- self.bus.consume_outbound(),
- timeout=1.0
- )
+ # wait_for creates a child task: it can remove the last
+ # queued message before this dispatcher records ownership.
+ # Keep dequeue and the busy claim in the same task.
+ async with asyncio.timeout(1.0):
+ msg = await self.bus.consume_outbound()
+ self._outbound_dispatching = True
+ # Intake can close while an empty queue is awaited. Retain the
+ # message, but do not start another transport write while paused.
+ await self.bus.admission.wait_until_open()
event = msg.event
progress_event = event if isinstance(event, ProgressEvent) else None
@@ -945,6 +995,8 @@ class ChannelManager:
continue
except asyncio.CancelledError:
break
+ finally:
+ self._outbound_dispatching = False
@staticmethod
async def _send_reasoning_delta(
diff --git a/nanobot/channels/plugin.py b/nanobot/channels/plugin.py
index 3bdd8d49a..bd3b5f51b 100644
--- a/nanobot/channels/plugin.py
+++ b/nanobot/channels/plugin.py
@@ -11,6 +11,7 @@ from typing import TYPE_CHECKING, Any, cast
from packaging.requirements import InvalidRequirement, Requirement
+from nanobot.channels.connect import ChannelConnector
from nanobot.channels.contracts import ChannelManagementSpec, ChannelSetupSpec
if TYPE_CHECKING:
@@ -93,7 +94,7 @@ class ChannelPlugin:
)
return channel_cls
- def load_connector(self) -> Any:
+ def load_connector(self) -> ChannelConnector:
"""Construct the optional channel-owned interactive connector."""
if self.connector is None:
raise ImportError(f"Channel plugin '{self.name}' does not provide a connector")
@@ -110,7 +111,9 @@ class ChannelPlugin:
f"Channel plugin '{self.name}' connector '{self.connector}' "
"does not provide handle()"
)
- return connector
+ # Dynamic plugin edge: handle() is the established connector contract.
+ # Lifecycle support is optional and checked by its maintenance owner.
+ return cast(ChannelConnector, connector)
def _target_parts(target: str, *, label: str) -> tuple[str, str]:
diff --git a/nanobot/channels/qq/connect.py b/nanobot/channels/qq/connect.py
index ffd97ab38..b9bd81c76 100644
--- a/nanobot/channels/qq/connect.py
+++ b/nanobot/channels/qq/connect.py
@@ -93,6 +93,19 @@ class QQConnectStore:
def __init__(self) -> None:
self._sessions: dict[str, QQConnectSession] = {}
+ self._commits: dict[str, asyncio.Task[None]] = {}
+ self._closed = False
+
+ @property
+ def has_pending_work(self) -> bool:
+ now = time.monotonic()
+ return bool(self._commits) or any(session.deadline > now for session in self._sessions.values())
+
+ async def close(self) -> None:
+ self._closed = True
+ self._sessions.clear()
+ if self._commits:
+ await asyncio.shield(asyncio.gather(*self._commits.values(), return_exceptions=True))
async def handle(self, action: str, query: QueryParams) -> dict[str, Any]:
if action == "start":
@@ -134,6 +147,10 @@ class QQConnectStore:
# A transient portal error is not proof the scan failed; keep waiting.
return _pending(session, "Waiting for QQ scan...")
+ self._cleanup()
+ if self._sessions.get(session_id) is not session:
+ return _payload(session_id, "expired", "This QQ login has expired. Start again.")
+
status = result.get("status")
if status == 3:
self._sessions.pop(session_id, None)
@@ -151,7 +168,13 @@ class QQConnectStore:
if not app_id or not secret:
return _payload(session_id, "failed", "QQ confirmed the scan but returned no credentials.")
- await asyncio.to_thread(save_credentials, app_id, secret)
+ # Cancelling the awaiting request cannot stop a file-writing thread.
+ # Retain ownership until the writer finishes, including during shutdown.
+ commit = asyncio.create_task(asyncio.to_thread(save_credentials, app_id, secret))
+ self._commits[session_id] = commit
+ commit.add_done_callback(lambda task: self._commits.pop(session_id, None))
+ commit.add_done_callback(lambda task: task.exception() if not task.cancelled() else None)
+ await asyncio.shield(commit)
session.credentials = (app_id, secret)
return {
"session_id": session_id,
@@ -161,6 +184,8 @@ class QQConnectStore:
async def cancel(self, session_id: str) -> dict[str, Any]:
self._sessions.pop(session_id, None)
+ if commit := self._commits.get(session_id):
+ await asyncio.shield(asyncio.gather(commit, return_exceptions=True))
return _payload(session_id, "cancelled", "QQ login cancelled.")
async def login(self) -> tuple[str, str] | None:
@@ -181,6 +206,8 @@ class QQConnectStore:
self._sessions.pop(session.id, None)
def _new_session(self, task_id: str, key: str) -> QQConnectSession:
+ if self._closed:
+ raise ChannelConnectError("QQ connection store is closed", status=409)
session = QQConnectSession(
id=secrets.token_urlsafe(18),
task_id=task_id,
diff --git a/nanobot/channels/qq/tests/test_connect.py b/nanobot/channels/qq/tests/test_connect.py
index dfa0088fa..8e2133a17 100644
--- a/nanobot/channels/qq/tests/test_connect.py
+++ b/nanobot/channels/qq/tests/test_connect.py
@@ -48,9 +48,11 @@ async def test_qq_connect_writes_scanned_credentials_to_config(monkeypatch: pyte
started = await store.start()
assert started["status"] == "pending"
assert started["qr_url"].endswith("task_id=task-1&_wv=2")
+ assert store.has_pending_work
polled = await store.poll(started["session_id"])
assert polled["status"] == "succeeded"
+ assert not store.has_pending_work
assert await store.poll(started["session_id"]) == {
"session_id": started["session_id"],
"status": "expired",
@@ -64,6 +66,117 @@ async def test_qq_connect_writes_scanned_credentials_to_config(monkeypatch: pyte
assert qq["allowFrom"] == ["42"]
[email protected]("stop", ["cancel", "close", "expire"])
+async def test_qq_late_portal_result_cannot_save_after_session_ends(
+ monkeypatch: pytest.MonkeyPatch, _isolated_config: Path, stop: str,
+):
+ key = base64.b64encode(b"k" * 32).decode()
+ polling = asyncio.Event()
+ release = asyncio.Event()
+
+ async def fake_poll(_task_id: str) -> dict[str, Any]:
+ polling.set()
+ await release.wait()
+ return {"status": 2, "bot_appid": "1024", "bot_encrypt_secret": _encrypt("new", key)}
+
+ monkeypatch.setattr(connect, "poll_bind_task", fake_poll)
+ store = QQConnectStore()
+ session = store._new_session("task", key)
+ before = _isolated_config.read_bytes()
+ poll = asyncio.create_task(store.poll(session.id))
+ try:
+ await asyncio.wait_for(polling.wait(), timeout=5)
+ if stop == "cancel":
+ await store.cancel(session.id)
+ elif stop == "close":
+ await store.close()
+ else:
+ session.deadline = 0
+ assert not store.has_pending_work
+ finally:
+ release.set()
+ assert (await poll)["status"] == "expired"
+ assert _isolated_config.read_bytes() == before
+
+
[email protected]("stop", ["cancel", "close"])
+async def test_qq_cleanup_waits_for_writer_after_poll_request_is_cancelled(
+ monkeypatch: pytest.MonkeyPatch, _isolated_config: Path, stop: str,
+):
+ from nanobot.runtime_admission import RuntimeAdmission, RuntimeBusyError
+
+ key = base64.b64encode(b"k" * 32).decode()
+ saving = threading.Event()
+ release = threading.Event()
+ original_save = connect.save_credentials
+
+ async def fake_poll(_task_id: str) -> dict[str, Any]:
+ return {"status": 2, "bot_appid": "1024", "bot_encrypt_secret": _encrypt("new", key)}
+
+ def slow_save(app_id: str, secret: str) -> None:
+ saving.set()
+ if not release.wait(timeout=5):
+ raise TimeoutError("credential writer was not released")
+ original_save(app_id, secret)
+
+ monkeypatch.setattr(connect, "poll_bind_task", fake_poll)
+ monkeypatch.setattr(connect, "save_credentials", slow_save)
+ store = QQConnectStore()
+ admission = RuntimeAdmission()
+ admission.register_pending_work(lambda: store.has_pending_work)
+ session = store._new_session("task", key)
+ poll = asyncio.create_task(store.poll(session.id))
+ cleanup: asyncio.Task[None | dict[str, Any]] | None = None
+ try:
+ assert await asyncio.to_thread(saving.wait, 5)
+ poll.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await poll
+ session.deadline = 0
+ cleanup = asyncio.create_task(store.close() if stop == "close" else store.cancel(session.id))
+ await asyncio.sleep(0)
+ assert not cleanup.done()
+ assert store.has_pending_work
+ with pytest.raises(RuntimeBusyError), admission.pause_if_idle(lambda: False):
+ pytest.fail("an active credential writer must block an update")
+ finally:
+ release.set()
+ await asyncio.gather(poll, return_exceptions=True)
+ if cleanup is not None:
+ await cleanup
+ await store.close()
+ assert not store.has_pending_work
+ with admission.pause_if_idle(lambda: False):
+ assert admission.paused
+ saved = json.loads(_isolated_config.read_text(encoding="utf-8"))["channels"]["qq"]
+ assert (saved["appId"], saved["secret"], saved["allowFrom"]) == ("1024", "new", ["42"])
+
+
+async def test_qq_close_during_start_does_not_leave_a_new_session(monkeypatch: pytest.MonkeyPatch):
+ creating = asyncio.Event()
+ release = asyncio.Event()
+
+ async def fake_create() -> tuple[str, str]:
+ creating.set()
+ await release.wait()
+ return "late-task", base64.b64encode(b"k" * 32).decode()
+
+ monkeypatch.setattr(connect, "create_bind_task", fake_create)
+ store = QQConnectStore()
+ start = asyncio.create_task(store.start())
+ try:
+ await asyncio.wait_for(creating.wait(), timeout=5)
+ await store.close()
+ finally:
+ release.set()
+ with pytest.raises(connect.ChannelConnectError, match="closed"):
+ await start
+ assert not store.has_pending_work
+
+
@pytest.mark.asyncio
async def test_qq_connect_keeps_waiting_on_transient_portal_errors(monkeypatch: pytest.MonkeyPatch):
async def fake_create() -> tuple[str, str]:
diff --git a/nanobot/channels/websocket/runtime.py b/nanobot/channels/websocket/runtime.py
index 1e681a5f6..e4c4f0301 100644
--- a/nanobot/channels/websocket/runtime.py
+++ b/nanobot/channels/websocket/runtime.py
@@ -29,6 +29,7 @@ from nanobot.bus.queue import MessageBus
from nanobot.channels.base import BaseChannel
from nanobot.channels.websocket.binary_http import BinaryHTTPBridge
from nanobot.config_base import Base
+from nanobot.runtime_admission import RuntimeMaintenanceError
from nanobot.session.webui_turns import (
clear_websocket_turn_if_current,
mark_websocket_turn_transcript_persistence_failed,
@@ -705,6 +706,15 @@ class WebSocketChannel(BaseChannel):
async def handler(connection: ServerConnection) -> None:
await self._connection_loop(connection)
+ from aiohttp import web
+
+ async def handle_binary(request: web.BaseRequest) -> web.StreamResponse:
+ try:
+ with self.bus.admission.activity():
+ return await self._uploads.handle(request)
+ except RuntimeMaintenanceError:
+ return web.json_response({"error": "Gateway update is being verified"}, status=503)
+
async def prune_uploads() -> None:
while not stop_event.is_set():
self._uploads.store.prune()
@@ -720,7 +730,7 @@ class WebSocketChannel(BaseChannel):
failures = 0
while not stop_event.is_set():
server: Server | None = None
- bridge = BinaryHTTPBridge(self._uploads.handle)
+ bridge = BinaryHTTPBridge(handle_binary)
was_serving = False
started_at = 0.0
try:
@@ -969,6 +979,16 @@ class WebSocketChannel(BaseChannel):
name=f"websocket-outbound-{id(connection):x}",
)
+ @property
+ def has_pending_delivery(self) -> bool:
+ # send() only enqueues a frame. buffered_bytes includes the frame that
+ # a writer has removed from its queue but has not finished transmitting.
+ return bool(self._outbound_retire_tasks) or any(
+ state.buffered_bytes or not state.queue.empty()
+ or (state.writer is not None and not state.writer.done())
+ for state in self._connection_outbound.values()
+ )
+
async def _drain_connection_outbound(
self,
connection: ServerConnection,
diff --git a/nanobot/channels/websocket/tests/test_attachment_ingress.py b/nanobot/channels/websocket/tests/test_attachment_ingress.py
index d25c19d93..d523d2bd1 100644
--- a/nanobot/channels/websocket/tests/test_attachment_ingress.py
+++ b/nanobot/channels/websocket/tests/test_attachment_ingress.py
@@ -1,6 +1,7 @@
"""Production listener regressions for HTTP upload + small WS references."""
import asyncio
import json
+import threading
from pathlib import Path
import aiohttp
@@ -9,6 +10,8 @@ from websockets.asyncio.client import connect
from nanobot.bus.queue import MessageBus
from nanobot.channels.websocket.runtime import WebSocketChannel, WebSocketConfig
+from nanobot.config.loader import load_config
+from nanobot.runtime_admission import RuntimeBusyError
from nanobot.session.manager import SessionManager
from nanobot.webui.gateway_services import build_gateway_services
@@ -48,6 +51,134 @@ async def event(ws, name):
return payload
[email protected]("finish", [True, False], ids=["complete", "disconnect"])
+async def test_streaming_upload_blocks_maintenance_until_written_or_cleaned(gateway, finish):
+ channel, bus, http_url, ws_url = gateway
+ port = int(http_url.rsplit(":", 1)[1])
+ store = channel.gateway.uploads.store
+ async with connect(ws_url) as ws:
+ capability = (await event(ws, "ready"))["upload"]
+ reader, writer = await asyncio.open_connection("127.0.0.1", port)
+ try:
+ writer.write((
+ f"POST {capability['path']} HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\n"
+ f"Authorization: Bearer {capability['token']}\r\n"
+ "Content-Type: image/png\r\nContent-Length: 8\r\n\r\npart"
+ ).encode())
+ await writer.drain()
+ async with asyncio.timeout(3):
+ while store._active == 0:
+ await asyncio.sleep(.01)
+ with pytest.raises(RuntimeBusyError):
+ with bus.admission.pause_if_idle(lambda: False):
+ pytest.fail("Maintenance ignored an in-progress binary write")
+ assert not bus.admission.paused
+ if finish:
+ writer.write(b"done")
+ await writer.drain()
+ response = await asyncio.wait_for(reader.read(), timeout=3)
+ assert response.startswith(b"HTTP/1.1 201"), response
+ else:
+ writer.close()
+ await writer.wait_closed()
+ async with asyncio.timeout(3):
+ while store._active:
+ await asyncio.sleep(.01)
+ with bus.admission.pause_if_idle(lambda: False):
+ assert bus.admission.paused
+ if not finish:
+ assert not tuple(store._journal.iterdir())
+ finally:
+ writer.close()
+ await writer.wait_closed()
+
+
+async def test_threaded_settings_write_stays_busy_after_browser_disconnect(gateway, monkeypatch):
+ channel, bus, _, ws_url = gateway
+ entered, release = threading.Event(), threading.Event()
+ settings = channel.gateway.settings
+ original = settings.config.run_serialized
+
+ def delayed_save(*args, **kwargs):
+ entered.set()
+ assert release.wait(10), "Test did not release the settings writer"
+ return original(*args, **kwargs)
+
+ monkeypatch.setattr(settings.config, "run_serialized", delayed_save)
+
+ def connection_url():
+ token = channel.gateway.tokens.issue_token(300, audience="webui")
+ return ws_url.replace("test-secret", token)
+
+ def request(identifier, value):
+ return json.dumps({"type": "webui_request", "request_id": identifier,
+ "action": "settings.runtime_config.update",
+ "payload": {"values": {"agents.defaults.max_tool_iterations": value}}})
+
+ try:
+ async with connect(connection_url()) as ws:
+ await event(ws, "ready")
+ await ws.send(request("slow-write", 31))
+ assert await asyncio.to_thread(entered.wait, 3)
+ with pytest.raises(RuntimeBusyError):
+ with bus.admission.pause_if_idle(lambda: False):
+ pytest.fail("Maintenance ignored a threaded settings write")
+ # Existing mutation ownership deliberately survives a lost browser;
+ # losing its delivery task must not make the gateway appear idle.
+ with pytest.raises(RuntimeBusyError):
+ with bus.admission.pause_if_idle(lambda: False):
+ pytest.fail("Browser disconnect released an unfinished write")
+ operation = channel._commands.request_operations["slow-write"].task
+ release.set()
+ result = await asyncio.wait_for(asyncio.shield(operation), timeout=5)
+ assert result.status is None, result
+ assert load_config(settings.config.path).agents.defaults.max_tool_iterations == 31
+ async with connect(connection_url()) as ws:
+ await event(ws, "ready")
+ with bus.admission.pause_if_idle(lambda: False):
+ await ws.send(request("blocked-write", 32))
+ rejected = await event(ws, "webui_response")
+ assert rejected["error"]["status"] == 503
+ assert load_config(settings.config.path).agents.defaults.max_tool_iterations == 31
+ await ws.send(request("after-abort", 33))
+ assert (await event(ws, "webui_response"))["ok"] is True
+ assert load_config(settings.config.path).agents.defaults.max_tool_iterations == 33
+ finally:
+ release.set()
+
+
+async def test_http_route_is_busy_until_its_async_work_finishes(gateway, monkeypatch):
+ channel, bus, http_url, _ = gateway
+ entered, release = asyncio.Event(), asyncio.Event()
+ route = channel.gateway.http._dispatch_resolved
+
+ async def delayed_route(*args, **kwargs):
+ entered.set()
+ await release.wait()
+ return await route(*args, **kwargs)
+
+ monkeypatch.setattr(channel.gateway.http, "_dispatch_resolved", delayed_route)
+ async with aiohttp.ClientSession(headers={"Authorization": "Bearer test-secret"}) as http:
+ request = asyncio.create_task(http.get(http_url + "/webui/bootstrap"))
+ try:
+ await asyncio.wait_for(entered.wait(), timeout=3)
+ with pytest.raises(RuntimeBusyError):
+ with bus.admission.pause_if_idle(lambda: False):
+ pytest.fail("Maintenance ignored a running HTTP handler")
+ release.set()
+ async with await asyncio.wait_for(request, timeout=3) as response:
+ assert response.status == 200
+ await response.read()
+ with bus.admission.pause_if_idle(lambda: False):
+ async with http.get(http_url + "/webui/bootstrap") as response:
+ assert response.status == 503
+ async with http.get(http_url + "/webui/bootstrap") as response:
+ assert response.status == 200
+ finally:
+ release.set()
+ await asyncio.gather(request, return_exceptions=True)
+
+
@pytest.mark.parametrize("mime,name", [
("image/png", "image.png"), ("text/csv", "report.csv"), ("video/webm", "clip.webm"),
])
diff --git a/nanobot/channels/websocket/tests/test_websocket_outbound_delivery.py b/nanobot/channels/websocket/tests/test_websocket_outbound_delivery.py
index e2cb206cd..93f64ae19 100644
--- a/nanobot/channels/websocket/tests/test_websocket_outbound_delivery.py
+++ b/nanobot/channels/websocket/tests/test_websocket_outbound_delivery.py
@@ -16,6 +16,7 @@ from nanobot.channels.manager import ChannelManager
from nanobot.channels.websocket import runtime
from nanobot.channels.websocket.runtime import WebSocketChannel, WebSocketConfig
from nanobot.config.schema import Config
+from nanobot.runtime_admission import RuntimeBusyError
from nanobot.webui.gateway_services import build_gateway_services
@@ -64,7 +65,7 @@ class _RecordingConnection:
def _channel() -> WebSocketChannel:
- bus = MagicMock(spec=MessageBus)
+ bus = MessageBus()
config = WebSocketConfig(
enabled=True,
allow_from=["*"],
@@ -129,9 +130,24 @@ async def test_message_bus_delivers_to_ten_tuis_with_one_blocked_connection() ->
assert await _next_text(connection) == "first"
assert await _next_text(connection) == "last"
assert connections[0].sent.empty()
+ async with asyncio.timeout(2):
+ while manager._outbound_tasks or bus.outbound_size:
+ await asyncio.sleep(0)
+ # The manager's send has finished; the physical transport still owns
+ # its final frames. A shutdown idle check must include that second queue.
+ assert channel.has_pending_delivery
+ with pytest.raises(RuntimeBusyError):
+ with bus.admission.pause_if_idle(lambda: False):
+ pytest.fail("The blocked WebSocket transport was missed")
+ assert not bus.admission.paused
connections[0].release_send.set()
assert await _next_text(connections[0]) == "first"
assert await _next_text(connections[0]) == "last"
+ async with asyncio.timeout(2):
+ while manager.has_pending_delivery:
+ await asyncio.sleep(0)
+ with bus.admission.pause_if_idle(lambda: False):
+ assert bus.admission.paused
finally:
dispatcher.cancel()
await asyncio.gather(dispatcher, return_exceptions=True)
@@ -142,6 +158,26 @@ async def test_message_bus_delivers_to_ten_tuis_with_one_blocked_connection() ->
assert not channel._connection_outbound
+async def test_delivery_remains_busy_until_timed_out_transport_is_retired(monkeypatch) -> None:
+ monkeypatch.setattr(runtime, "_OUTBOUND_SEND_TIMEOUT_S", 0.02)
+ channel = _channel()
+ connection = _RecordingConnection(block_first_send=True, block_close=True)
+ channel._attach(cast(Any, connection), "chat-retiring")
+ try:
+ await channel.send(_message("chat-retiring", "reply"))
+ await asyncio.wait_for(connection.closed.wait(), 2)
+ assert connection.send_cancelled.is_set()
+ assert channel.has_pending_delivery
+ connection.release_close.set()
+ await asyncio.wait_for(_wait_for_retire_tasks(channel), 2)
+ assert not channel.has_pending_delivery
+ finally:
+ connection.release_send.set()
+ connection.release_close.set()
+ await channel._cleanup_connection(cast(Any, connection))
+
+
@pytest.mark.asyncio
async def test_slow_tui_does_not_block_a_different_topic() -> None:
channel = _channel()
diff --git a/nanobot/channels/weixin/connect.py b/nanobot/channels/weixin/connect.py
index eb9d2e8a8..746d8675d 100644
--- a/nanobot/channels/weixin/connect.py
+++ b/nanobot/channels/weixin/connect.py
@@ -34,6 +34,15 @@ class WeixinConnectStore:
def __init__(self) -> None:
self._sessions: dict[str, WeixinConnectSession] = {}
+ @property
+ def has_pending_work(self) -> bool:
+ # Poll/commit are awaited by the settings request owner, not detached.
+ return any(session.deadline > time.monotonic() for session in self._sessions.values())
+
+ async def close(self) -> None:
+ for session_id in tuple(self._sessions):
+ await self.cancel(session_id)
+
async def handle(self, action: str, query: QueryParams) -> dict[str, Any]:
"""Handle one generic settings connection action."""
if action == "start":
diff --git a/nanobot/channels/weixin/tests/test_connect.py b/nanobot/channels/weixin/tests/test_connect.py
index aec484780..05d410268 100644
--- a/nanobot/channels/weixin/tests/test_connect.py
+++ b/nanobot/channels/weixin/tests/test_connect.py
@@ -57,10 +57,12 @@ async def test_weixin_connect_store_saves_confirmed_qr_login(
started = await store.start()
assert started["status"] == "pending"
assert started["qr_url"] == "https://qr.example/1"
+ assert store.has_pending_work is True
completed = await store.poll(started["session_id"])
assert completed["status"] == "succeeded"
assert completed["account"] == "wx-user"
+ assert store.has_pending_work is False
saved = json.loads((state_dir / "account.json").read_text())
assert saved["token"] == "wx-token"
@@ -177,9 +179,11 @@ async def test_weixin_reconnect_keeps_existing_account_until_scan_succeeds(
@pytest.mark.asyncio
[email protected]("shutdown", [False, True])
async def test_weixin_cancel_wins_over_inflight_confirmation(
tmp_path,
monkeypatch: pytest.MonkeyPatch,
+ shutdown: bool,
) -> None:
state_dir = tmp_path / "weixin-state"
config_path = tmp_path / "config.json"
@@ -214,15 +218,20 @@ async def test_weixin_cancel_wins_over_inflight_confirmation(
store = WeixinConnectStore()
started = await store.handle("start", {})
+ assert store.has_pending_work is True
query = {"session_id": [started["session_id"]]}
poll_task = asyncio.create_task(store.handle("poll", query))
await asyncio.wait_for(poll_started.wait(), timeout=5)
- cancelled = await store.handle("cancel", query)
+ if shutdown:
+ await store.close()
+ else:
+ cancelled = await store.handle("cancel", query)
+ assert cancelled["status"] == "cancelled"
release_poll.set()
completed = await poll_task
- assert cancelled["status"] == "cancelled"
+ assert store.has_pending_work is False
assert completed["status"] == "cancelled"
assert not (state_dir / "account.json").exists()
diff --git a/nanobot/channels/weixin/tests/test_weixin_channel.py b/nanobot/channels/weixin/tests/test_weixin_channel.py
index 85f26a815..bd86a4861 100644
--- a/nanobot/channels/weixin/tests/test_weixin_channel.py
+++ b/nanobot/channels/weixin/tests/test_weixin_channel.py
@@ -799,6 +799,7 @@ async def test_manager_surfaces_actionable_weixin_auth_error_without_traceback(
)
manager = manager_mod.ChannelManager.__new__(manager_mod.ChannelManager)
manager._channel_errors = {}
+ manager.bus = channel.bus
await manager._start_channel("weixin", channel)
diff --git a/nanobot/channels/whatsapp/connect.py b/nanobot/channels/whatsapp/connect.py
index 41eb4de43..0b3768339 100644
--- a/nanobot/channels/whatsapp/connect.py
+++ b/nanobot/channels/whatsapp/connect.py
@@ -21,6 +21,7 @@ if TYPE_CHECKING:
_NATIVE_STOP_TIMEOUT_SECONDS = 10.0
_DATABASE_REPLACE_TIMEOUT_SECONDS = 10.0
_FINALIZE_POLL_WAIT_SECONDS = 0.05
+_CONNECT_TTL_SECONDS = 600
@dataclass(slots=True)
@@ -36,6 +37,9 @@ class WhatsAppConnectSession:
deadline: float
qr_url: str = ""
finalize_task: asyncio.Task[None] | None = None
+ stop_task: asyncio.Task[None] | None = None
+ discard_task: asyncio.Task[None] | None = None
+ expiry_task: asyncio.Task[None] | None = None
class WhatsAppConnectStore:
@@ -44,6 +48,17 @@ class WhatsAppConnectStore:
def __init__(self) -> None:
self._sessions: dict[str, WhatsAppConnectSession] = {}
+ @property
+ def has_pending_work(self) -> bool:
+ """Keep login/native workers owned until completion or confirmed cleanup."""
+ return any(
+ session.finalize_task is None
+ or not session.finalize_task.done()
+ or not self._session_stopped(session)
+ or (session.discard_task is not None and not session.discard_task.done())
+ for session in self._sessions.values()
+ )
+
async def handle(self, action: str, query: QueryParams) -> dict[str, Any]:
if action == "start":
force = (query_first(query, "force") or "").strip().lower() in {
@@ -99,9 +114,13 @@ class WhatsAppConnectStore:
target_path=target_path,
pending_path=pending_path,
created_wall=now_wall,
- deadline=time.monotonic() + 600,
+ deadline=time.monotonic() + _CONNECT_TTL_SECONDS,
)
self._sessions[session_id] = session
+ session.expiry_task = asyncio.create_task(
+ self._expire_session(session), name=f"whatsapp-connect-expire-{session.id}",
+ )
+ session.expiry_task.add_done_callback(self._observe_task)
qr_wait = asyncio.create_task(self._wait_for_qr(session))
try:
@@ -113,6 +132,7 @@ class WhatsAppConnectStore:
finally:
if not qr_wait.done():
qr_wait.cancel()
+ await asyncio.gather(qr_wait, return_exceptions=True)
return self._pending_payload(session)
async def poll(self, session_id: str) -> dict[str, Any]:
@@ -124,6 +144,9 @@ class WhatsAppConnectStore:
"status": "expired",
"message": "This WhatsApp login has expired. Start again.",
}
+ if session.discard_task is not None:
+ # A concurrent poll must not promote a login being cancelled.
+ return await self.cancel(session_id)
if not session.result.done():
return self._pending_payload(session)
@@ -138,21 +161,25 @@ class WhatsAppConnectStore:
# Finish fast clients in this request without letting native shutdown
# block the polling response path.
await asyncio.wait({finalize_task}, timeout=_FINALIZE_POLL_WAIT_SECONDS)
+ if session.discard_task is not None:
+ return await self.cancel(session_id)
if not finalize_task.done():
payload = self._pending_payload(session)
payload["qr_url"] = ""
payload["message"] = "Finishing the WhatsApp connection."
return payload
- self._sessions.pop(session_id, None)
try:
finalize_task.result()
except Exception as exc:
+ if self._session_stopped(session):
+ self._sessions.pop(session_id, None)
return {
"session_id": session_id,
"status": "failed",
"message": f"WhatsApp QR login failed: {exc}",
}
+ self._sessions.pop(session_id, None)
return {
"session_id": session_id,
"status": "succeeded",
@@ -162,15 +189,21 @@ class WhatsAppConnectStore:
async def _finalize_session(self, session: WhatsAppConnectSession) -> None:
try:
session.result.result()
+ except BaseException:
await self._close_session(session)
+ self._remove_database(session.pending_path)
+ raise
+ # A stop timeout is not proof that the native SQLite writer exited.
+ # Preserve its database and ownership for an explicit cleanup retry.
+ await self._close_session(session)
+ try:
await self._commit_database(session.pending_path, session.target_path)
except BaseException:
- await self._close_session(session)
self._remove_database(session.pending_path)
raise
async def cancel(self, session_id: str) -> dict[str, Any]:
- session = self._sessions.pop(session_id, None)
+ session = self._sessions.get(session_id)
if session is not None:
await self._discard_session(session)
return {
@@ -186,17 +219,30 @@ class WhatsAppConnectStore:
if time.monotonic() >= session.deadline
]
for session_id in expired:
- session = self._sessions.pop(session_id)
- await self._discard_session(session)
+ await self.cancel(session_id)
+
+ async def _expire_session(self, session: WhatsAppConnectSession) -> None:
+ await asyncio.sleep(max(0, session.deadline - time.monotonic()))
+ await self.cancel(session.id)
async def close(self) -> None:
"""Stop every login client before the gateway event loop closes."""
sessions = tuple(self._sessions.values())
- self._sessions.clear()
for session in sessions:
await self._discard_session(session)
async def _discard_session(self, session: WhatsAppConnectSession) -> None:
+ task = session.discard_task
+ if task is None or task.done():
+ task = asyncio.create_task(
+ self._discard_and_remove(session), name=f"whatsapp-connect-discard-{session.id}",
+ )
+ task.add_done_callback(self._observe_task)
+ session.discard_task = task
+ # Closing a browser/request must not drop the native writer's owner.
+ await asyncio.shield(task)
+
+ async def _discard_and_remove(self, session: WhatsAppConnectSession) -> None:
finalize_task = session.finalize_task
if (
finalize_task is not None
@@ -205,9 +251,10 @@ class WhatsAppConnectStore:
if not finalize_task.done():
finalize_task.cancel()
await asyncio.gather(finalize_task, return_exceptions=True)
- else:
- await self._close_session(session)
+ await self._close_session(session)
self._remove_database(session.pending_path)
+ if self._sessions.get(session.id) is session:
+ del self._sessions[session.id]
@staticmethod
async def _connect(
@@ -229,36 +276,55 @@ class WhatsAppConnectStore:
while not session.qr_url and not session.result.done():
await asyncio.sleep(0.05)
+ async def _close_session(self, session: WhatsAppConnectSession) -> None:
+ task = session.stop_task
+ if task is None or (task.done() and not task.cancelled() and task.exception() is not None):
+ task = asyncio.create_task(
+ self._stop_session(session), name=f"whatsapp-connect-stop-{session.id}",
+ )
+ task.add_done_callback(self._observe_task)
+ session.stop_task = task
+ try:
+ await asyncio.wait_for(asyncio.shield(task), timeout=_NATIVE_STOP_TIMEOUT_SECONDS)
+ except TimeoutError as exc:
+ raise RuntimeError(
+ "WhatsApp is still stopping. Retry cancelling the connection before updating."
+ ) from exc
+
+ @staticmethod
+ def _observe_task(task: asyncio.Task[None]) -> None:
+ if not task.cancelled():
+ task.exception()
+
+ @staticmethod
+ def _session_stopped(session: WhatsAppConnectSession) -> bool:
+ task = session.stop_task
+ return task is not None and task.done() and not task.cancelled() and task.exception() is None
+
@staticmethod
- async def _close_session(session: WhatsAppConnectSession) -> None:
+ async def _stop_session(session: WhatsAppConnectSession) -> None:
+ if session.expiry_task is not None:
+ session.expiry_task.cancel()
+ await asyncio.gather(session.expiry_task, return_exceptions=True)
if not session.result.done():
session.result.cancel()
- if not session.connect_task.done():
- session.connect_task.cancel()
- with suppress(Exception, asyncio.CancelledError):
- await session.connect_task
- native_task: asyncio.Task[Any] | None = None
- if session.connect_task.done() and not session.connect_task.cancelled():
- with suppress(Exception, asyncio.CancelledError):
- native_task = session.connect_task.result()
+ elif not session.result.cancelled():
+ session.result.exception()
+ # Both Stop and Neonize use asyncio.to_thread in the supported SDK.
+ # Cancellation cannot join those threads. Signal, then await actual return;
+ # the bounded caller may time out without cancelling this owned task.
+ await session.client.stop()
+ await asyncio.shield(asyncio.gather(session.connect_task, return_exceptions=True))
+ if session.connect_task.cancelled():
+ raise RuntimeError("WhatsApp connection shutdown could not be verified")
+ native_task = session.connect_task.result()
client_native_task = getattr(session.client, "connect_task", None)
if native_task is None and isinstance(client_native_task, asyncio.Task):
native_task = cast(asyncio.Task[Any], client_native_task)
- with suppress(Exception):
- await asyncio.wait_for(session.client.stop(), timeout=5)
if native_task is not None:
- if not native_task.done():
- try:
- # Stop only signals neonize's Go worker. Wait for that worker
- # to return so Windows releases its SQLite file handle before
- # the temporary login database is promoted.
- await asyncio.wait_for(
- asyncio.shield(native_task),
- timeout=_NATIVE_STOP_TIMEOUT_SECONDS,
- )
- except TimeoutError:
- native_task.cancel()
- await asyncio.gather(native_task, return_exceptions=True)
+ await asyncio.shield(asyncio.gather(native_task, return_exceptions=True))
+ if native_task.cancelled():
+ raise RuntimeError("WhatsApp native shutdown could not be verified")
@staticmethod
def _build_channel() -> tuple[WhatsAppChannel, Path]:
@@ -327,7 +393,7 @@ class WhatsAppConnectStore:
"session_id": session.id,
"status": "pending",
"interval_ms": 2000,
- "expires_at_ms": int((session.created_wall + 600) * 1000),
+ "expires_at_ms": int((session.created_wall + _CONNECT_TTL_SECONDS) * 1000),
"message": "Waiting for the WhatsApp scan.",
}
if session.qr_url:
diff --git a/nanobot/channels/whatsapp/tests/test_connect.py b/nanobot/channels/whatsapp/tests/test_connect.py
index c75f4c292..7fd889cf8 100644
--- a/nanobot/channels/whatsapp/tests/test_connect.py
+++ b/nanobot/channels/whatsapp/tests/test_connect.py
@@ -2,6 +2,7 @@ from __future__ import annotations
import asyncio
import os
+import threading
from pathlib import Path
from types import SimpleNamespace
from typing import Any
@@ -41,7 +42,8 @@ class _FakeClient:
await self.native_stop.wait()
self.native_released = True
return
- await asyncio.Event().wait()
+ await self.native_stop.wait()
+ self.native_released = True
async def stop(self) -> None:
if self.stop_gate is not None:
@@ -107,6 +109,7 @@ async def test_whatsapp_connect_commits_new_session_after_scan(
assert completed["status"] == "succeeded"
assert target.read_bytes() == b"new-session"
assert channel.client.stopped is True
+ assert store.has_pending_work is False
@pytest.mark.asyncio
@@ -121,6 +124,7 @@ async def test_whatsapp_connect_cancel_preserves_existing_session(
monkeypatch.setattr(store, "_build_channel", lambda: (channel, target))
started = await store.start(force=True)
+ assert store.has_pending_work is True
pending_path = Path(channel.config.database_path)
pending_path.write_bytes(b"partial-session")
cancelled = await store.cancel(started["session_id"])
@@ -129,6 +133,7 @@ async def test_whatsapp_connect_cancel_preserves_existing_session(
assert target.read_bytes() == b"working-session"
assert not pending_path.exists()
assert channel.client.stopped is True
+ assert store.has_pending_work is False
@pytest.mark.asyncio
@@ -147,6 +152,7 @@ async def test_whatsapp_connect_clears_qr_while_finishing_login(
assert finishing["status"] == "pending"
assert finishing["qr_url"] == ""
+ assert store.has_pending_work is True
stop_gate.set()
await asyncio.sleep(0)
@@ -224,3 +230,132 @@ async def test_whatsapp_connect_store_closes_pending_login(
assert started["status"] == "pending"
assert not pending_path.exists()
assert channel.client.stopped is True
+ assert store.has_pending_work is False
+
+
[email protected]("action", ["cancel", "finalize"])
+async def test_native_thread_timeout_keeps_database_and_can_retry_cleanup(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, action: str,
+) -> None:
+ """A cancelled asyncio wrapper cannot prove a native SQLite writer stopped."""
+ target = tmp_path / "neonize.db"
+ target.write_bytes(b"working-session")
+ native_entered, native_release, native_exited = (
+ threading.Event(), threading.Event(), threading.Event(),
+ )
+ channel = _FakeChannel(complete=action == "finalize", linger_until_stopped=True)
+ store = WhatsAppConnectStore()
+ monkeypatch.setattr(store, "_build_channel", lambda: (channel, target))
+ monkeypatch.setattr("nanobot.channels.whatsapp.connect._NATIVE_STOP_TIMEOUT_SECONDS", 0.03)
+
+ def native_writer() -> None:
+ native_entered.set()
+ assert native_release.wait(3)
+ native_exited.set()
+
+ async def connect() -> None:
+ await channel.client.qr_handler(b"whatsapp-qr-payload")
+ Path(channel.config.database_path).write_bytes(b"new-session")
+ if channel.client.complete:
+ channel.client.result.set_result(None)
+ await asyncio.to_thread(native_writer)
+
+ monkeypatch.setattr(channel.client, "connect", connect)
+ started = await store.start(force=True)
+ pending = Path(channel.config.database_path)
+ try:
+ assert await asyncio.to_thread(native_entered.wait, 1)
+ if action == "cancel":
+ with pytest.raises(RuntimeError, match="still stopping"):
+ await store.cancel(started["session_id"])
+ else:
+ result = await store.poll(started["session_id"])
+ assert result["status"] == "failed"
+ assert "still stopping" in result["message"]
+ assert store.has_pending_work is True
+ assert channel.client.connect_task is not None
+ assert not channel.client.connect_task.done()
+ assert not native_exited.is_set()
+ assert pending.read_bytes() == b"new-session"
+ assert target.read_bytes() == b"working-session"
+ finally:
+ native_release.set()
+ await store.cancel(started["session_id"])
+ assert native_exited.is_set()
+ assert store.has_pending_work is False
+ assert not pending.exists()
+ assert target.read_bytes() == b"working-session"
+
+
+async def test_cancelling_cleanup_waiter_keeps_owned_shutdown(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path,
+) -> None:
+ target = tmp_path / "neonize.db"
+ stop_gate = asyncio.Event()
+ channel = _FakeChannel(complete=False, stop_gate=stop_gate)
+ store = WhatsAppConnectStore()
+ monkeypatch.setattr(store, "_build_channel", lambda: (channel, target))
+ started = await store.start(force=True)
+ pending = Path(channel.config.database_path)
+ pending.write_bytes(b"partial-session")
+ waiter = asyncio.create_task(store.cancel(started["session_id"]))
+ await asyncio.sleep(0)
+ waiter.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await waiter
+ assert store.has_pending_work is True
+ assert pending.exists()
+ stop_gate.set()
+ await store.close()
+ assert store.has_pending_work is False
+ assert channel.client.native_released is True
+ assert not pending.exists()
+
+
+async def test_abandoned_login_expires_without_another_browser_poll(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path,
+) -> None:
+ target = tmp_path / "neonize.db"
+ channel = _FakeChannel(complete=False)
+ store = WhatsAppConnectStore()
+ monkeypatch.setattr(store, "_build_channel", lambda: (channel, target))
+ monkeypatch.setattr("nanobot.channels.whatsapp.connect._CONNECT_TTL_SECONDS", 0.02)
+ started = await store.start(force=True)
+ session = store._sessions[started["session_id"]]
+ try:
+ await asyncio.wait_for(channel.client.native_stop.wait(), timeout=1)
+ assert session.discard_task is not None
+ await asyncio.wait_for(asyncio.shield(session.discard_task), timeout=1)
+ assert store.has_pending_work is False
+ assert channel.client.native_released is True
+ finally:
+ await store.close()
+
+
+async def test_cancel_during_finalize_does_not_promote_login_database(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path,
+) -> None:
+ target = tmp_path / "neonize.db"
+ target.write_bytes(b"working-session")
+ stop_gate = asyncio.Event()
+ channel = _FakeChannel(complete=True, stop_gate=stop_gate)
+ store = WhatsAppConnectStore()
+ monkeypatch.setattr(store, "_build_channel", lambda: (channel, target))
+ started = await store.start(force=True)
+ assert (await store.poll(started["session_id"]))["status"] == "pending"
+ cancelling = asyncio.create_task(store.cancel(started["session_id"]))
+ await asyncio.sleep(0)
+ polling = asyncio.create_task(store.poll(started["session_id"]))
+ try:
+ assert store.has_pending_work is True
+ finally:
+ stop_gate.set()
+ cancelled, polled = await asyncio.gather(cancelling, polling)
+ assert cancelled["status"] == polled["status"] == "cancelled"
+ assert target.read_bytes() == b"working-session"
+ assert not Path(channel.config.database_path).exists()
+ assert store.has_pending_work is False
diff --git a/nanobot/cli/_macos_dock.py b/nanobot/cli/_macos_dock.py
new file mode 100644
index 000000000..b972fa870
--- /dev/null
+++ b/nanobot/cli/_macos_dock.py
@@ -0,0 +1,238 @@
+"""Windowless AppKit helper. Run as an isolated stdlib-only script, not an agent.
+
+Only the parent launcher can pass the listening socket. Its private connections
+contain browser URLs and act as lifetime leases; no configuration is persisted.
+AppKit stays on the main thread. The socket thread sleeps in select, not a GUI
+polling loop, and EOF from every launcher removes the icon.
+"""
+
+from __future__ import annotations
+
+import ctypes as c
+import ipaddress
+import selectors
+import socket
+import sys
+import threading
+from collections.abc import Callable
+from pathlib import Path
+from typing import Any
+from urllib.parse import urlsplit
+
+
+def is_local_browser_url(url: str) -> bool:
+ try:
+ parts = urlsplit(url)
+ local = parts.hostname == "localhost" or ipaddress.ip_address(parts.hostname or "").is_loopback
+ return (parts.scheme == "http" and local and parts.port is not None
+ and parts.port > 0 and parts.username is None and parts.password is None
+ and not any(ord(char) < 32 or ord(char) == 127 for char in url))
+ except ValueError:
+ return False
+
+
+class _Clients:
+ def __init__(self) -> None:
+ self.urls: dict[socket.socket, str] = {}
+ self.lock = threading.Lock()
+
+ def current_url(self) -> str | None:
+ with self.lock:
+ return next(reversed(self.urls.values()), None)
+
+ def add(self, connection: socket.socket, url: str) -> None:
+ with self.lock:
+ self.urls[connection] = url
+
+ def remove(self, connection: socket.socket) -> None:
+ with self.lock:
+ self.urls.pop(connection, None)
+
+
+def _serve(listener: socket.socket, address: Path, clients: _Clients, stop: Callable[[], None]) -> None:
+ import fcntl
+
+ listener.setblocking(False)
+ with selectors.DefaultSelector() as selector, (address.parent / "start.lock").open("a") as lock:
+ selector.register(listener, selectors.EVENT_READ)
+
+ def accept() -> None:
+ connection, _ = listener.accept()
+ connection.settimeout(0.5)
+ try:
+ with connection.makefile("rb") as stream:
+ line = stream.readline(8193)
+ if not line.endswith(b"\n") or len(line) > 8192:
+ raise ValueError("Invalid Dock request")
+ url = line[:-1].decode("utf-8")
+ if not is_local_browser_url(url):
+ raise ValueError("Invalid Dock URL")
+ clients.add(connection, url)
+ selector.register(connection, selectors.EVENT_READ)
+ connection.sendall(b"1")
+ connection.setblocking(False)
+ except (OSError, ValueError):
+ clients.remove(connection)
+ try:
+ selector.unregister(connection)
+ except KeyError:
+ pass
+ connection.close()
+
+ try:
+ while True:
+ for key, _ in selector.select(timeout=None if clients.current_url() else 0.1):
+ connection = key.fileobj
+ if connection is listener:
+ accept()
+ elif isinstance(connection, socket.socket):
+ # No commands after the initial URL. EOF (including SIGKILL)
+ # releases only this launcher's presence, never the gateway.
+ selector.unregister(connection)
+ clients.remove(connection)
+ connection.close()
+ if clients.current_url() is not None:
+ continue
+ try:
+ fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ except BlockingIOError:
+ continue
+ try:
+ # Serialize last-client exit against a new launcher's handshake.
+ while True:
+ try:
+ accept()
+ except BlockingIOError:
+ break
+ if clients.current_url() is None:
+ listener.close()
+ address.unlink(missing_ok=True)
+ return
+ finally:
+ fcntl.flock(lock, fcntl.LOCK_UN)
+ finally:
+ listener.close()
+ stop()
+
+
+class _AppKit:
+ """Small, explicit Objective-C ABI adapter; no third-party bridge or compiler."""
+
+ def __init__(self, icon: Path, clients: _Clients) -> None:
+ self.objc = c.CDLL("/usr/lib/libobjc.A.dylib")
+ self.framework = c.CDLL("/System/Library/Frameworks/AppKit.framework/AppKit")
+ for name, arguments, result in (
+ ("objc_getClass", [c.c_char_p], c.c_void_p),
+ ("sel_registerName", [c.c_char_p], c.c_void_p),
+ ("objc_allocateClassPair", [c.c_void_p, c.c_char_p, c.c_size_t], c.c_void_p),
+ ("class_addMethod", [c.c_void_p, c.c_void_p, c.c_void_p, c.c_char_p], c.c_bool),
+ ("objc_registerClassPair", [c.c_void_p], None),
+ ):
+ function = getattr(self.objc, name)
+ function.argtypes = arguments
+ function.restype = result
+ self.clients = clients
+ self.callbacks: list[Any] = []
+ self.pool = self.send(self.cls("NSAutoreleasePool"), "new")
+ self.app = self.send(self.cls("NSApplication"), "sharedApplication")
+ self.send(self.app, "setActivationPolicy:", 0, types=(c.c_long,), result=c.c_bool)
+ if self.send(self.app, "activationPolicy", result=c.c_long) != 0:
+ raise OSError("No desktop application session")
+ image = self.send(self.send(self.cls("NSImage"), "alloc"), "initWithContentsOfFile:",
+ self.string(str(icon)), types=(c.c_void_p,))
+ if not image:
+ raise OSError("Dock image unavailable")
+ self.send(self.app, "setApplicationIconImage:", image, types=(c.c_void_p,), result=None)
+ delegate_class = self.objc.objc_allocateClassPair(self.cls("NSObject"), b"NanobotDock", 0)
+
+ def open_page(_self: int, _cmd: int, _sender: int) -> None:
+ url = self.clients.current_url()
+ if url is None:
+ return
+ target = self.send(self.cls("NSURL"), "URLWithString:", self.string(url), types=(c.c_void_p,))
+ workspace = self.send(self.cls("NSWorkspace"), "sharedWorkspace")
+ if not self.send(workspace, "openURL:", target, types=(c.c_void_p,), result=c.c_bool):
+ alert = self.send(self.cls("NSAlert"), "new")
+ self.send(alert, "setMessageText:", self.string("Could not open the browser"),
+ types=(c.c_void_p,), result=None)
+ self.send(alert, "setInformativeText:", self.string("Use the WebUI link in your terminal."),
+ types=(c.c_void_p,), result=None)
+ self.send(alert, "runModal", result=c.c_long)
+
+ def reopen(_self: int, _cmd: int, sender: int, _visible: bool) -> bool:
+ open_page(_self, _cmd, sender)
+ return False
+
+ for selector, callback, signature, result, arguments in (
+ ("openPage:", open_page, b"v@:@", None, (c.c_void_p,)),
+ ("applicationShouldHandleReopen:hasVisibleWindows:", reopen, b"B@:@B",
+ c.c_bool, (c.c_void_p, c.c_bool)),
+ ):
+ wrapped = c.CFUNCTYPE(result, c.c_void_p, c.c_void_p, *arguments)(callback)
+ self.callbacks.append(wrapped) # Objective-C does not retain Python callbacks.
+ if not self.objc.class_addMethod(delegate_class, self.selector(selector),
+ c.cast(wrapped, c.c_void_p), signature):
+ raise OSError("Dock delegate unavailable")
+ self.objc.objc_registerClassPair(delegate_class)
+ self.delegate = self.send(delegate_class, "new")
+ self.send(self.app, "setDelegate:", self.delegate, types=(c.c_void_p,), result=None)
+ menu = self.send(self.cls("NSMenu"), "new")
+ for title, action, key, target in (
+ ("Open nanobot", "openPage:", "o", self.delegate),
+ ("Hide Dock Icon", "terminate:", "q", self.app),
+ ):
+ item = self.send(self.send(self.cls("NSMenuItem"), "alloc"),
+ "initWithTitle:action:keyEquivalent:", self.string(title),
+ self.selector(action), self.string(key),
+ types=(c.c_void_p, c.c_void_p, c.c_void_p))
+ self.send(item, "setTarget:", target, types=(c.c_void_p,), result=None)
+ self.send(menu, "addItem:", item, types=(c.c_void_p,), result=None)
+ root = self.send(self.cls("NSMenuItem"), "new")
+ self.send(root, "setSubmenu:", menu, types=(c.c_void_p,), result=None)
+ bar = self.send(self.cls("NSMenu"), "new")
+ self.send(bar, "addItem:", root, types=(c.c_void_p,), result=None)
+ self.send(self.app, "setMainMenu:", bar, types=(c.c_void_p,), result=None)
+ self.send(self.app, "finishLaunching", result=None)
+
+ def cls(self, name: str) -> int:
+ return self.objc.objc_getClass(name.encode())
+
+ def selector(self, name: str) -> int:
+ return self.objc.sel_registerName(name.encode())
+
+ def string(self, value: str) -> int:
+ return self.send(self.cls("NSString"), "stringWithUTF8String:", value.encode(), types=(c.c_char_p,))
+
+ def send(self, target: int, selector: str, *args: object,
+ types: tuple[Any, ...] = (), result: Any = c.c_void_p) -> Any:
+ # Give every objc_msgSend its actual ABI. Its variadic C declaration is
+ # not sufficient on Apple Silicon (and pointers must not truncate).
+ function = c.CFUNCTYPE(result, c.c_void_p, c.c_void_p, *types)(("objc_msgSend", self.objc))
+ return function(target, self.selector(selector), *args)
+
+ def stop(self) -> None:
+ pool = self.send(self.cls("NSAutoreleasePool"), "new")
+ self.send(self.app, "performSelectorOnMainThread:withObject:waitUntilDone:",
+ self.selector("terminate:"), None, False,
+ types=(c.c_void_p, c.c_void_p, c.c_bool), result=None)
+ self.send(pool, "drain", result=None)
+
+ def run(self) -> None:
+ self.send(self.app, "run", result=None)
+
+
+def main() -> None:
+ if sys.platform != "darwin" or len(sys.argv) != 4:
+ raise SystemExit(64)
+ listener = socket.socket(fileno=int(sys.argv[1]))
+ if (listener.family != socket.AF_UNIX or listener.type != socket.SOCK_STREAM
+ or listener.getsockname() != sys.argv[2]):
+ raise SystemExit(64)
+ clients = _Clients()
+ app = _AppKit(Path(sys.argv[3]), clients)
+ threading.Thread(target=_serve, args=(listener, Path(sys.argv[2]), clients, app.stop), daemon=True).start()
+ app.run()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/nanobot/cli/agent.py b/nanobot/cli/agent.py
index 09b81f28f..0263714fd 100644
--- a/nanobot/cli/agent.py
+++ b/nanobot/cli/agent.py
@@ -19,6 +19,7 @@ from nanobot.cli.runtime_config import (
_model_display,
_print_agent_start_error,
)
+from nanobot.config.schema import Config
console = Console()
@@ -117,6 +118,20 @@ def agent(
raise typer.Exit(exit_code)
return
+ from nanobot.config.home import get_home_path
+ from nanobot.config.loader import get_config_path
+ from nanobot.config.paths import get_data_dir
+ from nanobot.data_access import data_access, profile_data_paths
+
+ paths = profile_data_paths(home=get_home_path(), data_dir=get_data_dir(),
+ config=get_config_path(), workspace=runtime_config.workspace_path)
+ with data_access(paths):
+ _run_classic(runtime_config, message=message, session_id=session_id, markdown=markdown, logs=logs)
+
+
+def _run_classic(runtime_config: Config, *, message: str | None, session_id: str | None,
+ markdown: bool, logs: bool) -> None:
+ """Keep the data lease through writer initialization, execution and cleanup."""
from nanobot.agent.hooks import create_file_edit_activity_hook
from nanobot.agent.tools.image_generation import register_image_generation_tool
from nanobot.agent.tools.mcp import MCPProvider
diff --git a/nanobot/cli/assets/README.md b/nanobot/cli/assets/README.md
new file mode 100644
index 000000000..e51d207f2
--- /dev/null
+++ b/nanobot/cli/assets/README.md
@@ -0,0 +1,5 @@
+# Dock artwork
+
+`dock-icon.png` is a deterministic composition of the existing MIT-licensed nanobot cat from `webui/public/brand/nanobot_icon_512.png` (SHA-256 `d4cf9edb3c30b9e43d02fcd9974c87a8046afbf1b13903c68100ab510bd2cd41`). The cat is uniformly scaled without redrawing or recoloring. The user-approved design uses a 1024-pixel canvas, an 824-pixel rounded white tile at (100, 100), and a 656-pixel cat at (184, 168). Its optical center is 16 pixels below the tile center; shadows are separate from the original art.
+
+The packaged helper loads this PNG through AppKit. It needs neither a generated application executable nor an icon compiler at installation or launch. Keep artwork changes independent of the WebUI brand asset and of gateway lifecycle policy.
diff --git a/nanobot/cli/assets/dock-icon.png b/nanobot/cli/assets/dock-icon.png
new file mode 100644
index 000000000..2c4c09432
Binary files /dev/null and b/nanobot/cli/assets/dock-icon.png differ
diff --git a/nanobot/cli/commands.py b/nanobot/cli/commands.py
index aa42ba452..3070888c5 100644
--- a/nanobot/cli/commands.py
+++ b/nanobot/cli/commands.py
@@ -57,6 +57,7 @@ from nanobot.cli.runtime_config import ( # noqa: E402
_print_model_setup_steps,
_provider_setup_error,
)
+from nanobot.cli.update import update # noqa: E402
from nanobot.cli.webui import webui # noqa: E402
from nanobot.cli.webui_support import ( # noqa: E402
_prepare_webui_bundle_for_gateway,
@@ -96,6 +97,7 @@ app = typer.Typer(
)
console = Console()
+app.command()(update)
# Server-console pairing stays outside the agent/gateway lifecycle.
from nanobot.cli.remote import app as remote_app # noqa: E402
diff --git a/nanobot/cli/dock.py b/nanobot/cli/dock.py
new file mode 100644
index 000000000..8c6a643cc
--- /dev/null
+++ b/nanobot/cli/dock.py
@@ -0,0 +1,230 @@
+"""Best-effort macOS Dock presence for local WebUI clients and gateways.
+
+The icon owns no gateway lease or user data. Open local sockets keep one helper
+alive; the OS closes them even when a launcher is killed. Everything executable
+comes from the current installation, never a download or generated shell script.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import hashlib
+import os
+import plistlib
+import shutil
+import socket
+import stat
+import subprocess
+import sys
+import threading
+from collections.abc import Generator
+from contextlib import ExitStack, contextmanager
+from pathlib import Path
+from urllib.parse import urlsplit
+from uuid import uuid4
+
+from filelock import FileLock
+from loguru import logger
+
+_WORKER = Path(__file__).with_name("_macos_dock.py")
+_ICON = Path(__file__).with_name("assets") / "dock-icon.png"
+_STARTUP_TIMEOUT = 10
+
+
+def _desktop_available() -> bool:
+ if sys.platform != "darwin" or any(os.environ.get(key) for key in (
+ "SSH_CONNECTION", "SSH_CLIENT", "SSH_TTY",
+ )):
+ return False
+ try:
+ return os.getuid() != 0 and Path("/dev/console").stat().st_uid == os.getuid()
+ except OSError:
+ return False
+
+
+def _private_directory(path: Path) -> None:
+ path.mkdir(mode=0o700, exist_ok=True)
+ info = path.lstat()
+ if not stat.S_ISDIR(info.st_mode) or info.st_uid != os.getuid() or info.st_mode & 0o077:
+ raise PermissionError("Dock directory must be private to this user")
+
+
+def _directory(instance: Path, url: str) -> Path:
+ # Keep AF_UNIX paths short and isolate installations, instances and dev URLs.
+ # macOS AF_UNIX addresses are limited to 104 bytes. TMPDIR can be an arbitrary
+ # long path (including during isolated update acceptance); this directory is
+ # private, owner-checked and contains neither the URL nor user data.
+ root = Path("/tmp") / f"nanobot-dock-{os.getuid()}"
+ _private_directory(root)
+ origin = urlsplit(url)._replace(query="", fragment="").geturl()
+ identity = "\0".join((str(instance), sys.executable, str(_WORKER), origin)).encode()
+ digest = hashlib.sha256(identity + _WORKER.read_bytes() + _ICON.read_bytes()).hexdigest()
+ directory = root / digest[:12]
+ _private_directory(directory)
+ return directory
+
+
+def _bundle(directory: Path) -> Path:
+ """Give the existing interpreter a Dock identity, without copying its runtime."""
+ contents = directory / "nanobot.app" / "Contents"
+ executable = contents / "MacOS" / "nanobot"
+ executable.parent.mkdir(parents=True, exist_ok=True)
+ resources = contents / "Resources"
+ resources.mkdir(exist_ok=True)
+ if not executable.is_symlink():
+ executable.symlink_to(sys.executable)
+ elif os.readlink(executable) != sys.executable:
+ raise ValueError("Dock interpreter does not match this installation")
+ shutil.copyfile(_ICON, resources / "dock-icon.png")
+ (contents / "Info.plist").write_bytes(plistlib.dumps({
+ "CFBundleExecutable": "nanobot",
+ "CFBundleIdentifier": f"dev.nanobot.webui.{directory.name}",
+ "CFBundleName": "nanobot",
+ "CFBundleDisplayName": "nanobot",
+ "CFBundlePackageType": "APPL",
+ "CFBundleIconFile": "dock-icon.png",
+ "LSMinimumSystemVersion": "13.0",
+ "NSHighResolutionCapable": True,
+ }))
+ return executable
+
+
+def _connect(address: Path) -> socket.socket | None:
+ connection = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+ connection.settimeout(2)
+ try:
+ connection.connect(str(address))
+ return connection
+ except (FileNotFoundError, ConnectionRefusedError):
+ connection.close()
+ return None
+ except OSError:
+ connection.close()
+ raise
+
+
+def _attach(directory: Path, url: str) -> socket.socket:
+ address = directory / "s"
+ process: subprocess.Popen[bytes] | None = None
+ connection: socket.socket | None = None
+ with FileLock(str(directory / "start.lock"), timeout=_STARTUP_TIMEOUT):
+ try:
+ connection = _connect(address)
+ if connection is None:
+ if address.exists():
+ if not stat.S_ISSOCK(address.lstat().st_mode):
+ raise ValueError("Unexpected Dock socket path")
+ address.unlink()
+ executable = _bundle(directory)
+ with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as listener:
+ listener.bind(str(address))
+ listener.listen()
+ process = subprocess.Popen(
+ [str(executable), "-I", "-S", str(_WORKER), str(listener.fileno()),
+ str(address), str(_ICON)],
+ pass_fds=(listener.fileno(),), stdin=subprocess.DEVNULL,
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
+ start_new_session=True,
+ )
+ # Reap our child without making its lifetime depend on this thread.
+ threading.Thread(target=process.wait, daemon=True).start()
+ connection = _connect(address)
+ if connection is None:
+ raise OSError("Dock helper did not start")
+ # Connecting to the inherited listener is immediate, but the helper
+ # loads AppKit before acknowledging readiness. A cold post-update
+ # launch can exceed the short socket-connect deadline. Keep this
+ # bounded off the gateway event loop, including concurrent joiners.
+ connection.settimeout(_STARTUP_TIMEOUT)
+ # Credentials stay in the private local socket, never argv or a file.
+ connection.sendall(url.encode("utf-8") + b"\n")
+ if connection.recv(1) != b"1":
+ raise OSError("Dock helper did not become ready")
+ return connection
+ except BaseException:
+ # Ctrl-C can arrive during startup, before the context owns this socket.
+ # Clean up the new helper too, then propagate the original interruption.
+ if connection is not None:
+ connection.close()
+ if process is not None and process.poll() is None:
+ process.terminate()
+ raise
+
+
+@contextmanager
+def dock_icon(url: str, *, instance: Path, enabled: bool = True) -> Generator[None]:
+ """Show a shared icon while this WebUI launcher is attached; never own its service."""
+ connection: socket.socket | None = None
+ if enabled and _desktop_available():
+ from nanobot.cli._macos_dock import is_local_browser_url
+
+ try:
+ if is_local_browser_url(url):
+ connection = _attach(_directory(instance, url), url)
+ except (OSError, ValueError, TimeoutError) as exc:
+ # Do not include exception text: URL/installation details are private.
+ logger.debug("Dock startup failure category: {}", type(exc).__name__)
+ logger.warning("Dock icon unavailable; WebUI can still be used in your browser.")
+ try:
+ yield
+ finally:
+ if connection is not None:
+ connection.close()
+
+
+def request_gateway_icon(instance: Path, *, enabled: bool) -> None:
+ """Remember desktop intent, not a service lease, credential, or restart command."""
+ if not _desktop_available():
+ return
+ from nanobot.utils.atomic_file import atomic_write_text
+
+ try:
+ instance.parent.mkdir(parents=True, exist_ok=True)
+ atomic_write_text(instance.with_suffix(".dock"), f"{'show' if enabled else 'hide'}:{uuid4().hex}")
+ except OSError:
+ logger.warning("Dock preference unavailable; WebUI can still be used in your browser.")
+
+
+def _watch_gateway_icon(url: str, instance: Path, stopped: threading.Event) -> None:
+ """One bounded native handshake off the event loop for each explicit request."""
+ selected = ""
+ presence = ExitStack()
+ try:
+ while not stopped.is_set():
+ try:
+ with instance.with_suffix(".dock").open(encoding="ascii") as stream:
+ request = stream.read(64)
+ except (OSError, UnicodeError):
+ request = ""
+ if request != selected:
+ replacement = ExitStack()
+ if request.startswith("show:"):
+ # Join before releasing our old connection, so reopening the
+ # launcher cannot race the last-client cleanup of a live icon.
+ replacement.enter_context(dock_icon(url, instance=instance))
+ presence.close()
+ presence = replacement
+ selected = request
+ stopped.wait(0.5)
+ finally:
+ presence.close()
+
+
+async def watch_gateway_icon(url: str, *, instance: Path, activated: asyncio.Event) -> None:
+ """Own optional Dock presence only after ordinary/protected startup is activated.
+
+ The persisted request lets an existing gateway observe a detached launcher and
+ lets the next gateway generation restore it. No updater or data format changes.
+ Quitting the icon is respected until another explicit request or service start.
+ """
+ if not _desktop_available():
+ return
+ await activated.wait()
+ stopped = threading.Event()
+ watcher = asyncio.create_task(asyncio.to_thread(_watch_gateway_icon, url, instance, stopped))
+ try:
+ await asyncio.shield(watcher)
+ finally:
+ stopped.set()
+ # Never leave a still-starting helper behind when the gateway is cancelled.
+ await watcher
diff --git a/nanobot/cli/entry.py b/nanobot/cli/entry.py
index 860ec48d1..f8e28209a 100644
--- a/nanobot/cli/entry.py
+++ b/nanobot/cli/entry.py
@@ -7,8 +7,7 @@ import sys
from contextlib import suppress
from nanobot.cli.process_identity import set_cli_process_identity
-from nanobot.utils.log_config import configure_console_logging
-from nanobot.utils.rotating_output import configure_background_output_from_env
+from nanobot.installation_lock import InstallationBusyError, installation_access
_ROOT_OPTIONS = frozenset(
{
@@ -48,7 +47,8 @@ def _native_tui_candidate(args: list[str]) -> bool:
return True
-def _configure_windows_console() -> None:
+def configure_windows_console() -> None:
+ """Keep multilingual output usable for CLI and protected gateway startup."""
if sys.platform != "win32" or sys.stdout.encoding == "utf-8":
return
os.environ["PYTHONIOENCODING"] = "utf-8"
@@ -61,6 +61,8 @@ def _configure_windows_console() -> None:
def _run_agent(args: list[str], *, prog_name: str) -> None:
"""Run the shared agent command without importing the complete CLI graph."""
+ from nanobot.utils.log_config import configure_console_logging
+
configure_console_logging(sys.stderr)
import typer
@@ -72,8 +74,46 @@ def _run_agent(args: list[str], *, prog_name: str) -> None:
command.main(args=args, prog_name=prog_name)
+def _command_args(args: list[str]) -> list[str]:
+ """Skip only global home selectors, not arguments belonging to a subcommand."""
+ position = 0
+ while position < len(args):
+ argument = args[position]
+ if argument == "--home":
+ position += 2
+ elif argument.startswith("--home="):
+ position += 1
+ else:
+ return args[position:]
+ return []
+
+
def main() -> None:
+ """Acquire a runtime lease before loading application code."""
+ args = _command_args(sys.argv[1:])
+ saved_update = args[:1] == ["update"] and any(argument.split("=", 1)[0] == "--job" for argument in args[1:])
+ if args[:1] == ["update"] and not saved_update:
+ # The update entrypoint takes its own exclusive lease only for execution.
+ # Saved pre-mutation recovery instead owns a read lease before imports;
+ # its detached worker can replace files only after this process exits.
+ _dispatch()
+ return
+ try:
+ # Keep the repair/stop path usable after an interrupted older updater.
+ # These commands still take a lease and cannot run during a live install.
+ diagnostics = args[:1] in (["--help"], ["-h"], ["--version"], ["-v"])
+ stop_or_inspect = args[:2] in (["gateway", "stop"], ["gateway", "status"], ["gateway", "logs"])
+ with installation_access(allow_incomplete=diagnostics or stop_or_inspect):
+ _dispatch()
+ except InstallationBusyError as exc:
+ print(str(exc), file=sys.stderr)
+ raise SystemExit(1) from exc
+
+
+def _dispatch() -> None:
"""Dispatch native TUI startup without importing the complete CLI graph."""
+ from nanobot.utils.rotating_output import configure_background_output_from_env
+
configure_background_output_from_env()
raw_args = sys.argv[1:]
# Installed completion scripts call ``nanobot`` without positional arguments
@@ -83,7 +123,16 @@ def main() -> None:
agent_args = None if shell_completion else _agent_invocation_args(raw_args)
dispatch_args = ["agent", *agent_args] if agent_args is not None else raw_args
set_cli_process_identity(dispatch_args)
- _configure_windows_console()
+ configure_windows_console()
+ if not shell_completion and raw_args[:1] == ["update"]:
+ import typer
+
+ from nanobot.cli.update import update
+
+ update_app = typer.Typer(add_completion=False)
+ update_app.command()(update)
+ typer.main.get_command(update_app).main(args=raw_args[1:], prog_name="nanobot update")
+ return
if not shell_completion and not raw_args:
from nanobot.cli.desktop_target import dispatch_bare_desktop_target
diff --git a/nanobot/cli/gateway.py b/nanobot/cli/gateway.py
index 07a34c338..6ccb35021 100644
--- a/nanobot/cli/gateway.py
+++ b/nanobot/cli/gateway.py
@@ -241,6 +241,7 @@ def create_gateway_app(
run_gateway(
cfg,
port=port,
+ verbose=verbose,
webui_bundle_mode=interactive_build_mode(),
unconfigured_provider_error=unconfigured_provider_error,
gateway_instance=instance,
diff --git a/nanobot/cli/gateway_runtime.py b/nanobot/cli/gateway_runtime.py
index b1b67e85b..162da8ea5 100644
--- a/nanobot/cli/gateway_runtime.py
+++ b/nanobot/cli/gateway_runtime.py
@@ -3,11 +3,11 @@
import asyncio
import signal
from collections.abc import Awaitable, Callable, Coroutine, Iterable
-from contextlib import suppress
-from dataclasses import replace
+from contextlib import ExitStack, suppress
+from dataclasses import asdict, replace
from functools import partial
from pathlib import Path
-from typing import Any, cast
+from typing import TYPE_CHECKING, Any, cast
import typer
from loguru import logger
@@ -26,6 +26,7 @@ from nanobot.agent.tools.registry import ToolRegistry
from nanobot.bus.events import OutboundMessage
from nanobot.bus.queue import MessageBus
from nanobot.cli import terminal as cli_terminal
+from nanobot.cli.dock import watch_gateway_icon
from nanobot.cli.runtime_config import _migrate_cron_store
from nanobot.cli.webui_support import (
_gateway_health_bind_note,
@@ -40,9 +41,10 @@ from nanobot.cli.webui_support import (
_webui_display_url,
_webui_endpoint_reachable,
)
-from nanobot.config.paths import is_default_workspace
+from nanobot.config.paths import get_data_dir, is_default_workspace
from nanobot.config.schema import Config
-from nanobot.gateway.runtime import GatewayInstance
+from nanobot.gateway.runtime import GatewayHealthIdentity, GatewayInstance, GatewayRuntime
+from nanobot.installation_lock import installation_access
from nanobot.security.network import is_loopback_host
from nanobot.session.keys import (
HEARTBEAT_SESSION_KEY,
@@ -58,6 +60,10 @@ from nanobot.webui.build import BuildMode
from nanobot.webui.dev import WebUIDevError, WebUIDevServer
from nanobot.webui.sidebar_state import read_webui_sidebar_state
+if TYPE_CHECKING:
+ from nanobot.update_profiles import ProfileReceipt
+ from nanobot.update_restart import GatewayStartup
+
__all__ = ["_run_gateway"]
console = Console()
@@ -414,6 +420,7 @@ def _run_gateway(
config: Config,
*,
port: int | None = None,
+ verbose: bool = False,
open_browser_url: str | None = None,
open_browser_ready_url: str | None = None,
webui_static_dist: bool = True,
@@ -424,8 +431,61 @@ def _run_gateway(
unconfigured_provider_error: str | None = None,
webui_dev_server: WebUIDevServer | None = None,
gateway_instance: GatewayInstance | None = None,
+ update_startup: "GatewayStartup | None" = None,
) -> None:
- """Shared gateway runtime; ``open_browser_url`` opens a tab once channels are up."""
+ """Claim the installation and profile before initializing any runtime writers."""
+ from nanobot.config.loader import get_config_path
+ from nanobot.update_profiles import record_gateway_profile
+
+ port = port if port is not None else config.gateway.port
+ instance = gateway_instance or GatewayInstance.resolve(config_path=get_config_path())
+ gateway_runtime = GatewayRuntime(paths=instance.paths)
+ with installation_access(allow_incomplete=update_startup is not None):
+ if update_startup is not None:
+ update_startup.validate_installation()
+ with (
+ gateway_runtime.foreground_instance(instance.start_options(port=port, verbose=verbose)),
+ record_gateway_profile(instance, gateway_runtime, data_dir=get_data_dir(),
+ workspace=config.workspace_path, port=port, verbose=verbose,
+ grant=update_startup.grant if update_startup else None,
+ cooperative_stop=True) as profile,
+ ):
+ if update_startup is not None:
+ update_startup.validate_profile(profile)
+ _run_claimed_gateway(
+ config, port=port, gateway_instance=instance, gateway_runtime=gateway_runtime,
+ health_identity=profile.health_identity, update_startup=update_startup,
+ update_profile=profile,
+ open_browser_url=open_browser_url, open_browser_ready_url=open_browser_ready_url,
+ webui_static_dist=webui_static_dist, webui_bundle_mode=webui_bundle_mode,
+ webui_runtime_surface=webui_runtime_surface,
+ webui_runtime_capabilities=webui_runtime_capabilities,
+ health_server_enabled=health_server_enabled,
+ unconfigured_provider_error=unconfigured_provider_error,
+ webui_dev_server=webui_dev_server,
+ )
+
+
+def _run_claimed_gateway(
+ config: Config,
+ *,
+ port: int,
+ gateway_instance: GatewayInstance,
+ gateway_runtime: GatewayRuntime,
+ health_identity: GatewayHealthIdentity,
+ open_browser_url: str | None,
+ open_browser_ready_url: str | None,
+ webui_static_dist: bool,
+ webui_bundle_mode: BuildMode,
+ webui_runtime_surface: str,
+ webui_runtime_capabilities: dict[str, Any] | None,
+ health_server_enabled: bool,
+ unconfigured_provider_error: str | None,
+ webui_dev_server: WebUIDevServer | None,
+ update_startup: "GatewayStartup | None" = None,
+ update_profile: "ProfileReceipt | None" = None,
+) -> None:
+ """Initialize and run only while the caller holds the gateway lifecycle claim."""
from nanobot.agent.model_presets import load_model_preset_catalog
from nanobot.agent.tools.message import MessageTool
from nanobot.agent.turn_delivery import TurnDeliveryFactory
@@ -455,7 +515,6 @@ def _run_gateway(
from nanobot.triggers.local_store import LocalTriggerStore
from nanobot.webui.recovery import RecoveryCoordinator
- port = port if port is not None else config.gateway.port
webui_url = _webui_browser_url(config)
gateway_host_for_browser = _host_for_local_browser(config.gateway.host)
if health_server_enabled and _tcp_endpoint_reachable(gateway_host_for_browser, port):
@@ -514,19 +573,12 @@ def _run_gateway(
session_manager = SessionManager(config.workspace_path)
# Use the same runtime identity for foreground and managed gateway processes.
- from nanobot.config.loader import get_config_path
from nanobot.gateway.runtime import (
GatewayClientLease,
- GatewayRuntime,
monitor_gateway_clients,
)
- instance = gateway_instance or GatewayInstance.resolve(
- config_path=get_config_path(),
- )
- config_path = str(instance.config_path)
- gateway_runtime = GatewayRuntime(paths=instance.paths)
- gateway_start_options = instance.start_options(port=port)
+ config_path = str(gateway_instance.config_path)
# Preserve existing single-workspace installs, but keep custom workspaces clean.
if is_default_workspace(config.workspace_path):
@@ -534,7 +586,7 @@ def _run_gateway(
# Create cron service with workspace-scoped store
cron_store_path = config.workspace_path / "cron" / "jobs.json"
- cron = CronService(cron_store_path)
+ cron = CronService(cron_store_path, admission=bus.admission)
trigger_store = LocalTriggerStore(config.workspace_path)
webui_route_policy = WebuiTurnRoutePolicy(session_manager)
@@ -851,6 +903,8 @@ def _run_gateway(
if method == "GET" and path == "/health":
ready, payload = _gateway_readiness_payload(channels)
+ payload["runtime"] = asdict(health_identity)
+ payload["maintenance"] = bus.admission.paused
body = _json.dumps(payload)
status = "200 OK" if ready else "503 Service Unavailable"
content_type = "application/json"
@@ -957,6 +1011,8 @@ def _run_gateway(
console.print(f"[yellow]Could not open browser ({e}); visit {display_url}[/yellow]")
async def run() -> None:
+ startup_gate = ExitStack()
+ desktop_activated = asyncio.Event()
tasks: list[asyncio.Task[Any]] = []
shutdown_task: asyncio.Task[Any] | None = None
runtime_tasks: asyncio.Future[list[Any]] | None = None
@@ -971,15 +1027,20 @@ def _run_gateway(
)
try:
await agent.subagents.recover_interrupted()
- await cron.start()
# Re-read once on first admission to close the watcher subscription window.
agent.runtime_resolver.invalidate()
# Recovery must finish before WebSocket and other channels begin
# accepting new input. That makes a new user message reliably
# supersede an old recoverable turn instead of racing its queue.
await recovery.scan()
+ if update_startup is not None:
+ # Recovery may reconstruct queued work, but no consumer or
+ # external listener has started. Keep that work parked too.
+ startup_gate.enter_context(bus.admission.pause_before_start())
+ await cron.start()
async def _run_agent() -> None:
try:
+ await bus.admission.wait_until_open()
await mcp_provider.connect()
await agent.run()
finally:
@@ -1012,6 +1073,7 @@ def _run_gateway(
store=trigger_store,
submit_turn=agent.submit_local_trigger_turn,
is_channel_enabled=lambda name: channels.get_channel(name) is not None,
+ admission=bus.admission,
),
name="nanobot-local-triggers",
),
@@ -1020,6 +1082,28 @@ def _run_gateway(
name="nanobot-gateway-client-monitor",
),
])
+ if update_startup is not None:
+ async def activate(startup: "GatewayStartup") -> None:
+ await startup.wait_for_activation(health_identity)
+ startup_gate.close()
+ desktop_activated.set()
+
+ tasks.append(asyncio.create_task(activate(update_startup), name="nanobot-update-activation"))
+ else:
+ desktop_activated.set()
+ if _webui_channel_enabled(config):
+ tasks.append(asyncio.create_task(
+ watch_gateway_icon(webui_url, instance=gateway_instance.paths.state_path,
+ activated=desktop_activated),
+ name="nanobot-dock",
+ ))
+ if update_profile is not None:
+ from nanobot.update_stop import watch_gateway_stop
+
+ tasks.append(asyncio.create_task(
+ watch_gateway_stop(update_profile, agent.maintenance, shutdown_event, startup_gate),
+ name="nanobot-update-stop",
+ ))
if health_server_enabled:
tasks.append(asyncio.create_task(
_health_server(config.gateway.host, port),
@@ -1085,12 +1169,12 @@ def _run_gateway(
)
await bus.drain()
finally:
+ # On a failed/aborted startup, keep intake closed until all
+ # runtime consumers have been cancelled and cleanup finished.
+ startup_gate.close()
restore_shutdown_handlers()
- with (
- gateway_runtime.foreground_instance(gateway_start_options),
- webui_turn_coordinator.connected(),
- ):
+ with webui_turn_coordinator.connected():
if health_server_enabled:
gateway_runtime.publish_health_host(config.gateway.host)
asyncio.run(run())
diff --git a/nanobot/cli/tui_launcher.py b/nanobot/cli/tui_launcher.py
index e12f83655..895489816 100644
--- a/nanobot/cli/tui_launcher.py
+++ b/nanobot/cli/tui_launcher.py
@@ -17,6 +17,7 @@ from pathlib import Path
from typing import TYPE_CHECKING, Any, cast
from nanobot import __version__
+from nanobot.bun import BunUnavailableError, bun_environment, ensure_bun
from nanobot.cli.process_identity import named_executable
from nanobot.cli.runtime_config import _model_display
from nanobot.cli.webui_support import (
@@ -187,12 +188,12 @@ def resolve_tui_command(*, data_dir: Path | None = None) -> list[str]:
asset = f"nanobot-tui-{system}-{machine}{suffix}"
source_dir = _source_checkout_tui_dir()
if source_dir is not None:
- bun = shutil.which("bun")
- if not bun:
- raise TuiUnavailableError(
- "this source checkout requires Bun to run its matching TUI; "
- "install Bun, then run `nanobot agent` again"
- )
+ try:
+ bun = ensure_bun()
+ except BunUnavailableError as exc:
+ available = shutil.which("bun")
+ hint = f" (Bun found at {available!r} but could not be used)" if available else ""
+ raise TuiUnavailableError(f"{exc}{hint}") from exc
return _resolve_source_tui_command(source_dir, bun, data_dir=data_dir)
packaged = Path(__file__).resolve().parents[1] / "tui" / "bin" / asset
@@ -229,13 +230,15 @@ def _resolve_source_tui_command(
) -> list[str]:
dependency = source_dir / "node_modules" / "@opentui" / "core"
try:
- install = subprocess.run(
- [bun, "install", "--frozen-lockfile"],
- cwd=source_dir,
- capture_output=True,
- text=True,
- check=False,
- )
+ with bun_environment(bun) as env:
+ install = subprocess.run(
+ [bun, "install", "--frozen-lockfile"],
+ cwd=source_dir,
+ capture_output=True,
+ text=True,
+ check=False,
+ env=env,
+ )
except OSError as exc:
raise TuiUnavailableError(f"could not install TUI dependencies: {exc}") from exc
if install.returncode != 0 or not dependency.is_dir():
diff --git a/nanobot/cli/update.py b/nanobot/cli/update.py
new file mode 100644
index 000000000..d11ee4658
--- /dev/null
+++ b/nanobot/cli/update.py
@@ -0,0 +1,87 @@
+"""Command-line updates for release and source installations."""
+
+import asyncio
+import subprocess
+from typing import Literal
+
+import httpx
+import typer
+
+
+def update(
+ dev: bool = typer.Option(False, "--dev", "--update-dev", help="Install or update an editable source checkout and build its WebUI."),
+ check: bool = typer.Option(False, "--check", help="Check the latest stable release without installing."),
+ allow_downgrade: bool = typer.Option(False, "--allow-downgrade", help="Allow an intentional return to an older stable release. Back up data first."),
+ plan: bool = typer.Option(False, "--plan", help="Save an exact release plan without installing or restarting."),
+ channel: Literal["stable", "preview"] | None = typer.Option(None, "--channel", help="Release channel to inspect with --plan (default: saved subscription)."),
+ job: str | None = typer.Option(None, "--job", help="Read an exact saved job in this installation; does not install."),
+ retry_handoff: bool = typer.Option(False, "--retry-handoff", help="With --job, explicitly retry shutdown before package mutation."),
+ previous_confirmation: str | None = typer.Option(None, "--previous-confirmation", help="The execution confirmation from the job being retried."),
+ confirm_restart: bool = typer.Option(False, "--confirm-restart", help="Confirm the saved plan's shutdown, installation and restart."),
+) -> None:
+ """Update nanobot in the current Python environment."""
+ if job is not None or retry_handoff or previous_confirmation is not None or confirm_restart:
+ if job is None or dev or check or allow_downgrade or plan or channel is not None:
+ raise typer.BadParameter("Use --job separately from release selection and legacy update flags.")
+ if retry_handoff != (previous_confirmation is not None and confirm_restart):
+ raise typer.BadParameter("Retry requires --retry-handoff, --previous-confirmation and --confirm-restart together.")
+ if not retry_handoff and (previous_confirmation is not None or confirm_restart):
+ raise typer.BadParameter("Reading --job cannot authorize a restart.")
+ _saved_job(job, previous_confirmation if retry_handoff else None)
+ return
+
+ from nanobot import __version__
+ from nanobot.update import latest_release, update_installation
+
+ if plan:
+ if dev or check or allow_downgrade:
+ raise typer.BadParameter("Use --plan with --channel, without execution flags.")
+ from nanobot.update_plan import describe_plan, preview_release_update
+
+ try:
+ typer.echo(describe_plan(asyncio.run(preview_release_update(channel))))
+ except (RuntimeError, OSError, ValueError, subprocess.SubprocessError, httpx.HTTPError) as exc:
+ typer.echo(f"Could not prepare update plan: {exc}", err=True)
+ raise typer.Exit(1) from exc
+ return
+ if channel is not None:
+ raise typer.BadParameter("Channel inspection requires --plan; confirm channel-aware installation in Settings → About.")
+
+ if check and dev:
+ raise typer.BadParameter("--check checks PyPI releases; use it without --dev.")
+ try:
+ if check:
+ from nanobot.installation_lock import installation_access
+
+ with installation_access():
+ typer.echo(f"Installed: {__version__}\nLatest release: {latest_release()}")
+ return
+ result = update_installation(dev=dev, allow_downgrade=allow_downgrade, output=typer.echo)
+ except (RuntimeError, OSError, ValueError) as exc:
+ typer.echo(f"Update failed: {exc}", err=True)
+ raise typer.Exit(1) from exc
+ if result["requires_restart"]:
+ typer.echo(f"Installed nanobot {result['version']}. Restart nanobot to use it; the running process has not been verified.")
+ else:
+ typer.echo(f"nanobot {result['version']} is already installed. No files changed.")
+
+
+def _saved_job(plan_id: str, previous_confirmation: str | None) -> None:
+ from nanobot.installation_lock import installation_access, installation_state_dir
+ from nanobot.update_jobs import read_update_job, retry_handoff
+ from nanobot.update_service import UpdateRetryRequest
+
+ try:
+ # The console bootstrap also owns this before importing application
+ # dependencies. Do not use this route to repair a mutated environment.
+ with installation_access():
+ job = read_update_job(plan_id)
+ if previous_confirmation is not None:
+ request = UpdateRetryRequest(id=plan_id, previous_confirmation_id=previous_confirmation,
+ confirm_restart=True)
+ retry_handoff(installation_state_dir() / "jobs" / request.id, request.previous_confirmation_id)
+ job = read_update_job(plan_id)
+ typer.echo(job.model_dump_json(indent=2))
+ except (OSError, RuntimeError, ValueError, KeyError) as exc:
+ typer.echo("Could not read or retry this saved handoff. No automatic repair was started.", err=True)
+ raise typer.Exit(1) from exc
diff --git a/nanobot/cli/webui.py b/nanobot/cli/webui.py
index 64bd9d93c..41fe275fc 100644
--- a/nanobot/cli/webui.py
+++ b/nanobot/cli/webui.py
@@ -1,5 +1,8 @@
"""WebUI CLI command."""
+import hashlib
+import sys
+from contextlib import ExitStack
from pathlib import Path
import typer
@@ -7,6 +10,7 @@ from pydantic import ValidationError
from rich.console import Console
from nanobot.cli import terminal as cli_terminal
+from nanobot.cli.dock import dock_icon, request_gateway_icon
from nanobot.cli.runtime_config import (
_print_config_error,
_print_runtime_config_validation_error,
@@ -84,6 +88,8 @@ def webui(
help="Run the Vite development server with live frontend updates",
),
no_open: bool = typer.Option(False, "--no-open", help="Do not open a browser"),
+ no_dock: bool = typer.Option(False, "--no-dock", help="Do not show the macOS Dock icon"),
+ detach: bool = typer.Option(False, "--detach", help="Keep the gateway running and return to the terminal"),
yes: bool = typer.Option(
False,
"--yes",
@@ -98,6 +104,14 @@ def webui(
GatewayInstance,
GatewayRuntime,
)
+ from nanobot.installation_receipt import RECEIPT_NAME, managed_extras
+
+ receipt = Path(sys.prefix) / RECEIPT_NAME
+ if receipt.exists() and not dev:
+ managed_extras(str(Path(sys.prefix).resolve()), hashlib.sha256(receipt.read_bytes()).hexdigest())
+ detach = True
+ if detach and dev:
+ raise typer.BadParameter("--detach cannot keep a Vite development server alive")
cli_terminal._ensure_interactive_tty_mode()
config_path = _resolve_webui_config_path(config)
@@ -207,7 +221,7 @@ def webui(
def announce_ready(url: str, *, managed: bool) -> None:
_print_webui_ready(
runtime_config, config_path, url, workspace=workspace, dev=dev, managed=managed,
- provider_error=provider_error,
+ provider_error=provider_error, detached=detach,
)
if not no_open:
_open_webui_browser(url, wait=False)
@@ -228,8 +242,31 @@ def webui(
)
raise typer.Exit(1)
+ if detach:
+ status = runtime.status()
+ if existing_gateway and not status.running:
+ raise typer.BadParameter("The existing gateway has another owner; use its launch command")
+ request_gateway_icon(runtime.paths.state_path, enabled=not no_dock)
+ if changed_webui and status.running:
+ result = runtime.restart(start_options, timeout_s=20)
+ if result.ok:
+ # Restart retains the old lifetime; detached launch promotes it.
+ result = runtime.start_background(start_options)
+ else:
+ result = runtime.start_background(start_options)
+ if not result.ok and result.message != "gateway_already_running":
+ console.print(f"[red]Gateway could not start: {result.message}[/red]")
+ raise typer.Exit(1)
+ if not _wait_for_webui(webui_url, timeout_s=20):
+ console.print("[red]WebUI did not become ready. Check the gateway logs.[/red]")
+ console.print(f"Logs: {runtime.paths.log_path}", markup=False)
+ raise typer.Exit(1)
+ announce_ready(webui_url, managed=True)
+ return
+
lease = GatewayClientLease(runtime, kind="webui")
lease.acquire()
+ desktop = ExitStack()
try:
if not existing_gateway:
console.print("[dim]Starting WebUI…[/dim]")
@@ -249,6 +286,9 @@ def webui(
output=lambda message: console.print(message, style="dim", markup=False),
) as dev_server:
managed = not existing_gateway or runtime.status().running
+ desktop.enter_context(dock_icon(
+ dev_browser_url, instance=runtime.paths.state_path, enabled=not no_dock,
+ ))
announce_ready(dev_browser_url, managed=managed)
if managed:
_attach_to_background_gateway(
@@ -268,8 +308,12 @@ def webui(
return
managed = not existing_gateway or runtime.status().running
+ desktop.enter_context(dock_icon(
+ webui_url, instance=runtime.paths.state_path, enabled=managed and not no_dock,
+ ))
announce_ready(webui_url, managed=managed)
if managed:
_attach_to_background_gateway(runtime, log_cursor=log_cursor)
finally:
+ desktop.close()
lease.release(wait_for_stop=False)
diff --git a/nanobot/cli/webui_support.py b/nanobot/cli/webui_support.py
index 88e80b77c..bb84c59b1 100644
--- a/nanobot/cli/webui_support.py
+++ b/nanobot/cli/webui_support.py
@@ -549,6 +549,7 @@ def _print_webui_ready(
dev: bool,
managed: bool,
provider_error: str | None = None,
+ detached: bool = False,
) -> None:
"""Show one ready state and a complete browser handoff in the local terminal."""
ws_cfg = _webui_config_dict(config)
@@ -575,7 +576,11 @@ def _print_webui_ready(
console.print()
log_command = _gateway_instance_command("logs", config_path=config_path, workspace=workspace)
console.print(Text(f"Logs: {log_command}", style="dim"), soft_wrap=True)
- if managed:
+ if detached:
+ stop_command = _gateway_instance_command("stop", config_path=config_path, workspace=workspace)
+ lifecycle = "Running in the background. Closing the browser or terminal does not stop nanobot.\n"
+ lifecycle += f"Stop nanobot: {stop_command}"
+ elif managed:
lifecycle = "Keep this terminal open while using WebUI.\n"
lifecycle += "Ctrl+C stops development mode." if dev else "Press Ctrl+C to exit."
else:
diff --git a/nanobot/cron/service.py b/nanobot/cron/service.py
index c76b75e68..6621cc6f8 100644
--- a/nanobot/cron/service.py
+++ b/nanobot/cron/service.py
@@ -26,6 +26,7 @@ from nanobot.cron.types import (
CronSchedule,
CronStore,
)
+from nanobot.runtime_admission import RuntimeAdmission
from nanobot.runtime_context import RUNTIME_CONTEXT_INPUT_META
from nanobot.utils.helpers import atomic_write_text
from nanobot.utils.run_records import (
@@ -202,7 +203,10 @@ class CronService:
store_path: Path,
on_job: Callable[[CronJob], Coroutine[Any, Any, str | CronRunResult | None]] | None = None,
max_sleep_ms: int = 300_000, # 5 minutes
+ *,
+ admission: RuntimeAdmission | None = None,
):
+ self.admission = admission if admission is not None else RuntimeAdmission()
self.store_path = store_path
self._action_path = store_path.parent / "action.jsonl"
self._run_records_dir = store_path.parent / "runs"
@@ -550,6 +554,13 @@ class CronService:
async def _on_timer(self) -> None:
"""Handle timer tick - run due jobs."""
+ # Do not spin on an overdue timestamp or consume jobs while paused.
+ # stop() cancels this waiter; an aborted maintenance wakes it normally.
+ await self.admission.wait_until_open()
+ with self.admission.activity():
+ await self._run_timer()
+
+ async def _run_timer(self) -> None:
reload_store = self._active_executions == 0
self._active_executions += 1
try:
@@ -934,6 +945,10 @@ class CronService:
async def run_job(self, job_id: str, force: bool = False) -> bool:
"""Manually run a job without disturbing the service's running state."""
+ with self.admission.activity():
+ return await self._run_job(job_id, force)
+
+ async def _run_job(self, job_id: str, force: bool) -> bool:
reload_store = self._active_executions == 0
self._active_executions += 1
try:
diff --git a/nanobot/data_access.py b/nanobot/data_access.py
new file mode 100644
index 000000000..94be1739d
--- /dev/null
+++ b/nanobot/data_access.py
@@ -0,0 +1,368 @@
+"""Account-scoped leases for named nanobot stores shared by Python installations.
+
+Runtimes share leases; backup/install maintenance requires exclusive access. Two
+lease namespaces cover overlapping store roots in both directions. This coordinates
+participating runtimes, not older versions, other accounts, external databases or
+arbitrary project files.
+Each process must acquire its own lease; a parent's exit must not unlock a pip child.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import os
+import re
+from collections.abc import Generator, Iterable
+from contextlib import ExitStack, contextmanager
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import cast
+from uuid import UUID
+
+from nanobot.installation_lock import FileLease, InstallationBusyError, file_access
+from nanobot.utils.atomic_file import atomic_write_lines, read_atomic_bytes
+
+_DATA_STORES = (
+ "sessions", "webui", "media", "auth", "pairing.json", "cron", "delivery",
+ "llm_usage.sqlite3", "llm_usage.sqlite3-wal", "llm_usage.sqlite3-shm",
+ "whatsapp-auth", "weixin", "matrix-store", "linear", "mochat", "cli-apps/installed.json",
+)
+_WORKSPACE_STORES = (
+ ".nanobot", "memory", "skills", "sessions", "cron", "triggers",
+ "AGENTS.md", "TOOLS.md", "SOUL.md", "USER.md", "HEARTBEAT.md",
+)
+_MAX_RESERVATION_BYTES = 16 * 1024 * 1024
+
+
+def _stored_roots(raw: object) -> tuple[str, ...]:
+ if not isinstance(raw, list):
+ raise ValueError("Invalid data maintenance scope")
+ values = cast(list[object], raw)
+ if not 1 <= len(values) <= 40_000 or any(
+ not isinstance(root, str) or len(root) > 4096 or "\0" in root or not Path(root).is_absolute()
+ for root in values
+ ):
+ raise ValueError("Invalid data maintenance scope")
+ return tuple(cast(list[str], values))
+
+
+def _covered(requested: tuple[str, ...], reserved: tuple[str, ...]) -> bool:
+ allowed = set(map(Path, reserved))
+ return all(any(parent in allowed for parent in (path, *path.parents)) for path in map(Path, requested))
+
+
+@dataclass(frozen=True)
+class _Reservation:
+ job_id: str
+ roots: tuple[str, ...]
+ grants: dict[str, tuple[str, tuple[str, ...]]] = field(default_factory=dict)
+
+ def save(self, path: Path) -> None:
+ encoded = json.dumps({
+ "schema_version": 1, "job_id": self.job_id, "roots": self.roots,
+ "grants": {participant: {"token_sha256": digest, "roots": scope}
+ for participant, (digest, scope) in self.grants.items()},
+ })
+ if len(encoded.encode("utf-8")) + 1 > _MAX_RESERVATION_BYTES:
+ raise ValueError("Data maintenance reservation is too large")
+ atomic_write_lines(path, [encoded])
+ path.chmod(0o600)
+
+
+def _reservation(path: Path) -> _Reservation | None:
+ """Read a bounded, atomically replaced reservation; corruption never means idle."""
+ if path.is_symlink():
+ raise ValueError("Invalid data maintenance reservation")
+ try:
+ encoded = read_atomic_bytes(path, max_bytes=_MAX_RESERVATION_BYTES + 1)
+ except FileNotFoundError:
+ return None
+ if len(encoded) > _MAX_RESERVATION_BYTES:
+ raise ValueError("Data maintenance reservation is too large")
+ raw: object = json.loads(encoded)
+ if raw is None:
+ return None
+ if not isinstance(raw, dict):
+ raise ValueError("Invalid data maintenance reservation")
+ record = cast(dict[str, object], raw)
+ owner, roots = record.get("job_id"), record.get("roots")
+ if (record.get("schema_version") != 1 or not isinstance(owner, str)
+ or str(UUID(owner)) != owner):
+ raise ValueError("Invalid data maintenance reservation")
+ scope = _stored_roots(roots)
+ raw_grants = record.get("grants", {})
+ if not isinstance(raw_grants, dict):
+ raise ValueError("Invalid maintenance startup grants")
+ grant_values = cast(dict[object, object], raw_grants)
+ if len(grant_values) > 1024:
+ raise ValueError("Invalid maintenance startup grants")
+ grants: dict[str, tuple[str, tuple[str, ...]]] = {}
+ for participant, raw_grant in grant_values.items():
+ if not isinstance(participant, str) or not re.fullmatch(r"[0-9a-f]{64}", participant) or not isinstance(raw_grant, dict):
+ raise ValueError("Invalid maintenance startup participant")
+ grant = cast(dict[str, object], raw_grant)
+ digest = grant.get("token_sha256")
+ if not isinstance(digest, str) or not re.fullmatch(r"[0-9a-f]{64}", digest):
+ raise ValueError("Invalid maintenance startup grant")
+ granted_scope = _stored_roots(grant.get("roots"))
+ if not _covered(granted_scope, scope):
+ raise ValueError("Maintenance startup scope exceeds the reserved data")
+ grants[participant] = digest, granted_scope
+ return _Reservation(owner, scope, grants)
+
+
+@dataclass(frozen=True)
+class DataStartupGrant:
+ """Process-local bearer for one reviewed participant, not task admission.
+
+ The lifecycle owner must pass it only to the intended verified startup and
+ keep agent/tool/scheduler admission closed. This coordinates cooperating
+ runtimes; it is not an OS security boundary against the same account.
+ """
+
+ job_id: str
+ participant: str
+ token: str = field(repr=False)
+
+ def __post_init__(self) -> None:
+ if (str(UUID(self.job_id)) != self.job_id or not re.fullmatch(r"[0-9a-f]{64}", self.participant)
+ or not re.fullmatch(r"[0-9a-f]{64}", self.token)):
+ raise ValueError("Invalid maintenance startup grant")
+
+ @property
+ def digest(self) -> str:
+ return hashlib.sha256(self.token.encode()).hexdigest()
+
+
+@dataclass(frozen=True)
+class DataLease:
+ """Reservation operations are valid only inside the owning data_access context."""
+
+ roots: tuple[str, ...]
+ reservation_path: Path
+ job_id: str | None
+ exclusive: bool
+ _files: tuple[FileLease, ...] = field(default=(), repr=False, compare=False)
+
+ @contextmanager
+ def inherit_for_exec(self) -> Generator[None]:
+ """Retain all store leases in a dedicated POSIX installer's exec handoff."""
+ with ExitStack() as stack:
+ for lease in self._files:
+ stack.enter_context(lease.inherit_for_exec())
+ yield
+
+ def reserve(self) -> None:
+ """Keep participating writers out through handoff, crash and repair."""
+ if self.job_id is None or not self.exclusive:
+ raise ValueError("Only an update job may reserve data maintenance")
+ # Starting another package mutation revokes every old startup grant.
+ _Reservation(self.job_id, self.roots).save(self.reservation_path)
+
+ def grant_startup(self, participant: str, paths: Iterable[str | Path]) -> DataStartupGrant:
+ """Authorize one runtime during a shared, job-owned post-install handoff.
+
+ Must be called inside data_access(paths, job_id=...) after installation
+ verification. No exclusive data locks are held while the child starts.
+ A live participant retains its own OS lease and cannot be reauthorized.
+ """
+ if self.job_id is None or self.exclusive:
+ raise ValueError("Startup grants require a shared maintenance handoff")
+ grant = DataStartupGrant(self.job_id, participant, os.urandom(32).hex())
+ scope = _canonical_roots(paths)
+ if not scope or not _covered(scope, self.roots):
+ raise ValueError("Startup grant exceeds the reviewed data scope")
+ current = _reservation(self.reservation_path)
+ if current is None or (current.job_id, current.roots) != (self.job_id, self.roots):
+ raise ValueError("Data maintenance belongs to a different job or scope")
+ if participant not in current.grants and len(current.grants) >= 1024:
+ raise ValueError("Too many maintenance startup participants")
+ try:
+ with file_access(self.reservation_path.parent / f"startup-{participant}.lock", exclusive=True):
+ current.grants[participant] = grant.digest, scope
+ current.save(self.reservation_path)
+ except BlockingIOError as exc:
+ raise InstallationBusyError("This maintenance startup participant is still running") from exc
+ return grant
+
+ def release_reservation(self) -> None:
+ """Clear only this job's reservation after verification or safe cancellation."""
+ if self.job_id is None:
+ raise ValueError("Only an update job may release data maintenance")
+ current = _reservation(self.reservation_path)
+ if current is None:
+ return
+ if (current.job_id, current.roots) != (self.job_id, self.roots):
+ raise ValueError("Data maintenance belongs to a different job or scope")
+ # Atomic replacement also flushes the directory; a crash cannot lose an
+ # unsynced unlink and resurrect an apparently cleared reservation.
+ atomic_write_lines(self.reservation_path, ["null"])
+
+ def grant_profile_startup(self, participant: str, *, home: Path, data_dir: Path,
+ config: Path, workspace: Path) -> DataStartupGrant:
+ """Honor a protocol-1 handoff without granting its new lazy store early."""
+ paths = profile_data_paths(home=home, data_dir=data_dir, config=config, workspace=workspace)
+ delivery = (data_dir / "delivery").absolute()
+ if not _covered(_canonical_roots((delivery,)), self.roots):
+ paths = tuple(path for path in paths if path != delivery)
+ # Every other store must still be covered by the immutable reservation.
+ # profile_data_access holds the deferred store's ordinary lease, and the
+ # runtime admission gate keeps its lazy owner inactive until activation.
+ return self.grant_startup(participant, paths)
+
+
+def _canonical_roots(paths: Iterable[str | Path]) -> tuple[str, ...]:
+ roots: set[str] = set()
+ for raw in paths:
+ path = Path(raw)
+ if not path.is_absolute():
+ raise ValueError("Data stores must use absolute paths")
+ roots.add(str(path.resolve()).casefold())
+ return tuple(sorted(roots))
+
+
+def profile_data_paths(*, home: Path, data_dir: Path, config: Path, workspace: Path) -> tuple[Path, ...]:
+ """One store inventory for runtime leases and scoped update backups.
+
+ Keep store symlinks visible here: backup must reject them, not silently expand
+ its read scope. Lease identity alone resolves aliases so runtimes cannot race.
+ CLI/config workspace paths may be relative; bind them to this runtime's cwd
+ without following symlinks before passing the inventory to strict leases.
+ """
+ return tuple(path.absolute() for path in (
+ config, home / "history" / "cli_history", home / "sessions",
+ *(data_dir / name for name in _DATA_STORES),
+ *(workspace / name for name in _WORKSPACE_STORES),
+ ))
+
+
+@contextmanager
+def profile_data_access(*, home: Path, data_dir: Path, config: Path, workspace: Path,
+ grant: DataStartupGrant | None = None) -> Generator[None]:
+ """Lease current stores without expanding an older updater's startup grant.
+
+ Protocol 1 predates the delivery store. That owner is lazy and cannot open
+ its database until runtime admission opens. Under an exact legacy grant,
+ lease delivery normally, separately from protected initialization. No data
+ migration or delivery write is permitted before activation. New updaters
+ include it in the ordinary full backup/reservation scope.
+ """
+ paths = profile_data_paths(home=home, data_dir=data_dir, config=config, workspace=workspace)
+ delivery = (data_dir / "delivery").absolute()
+ legacy = tuple(path for path in paths if path != delivery)
+ if grant is not None:
+ pending = _reservation(Path.home() / ".nanobot/updates/data-locks/maintenance.json")
+ if (pending is not None and pending.job_id == grant.job_id
+ and pending.grants.get(grant.participant) == (grant.digest, _canonical_roots(legacy))):
+ with data_access(legacy, grant=grant), data_access((delivery,)):
+ yield
+ return
+ with data_access(paths, grant=grant):
+ yield
+
+
+def finish_data_handoff(paths: Iterable[str | Path], *, job_id: str) -> None:
+ """Finish cleanup of a durably verified handoff, including after a crash.
+
+ Unlike starting a handoff this can find its reservation already cleared.
+ Caller must have persisted verified runtime success. The owner lock and
+ exact job/scope check prevent clearing another maintenance reservation;
+ running children keep their own data leases throughout this cleanup.
+ """
+ roots = _canonical_roots(paths)
+ if not roots or str(UUID(job_id)) != job_id:
+ raise ValueError("Data handoff completion requires its original identity and scope")
+ directory = Path.home() / ".nanobot" / "updates" / "data-locks"
+ with file_access(directory / "maintenance.lock", exclusive=True):
+ DataLease(roots, directory / "maintenance.json", job_id, False).release_reservation()
+
+
+def require_no_pending_data_update() -> None:
+ """Reject a known unfinished transaction before stopping another gateway.
+
+ This is an early check, not a maintenance grant. The worker must still obtain
+ exclusive installation/data leases and validate the reservation after shutdown.
+ """
+ directory = Path.home() / ".nanobot" / "updates" / "data-locks"
+ try:
+ with file_access(directory / "maintenance.lock", exclusive=True):
+ if _reservation(directory / "maintenance.json") is not None:
+ raise InstallationBusyError("Another data update is unfinished; recover it before stopping this gateway")
+ except BlockingIOError as exc:
+ raise InstallationBusyError("Another data update is active; this gateway was not stopped") from exc
+
+
+@contextmanager
+def data_access(paths: Iterable[str | Path], *, updating: bool = False,
+ job_id: str | None = None, grant: DataStartupGrant | None = None) -> Generator[DataLease]:
+ """Refuse overlapping live writers/maintenance without waiting or killing them.
+
+ Writers claim roots in one namespace and ancestors in the other; maintenance
+ does the reverse, exclusively. Neither a parent nor a child store can bypass
+ the other's lease. Disjoint runtime data stays available; maintenance jobs in
+ this account serialize deliberately rather than require a live lock registry.
+ Leases are nonblocking, ordered and released together after partial failure.
+ An exclusive job may reserve its roots across process handoff. Only that same
+ job and exact scope can resume maintenance; a crash does not lift the fence.
+
+ After verifying package files, the owner may use shared access with job_id to
+ grant restricted child startup. The owner retains the maintenance lock, while
+ each granted child holds its own shared data and exclusive participant leases.
+ Only the owner releases the reservation after runtime verification; context
+ exit never clears it. A grant permits data initialization, not normal work.
+ """
+ canonical = _canonical_roots(paths)
+ roots = set(map(Path, canonical))
+ if job_id is not None and (not roots or str(UUID(job_id)) != job_id):
+ raise ValueError("Data maintenance requires a canonical job identity")
+ if grant is not None and (updating or job_id is not None):
+ raise ValueError("A startup participant cannot act as the maintenance owner")
+ leases: set[tuple[str, str]] = set()
+ for path in roots:
+ requested, ancestors = (path,), (path, *path.parents)
+ for namespace, items in (
+ ("writers", requested if updating else ancestors),
+ ("maintenance", ancestors if updating else requested),
+ ):
+ for item in items:
+ # Conservatively merge case aliases, including on macOS volumes
+ # where normcase alone does not normalize path identity.
+ leases.add((namespace, str(item).casefold()))
+ directory = Path.home() / ".nanobot" / "updates" / "data-locks"
+ with ExitStack() as stack:
+ held: list[FileLease] = []
+ try:
+ if updating or job_id is not None:
+ # One reservation per account, including Windows stores on
+ # different drives that have no shared filesystem ancestor.
+ held.append(stack.enter_context(file_access(directory / "maintenance.lock", exclusive=True)))
+ if grant is not None:
+ held.append(stack.enter_context(file_access(directory / f"startup-{grant.participant}.lock", exclusive=True)))
+ for namespace, key in sorted(leases):
+ name = hashlib.sha256(os.fsencode(key)).hexdigest()
+ held.append(stack.enter_context(file_access(directory / f"{namespace}-{name}.lock", exclusive=updating)))
+ except BlockingIOError as exc:
+ raise InstallationBusyError(
+ "Nanobot data is in use by another runtime or update. Stop its writers "
+ "before retrying; no data lease was granted."
+ ) from exc
+ path = directory / "maintenance.json"
+ pending = _reservation(path)
+ if pending is None and (grant is not None or (job_id is not None and not updating)):
+ raise InstallationBusyError("Data maintenance handoff is no longer reserved")
+ if pending is not None:
+ owner, reserved = pending.job_id, pending.roots
+ if updating or job_id is not None:
+ if (job_id, canonical) != (owner, reserved):
+ raise InstallationBusyError("Data maintenance belongs to an unfinished update; resume that job first")
+ elif grant is not None:
+ if grant.job_id != owner or pending.grants.get(grant.participant) != (grant.digest, canonical):
+ raise InstallationBusyError("Startup grant does not match this participant's reserved data scope")
+ else:
+ requested = set(map(Path, canonical))
+ ancestors = {parent for root in requested for parent in (root, *root.parents)}
+ if any(root in ancestors or any(parent in requested for parent in root.parents)
+ for root in map(Path, reserved)):
+ raise InstallationBusyError("Nanobot data is reserved by an unfinished update; check its saved job before restarting")
+ yield DataLease(canonical, path, job_id, updating, tuple(held))
diff --git a/nanobot/gateway/runtime.py b/nanobot/gateway/runtime.py
index 72a8fdaa6..e8abd0eb0 100644
--- a/nanobot/gateway/runtime.py
+++ b/nanobot/gateway/runtime.py
@@ -15,7 +15,7 @@ import time
import uuid
from collections.abc import Callable
from contextlib import contextmanager
-from dataclasses import dataclass
+from dataclasses import asdict, dataclass
from datetime import UTC, datetime
from pathlib import Path
from typing import Any, Generator, Literal, cast
@@ -47,19 +47,30 @@ GatewayLaunchMode = Literal["foreground", "background", "unknown"]
GatewayLifetime = Literal["explicit", "on_demand"]
-def _gateway_health_ready(host: str, port: int, *, timeout_s: float = 0.4) -> bool:
+@dataclass(frozen=True)
+class GatewayHealthIdentity:
+ """Opaque local instance/run identity; never configuration paths or credentials."""
+
+ instance_id: str
+ run_id: str
+ version: str
+
+
+def _gateway_health_ready(host: str, port: int, *, timeout_s: float = 0.4,
+ expected: GatewayHealthIdentity | None = None,
+ maintenance: bool | None = None) -> bool:
"""Read readiness from the management listener without using proxy settings."""
connect_host = "127.0.0.1" if host in {"", "0.0.0.0"} else "::1" if host == "::" else host
connection = http.client.HTTPConnection(connect_host, port, timeout=timeout_s)
try:
connection.request("GET", "/health")
response = connection.getresponse()
- body = response.read(1024)
+ body = response.read(4097)
except (OSError, http.client.HTTPException, TimeoutError):
return False
finally:
connection.close()
- if response.status != 200:
+ if response.status != 200 or len(body) > 4096:
return False
try:
raw_payload = cast(object, json.loads(body.decode("utf-8")))
@@ -68,6 +79,15 @@ def _gateway_health_ready(host: str, port: int, *, timeout_s: float = 0.4) -> bo
if not isinstance(raw_payload, dict):
return False
payload = cast(dict[str, object], raw_payload)
+ if maintenance is not None and payload.get("maintenance") is not maintenance:
+ return False
+ if expected is not None:
+ raw_identity = payload.get("runtime")
+ if payload.get("ready") is not True or not isinstance(raw_identity, dict):
+ return False
+ identity = cast(dict[str, object], raw_identity)
+ if any(identity.get(key) != value for key, value in asdict(expected).items()):
+ return False
return (
payload.get("status") == "ok"
and payload.get("ready") is not False
@@ -340,6 +360,26 @@ class GatewayRuntime(ManagedProcessRuntime[GatewayStartOptions]):
state["health_host"] = host
self._write_state(state)
+ def verify_ready(self, expected: GatewayHealthIdentity, *, maintenance: bool | None = None) -> bool:
+ """Bind health to one live local process, not merely a responding port.
+
+ This is local lifecycle evidence, not remote authentication. Missing
+ identity metadata on an older host cannot confirm an update restart.
+ """
+ state = self._read_state()
+ if not state:
+ return False
+ pid, host, port = state.get("pid"), state.get("health_host"), state.get("port")
+ if (type(pid) is not int or type(port) is not int or not 0 < port < 65536
+ or not isinstance(host, str) or not self._is_pid_running(pid)
+ or not self._record_matches_process(state, pid)):
+ return False
+ if not _gateway_health_ready(host, port, expected=expected, maintenance=maintenance):
+ return False
+ # The process may have exited or been replaced while the HTTP probe ran.
+ return (self._read_state() == state and self._is_pid_running(pid)
+ and self._record_matches_process(state, pid))
+
@contextmanager
def foreground_instance(self, options: GatewayStartOptions) -> Generator[None]:
"""Publish this process and own its stop signal across asyncio.run()."""
diff --git a/nanobot/installation_lock.py b/nanobot/installation_lock.py
new file mode 100644
index 000000000..3e05801b6
--- /dev/null
+++ b/nanobot/installation_lock.py
@@ -0,0 +1,146 @@
+"""Coordinate nanobot entrypoints with updates of their shared Python installation.
+
+This module uses only the standard library so startup and a detached update worker
+can use the same lock without importing dependencies they are about to replace.
+The OS releases leases on process exit, including a crash. Never unlink the lock
+file: replacing its inode would let two processes acquire different locks.
+"""
+
+from __future__ import annotations
+
+import errno
+import hashlib
+import os
+import sys
+from collections.abc import Generator
+from contextlib import contextmanager
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import BinaryIO
+
+from nanobot.utils.atomic_file import io_path
+
+
+class InstallationBusyError(RuntimeError):
+ """Another runtime or updater holds an incompatible installation lease."""
+
+
+@dataclass(frozen=True)
+class FileLease:
+ """An OS lease owned by the enclosing file_access context."""
+
+ _handle: BinaryIO = field(repr=False)
+
+ @contextmanager
+ def inherit_for_exec(self) -> Generator[None]:
+ """Keep a dedicated POSIX worker's lease when exec replaces its program.
+
+ Enter only immediately around exec, not a spawned child or normal runtime
+ work. The new program must retain the descriptors and must not delegate
+ mutation to unprotected children. Windows byte-range locks do not provide
+ this ownership transfer. A failed exec restores the original FD flags.
+ """
+ if os.name != "posix":
+ raise OSError("Lease inheritance requires a POSIX exec handoff")
+ descriptor = self._handle.fileno()
+ original = os.get_inheritable(descriptor)
+ os.set_inheritable(descriptor, True)
+ try:
+ yield
+ finally:
+ os.set_inheritable(descriptor, original)
+
+
+def installation_id(environment: str | Path | None = None) -> str:
+ return hashlib.sha256(os.fsencode(Path(environment or sys.prefix).resolve())).hexdigest()[:32]
+
+
+def installation_state_dir(environment: str | Path | None = None) -> Path:
+ # Deliberately independent of --home/config/workspace: profiles sharing this
+ # interpreter must not get independent update locks.
+ return Path.home() / ".nanobot" / "updates" / installation_id(environment)
+
+
+def pending_update_path(environment: str | Path | None = None) -> Path:
+ return Path.home() / ".nanobot" / "run" / f"update-{installation_id(environment)[:16]}.pending"
+
+
+def _lock_windows(handle: BinaryIO, *, exclusive: bool) -> None:
+ import ctypes
+ import msvcrt
+ from ctypes import wintypes
+
+ class Overlapped(ctypes.Structure):
+ _fields_ = [
+ ("Internal", ctypes.c_size_t), ("InternalHigh", ctypes.c_size_t),
+ ("Offset", wintypes.DWORD), ("OffsetHigh", wintypes.DWORD),
+ ("hEvent", wintypes.HANDLE),
+ ]
+
+ kernel = ctypes.WinDLL("kernel32", use_last_error=True)
+ lock = kernel.LockFileEx
+ lock.argtypes = [wintypes.HANDLE, wintypes.DWORD, wintypes.DWORD,
+ wintypes.DWORD, wintypes.DWORD, ctypes.POINTER(Overlapped)]
+ lock.restype = wintypes.BOOL
+ overlap = Overlapped()
+ # LOCKFILE_FAIL_IMMEDIATELY, plus LOCKFILE_EXCLUSIVE_LOCK for an updater.
+ if not lock(msvcrt.get_osfhandle(handle.fileno()), 1 | (2 if exclusive else 0),
+ 0, 1, 0, ctypes.byref(overlap)):
+ code = ctypes.get_last_error()
+ if code in {32, 33}: # sharing/lock violation
+ raise BlockingIOError(errno.EAGAIN, "Installation is in use")
+ raise ctypes.WinError(code)
+
+
+@contextmanager
+def file_access(path: Path, *, exclusive: bool) -> Generator[FileLease]:
+ """Hold a nonblocking OS lease; never replace or delete its file."""
+ path = io_path(path)
+ path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
+ descriptor = os.open(path, os.O_RDWR | os.O_CREAT | getattr(os, "O_NOFOLLOW", 0), 0o600)
+ with os.fdopen(descriptor, "a+b") as handle:
+ try:
+ if sys.platform == "win32":
+ _lock_windows(handle, exclusive=exclusive)
+ else:
+ import fcntl
+
+ fcntl.flock(handle, (fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH) | fcntl.LOCK_NB)
+ except OSError as exc:
+ if exc.errno in {errno.EAGAIN, errno.EACCES}:
+ raise BlockingIOError(errno.EAGAIN, "The file lease is held") from exc
+ raise
+ yield FileLease(handle)
+
+
+@contextmanager
+def installation_access(*, updating: bool = False, allow_incomplete: bool = False,
+ environment: str | Path | None = None) -> Generator[FileLease]:
+ """Hold a shared runtime lease, or refuse an update until all runtimes exit.
+
+ This protects cooperating entrypoints in this account, not arbitrary Python
+ imports or externally managed deployments. Process-owner shutdown/restart is
+ still required before enabling an in-app installation handoff. Diagnostics and
+ stop commands may allow an incomplete install; they still cannot race a writer.
+ """
+ acquired = False
+ try:
+ with file_access(installation_state_dir(environment) / "runtime.lock", exclusive=updating) as lease:
+ acquired = True
+ if not updating and not allow_incomplete and io_path(pending_update_path(environment)).exists():
+ raise InstallationBusyError(
+ "A previous update did not finish. Check its saved update state at "
+ f"{installation_state_dir(environment)} before repairing this installation. "
+ "Do not start a different update. No automatic rollback was performed."
+ )
+ yield lease
+ except BlockingIOError as exc:
+ if not acquired:
+ message = (
+ "This installation is in use. Stop its nanobot gateways and clients before updating; "
+ "no processes were stopped and no package files were changed."
+ if updating else
+ "This installation is being updated. Wait for the update to finish before starting nanobot."
+ )
+ raise InstallationBusyError(message) from exc
+ raise
diff --git a/nanobot/installation_receipt.py b/nanobot/installation_receipt.py
new file mode 100644
index 000000000..2cb6fdc28
--- /dev/null
+++ b/nanobot/installation_receipt.py
@@ -0,0 +1,28 @@
+"""The official installer's explicit package selection, not inferred dependencies.
+
+The installer records selection before creating a dedicated environment, so retry
+survives first-install failure. The receipt alone does not prove installation or
+readiness. Existing uv, pipx, source and unrecorded venvs are never adopted implicitly.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+from pathlib import Path
+
+RECEIPT_NAME = "nanobot-install.json"
+
+
+def managed_extras(environment: str, expected_sha256: str) -> list[str]:
+ path = Path(environment) / RECEIPT_NAME
+ if path.is_symlink() or path.stat().st_size > 4096:
+ raise ValueError("Invalid installer receipt")
+ payload = path.read_bytes()
+ if hashlib.sha256(payload).hexdigest() != expected_sha256:
+ raise ValueError("Installer receipt changed")
+ record = json.loads(payload)
+ if record != {"schema_version": 1, "owner": "nanobot-installer",
+ "environment": str(Path(environment).resolve()), "extras": []}:
+ raise ValueError("This installation selection needs its owner's update workflow")
+ return []
diff --git a/nanobot/optional_features.py b/nanobot/optional_features.py
index 0724763c2..ab7debfbe 100644
--- a/nanobot/optional_features.py
+++ b/nanobot/optional_features.py
@@ -6,6 +6,7 @@ import os
import shutil
import subprocess
import sys
+from collections.abc import Callable
from dataclasses import dataclass
from importlib.metadata import PackageNotFoundError, distribution
from pathlib import Path
@@ -223,10 +224,24 @@ def install_extra(
*,
runner: Any = run_install_command,
) -> InstallResult:
+ install_args, label = install_args_for_extra(extra, deps)
+ return install_packages(install_args, label, runner=runner, log_name=extra)
+
+
+def install_packages(
+ install_args: list[str],
+ label: str,
+ *,
+ upgrade: bool = False,
+ runner: Callable[..., subprocess.CompletedProcess[str]] = run_install_command,
+ log_name: str | None = None,
+) -> InstallResult:
+ """Install into the running interpreter, bootstrapping pip only when needed."""
import importlib
- install_args, label = install_args_for_extra(extra, deps)
- pip_cmd = [sys.executable, "-m", "pip", "install", *install_args]
+ pip_options = ["--upgrade", "--upgrade-strategy", "only-if-needed"] if upgrade else []
+ extra = log_name or label
+ pip_cmd = [sys.executable, "-m", "pip", "install", *pip_options, *install_args]
if not install_args:
logger.info("Optional feature '{}' has no installable dependencies for this platform", extra)
return InstallResult(True, label, pip_cmd)
@@ -242,7 +257,9 @@ def install_extra(
failed_proc = proc
if missing_pip(proc):
if shutil.which("uv"):
- uv_cmd = ["uv", "pip", "install", "--python", sys.executable, *install_args]
+ uv_options = ["--upgrade-package", "nanobot-ai"] if upgrade else []
+ uv_args = ["--reinstall" if arg == "--force-reinstall" else arg for arg in install_args]
+ uv_cmd = ["uv", "pip", "install", "--python", sys.executable, *uv_options, *uv_args]
uv_env = os.environ.copy()
if index_url := os.environ.get("PIP_INDEX_URL", "").strip():
uv_env["UV_INDEX_URL"] = index_url
diff --git a/nanobot/process_runtime.py b/nanobot/process_runtime.py
index 8ef4351d9..e94f96205 100644
--- a/nanobot/process_runtime.py
+++ b/nanobot/process_runtime.py
@@ -23,6 +23,7 @@ from typing import Any, Generic, Literal, TypeVar, cast
from filelock import FileLock
+from nanobot.utils.atomic_file import read_atomic_bytes, replace_atomic
from nanobot.utils.rotating_output import (
BACKGROUND_LOG_BACKUP_COUNT_ENV,
BACKGROUND_LOG_MAX_BYTES_ENV,
@@ -477,8 +478,7 @@ class ManagedProcessRuntime(Generic[_StartOptionsT]):
def _read_state(self) -> dict[str, Any] | None:
try:
- with self.paths.state_path.open(encoding="utf-8") as handle:
- payload = json.load(handle)
+ payload = json.loads(read_atomic_bytes(self.paths.state_path).decode("utf-8"))
except (OSError, json.JSONDecodeError, ValueError):
return None
return cast(dict[str, Any], payload) if isinstance(payload, dict) else None
@@ -497,7 +497,7 @@ class ManagedProcessRuntime(Generic[_StartOptionsT]):
handle.write("\n")
handle.flush()
os.fsync(handle.fileno())
- tmp_path.replace(self.paths.state_path)
+ replace_atomic(tmp_path, self.paths.state_path)
finally:
tmp_path.unlink(missing_ok=True)
diff --git a/nanobot/providers/github_copilot_oauth.py b/nanobot/providers/github_copilot_oauth.py
index c233a30d3..cfccf0c1e 100644
--- a/nanobot/providers/github_copilot_oauth.py
+++ b/nanobot/providers/github_copilot_oauth.py
@@ -27,6 +27,7 @@ class GitHubCopilotOAuthFlow:
self._error: Exception | None = None
self._commit_lock = threading.Lock()
self._saved = False
+ self._thread = threading.Thread(target=self._run, daemon=True, name="github-device-login")
@property
def remaining_seconds(self) -> int:
@@ -36,6 +37,14 @@ class GitHubCopilotOAuthFlow:
def expired(self) -> bool:
return self._cancelled.is_set() or self.remaining_seconds <= 0
+ @property
+ def has_pending_work(self) -> bool:
+ return self._thread.is_alive()
+
+ def wait_closed(self) -> None:
+ if self._thread.ident is not None:
+ self._thread.join()
+
def cancel(self) -> None:
with self._commit_lock:
self._cancelled.set()
@@ -63,7 +72,10 @@ class GitHubCopilotOAuthFlow:
self._ready.set()
def start(self) -> None:
- threading.Thread(target=self._run, daemon=True, name="github-device-login").start()
+ with self._commit_lock:
+ if self.expired:
+ raise RuntimeError("GitHub sign-in expired or cancelled. Start again.")
+ self._thread.start()
if not self._ready.wait(timeout=15):
self.cancel()
raise RuntimeError("GitHub sign-in timed out. Start again.")
@@ -72,7 +84,7 @@ class GitHubCopilotOAuthFlow:
if self._error is not None:
raise RuntimeError("GitHub sign-in failed. Start again.") from None
- def complete(self) -> OAuthToken | None:
+ def complete(self, _authorization_response: str | None = None) -> OAuthToken | None:
# Approval alone must not change credentials after the UI was closed.
# Commit only through the live flow's completion endpoint, serialized
# with cancellation (including sign-out).
diff --git a/nanobot/providers/openai_codex_oauth.py b/nanobot/providers/openai_codex_oauth.py
index ffc20cefa..291fb315e 100644
--- a/nanobot/providers/openai_codex_oauth.py
+++ b/nanobot/providers/openai_codex_oauth.py
@@ -17,6 +17,7 @@ from urllib.parse import parse_qs, urlsplit
from oauth_cli_kit import login_oauth_interactive
from oauth_cli_kit.models import OAuthToken
from oauth_cli_kit.providers import OPENAI_CODEX_PROVIDER
+from oauth_cli_kit.storage import FileTokenStorage
_AUTHORIZATION_URL_TIMEOUT_S = 5.0
_CALLBACK = urlsplit(OPENAI_CODEX_PROVIDER.redirect_uri)
@@ -32,6 +33,22 @@ class OpenAICodexOAuthInputError(OpenAICodexOAuthError):
"""A recoverable error in a callback URL pasted by the user."""
+class _LoginTokenStorage(FileTokenStorage):
+ """Use the SDK's public storage seam to exclude cancelled/expired writes."""
+
+ def __init__(self, cancelled: threading.Event, lock: threading.Lock, deadline: float) -> None:
+ super().__init__(token_filename=OPENAI_CODEX_PROVIDER.token_filename)
+ self._cancelled = cancelled
+ self._commit_lock = lock
+ self._deadline = deadline
+
+ def save(self, token: OAuthToken) -> None:
+ with self._commit_lock:
+ if self._cancelled.is_set() or time.monotonic() >= self._deadline:
+ raise OpenAICodexOAuthError("OpenAI Codex sign-in expired or was cancelled.")
+ super().save(token)
+
+
class OpenAICodexOAuthLoginFlow:
"""Expose oauth-cli-kit's blocking prompt as a two-stage WebUI flow."""
@@ -51,6 +68,8 @@ class OpenAICodexOAuthLoginFlow:
self._result: Future[OAuthToken] = Future()
self._ready = threading.Event()
self._submission_lock = threading.Lock()
+ self._commit_lock = threading.Lock()
+ self._cancelled = threading.Event()
self._submitted = False
self._thread = threading.Thread(
target=self._run,
@@ -66,8 +85,20 @@ class OpenAICodexOAuthLoginFlow:
def remaining_seconds(self) -> int:
return max(0, int(self._expires_at - time.monotonic()))
+ @property
+ def has_pending_work(self) -> bool:
+ return self._thread.is_alive()
+
+ def wait_closed(self) -> None:
+ """Join the worker, including the SDK's token exchange and cleanup."""
+ if self._thread.ident is not None:
+ self._thread.join()
+
def start(self) -> OpenAICodexOAuthLoginFlow:
- self._thread.start()
+ with self._commit_lock:
+ if self._cancelled.is_set():
+ raise OpenAICodexOAuthError("OpenAI Codex sign-in was cancelled.")
+ self._thread.start()
wait_s = min(
_AUTHORIZATION_URL_TIMEOUT_S,
max(0.0, self._expires_at - time.monotonic()),
@@ -126,8 +157,6 @@ class OpenAICodexOAuthLoginFlow:
def cancel(self) -> None:
"""Unblock an abandoned interactive login."""
self._fail(OpenAICodexOAuthError("OpenAI Codex sign-in was cancelled."))
- if threading.current_thread() is not self._thread:
- self._thread.join(timeout=0.5)
def _run(self) -> None:
try:
@@ -135,6 +164,7 @@ class OpenAICodexOAuthLoginFlow:
print_fn=self._capture_output,
prompt_fn=self._prompt_for_callback,
provider=OPENAI_CODEX_PROVIDER,
+ storage=_LoginTokenStorage(self._cancelled, self._commit_lock, self._expires_at),
proxy=self._proxy,
open_browser=self._open_browser,
)
@@ -176,6 +206,8 @@ class OpenAICodexOAuthLoginFlow:
return value
def _fail(self, error: OpenAICodexOAuthError) -> None:
+ with self._commit_lock:
+ self._cancelled.set()
try:
self._result.set_exception(error)
except Exception:
@@ -193,11 +225,17 @@ def start_openai_codex_oauth_login(
open_browser: bool = True,
) -> OpenAICodexOAuthLoginFlow:
"""Start a non-blocking wrapper around oauth-cli-kit's Codex login."""
- return OpenAICodexOAuthLoginFlow(
+ flow = OpenAICodexOAuthLoginFlow(
proxy=proxy,
timeout_s=timeout_s,
open_browser=open_browser,
- ).start()
+ )
+ try:
+ return flow.start()
+ except BaseException:
+ flow.cancel()
+ flow.wait_closed()
+ raise
def complete_openai_codex_oauth_login(
diff --git a/nanobot/providers/xai_oauth.py b/nanobot/providers/xai_oauth.py
index 9012300ef..c4853b1bc 100644
--- a/nanobot/providers/xai_oauth.py
+++ b/nanobot/providers/xai_oauth.py
@@ -144,10 +144,26 @@ class XAIOAuthLoginFlow:
name="nanobot-xai-grok-oauth-callback",
daemon=True,
)
- self._server_thread.start()
self._timeout_timer = threading.Timer(timeout_s, self._expire)
self._timeout_timer.daemon = True
- self._timeout_timer.start()
+
+ def start(self) -> XAIOAuthLoginFlow:
+ with self._lock:
+ self._raise_if_finished()
+ self._server_thread.start()
+ self._timeout_timer.start()
+ return self
+
+ @property
+ def has_pending_work(self) -> bool:
+ return self._server_thread.is_alive() or self._timeout_timer.is_alive()
+
+ def wait_closed(self) -> None:
+ # Join outside _lock: the expiry timer can be waiting to acquire it.
+ if self._timeout_timer.ident is not None:
+ self._timeout_timer.join()
+ if self._server_thread.ident is not None:
+ self._server_thread.join()
@property
def expired(self) -> bool:
@@ -253,8 +269,8 @@ class XAIOAuthLoginFlow:
self._closed = True
self._timeout_timer.cancel()
self._stop_event.set()
- if threading.current_thread() is not self._server_thread:
- self._server_thread.join(timeout=2)
+ if self._server_thread.ident is None:
+ self._server.server_close()
def get_xai_oauth_storage_path() -> Path:
@@ -309,6 +325,7 @@ def login_xai_oauth(
return flow.wait(callback_timeout_s)
finally:
flow.cancel()
+ flow.wait_closed()
def start_xai_oauth_login(
@@ -317,6 +334,15 @@ def start_xai_oauth_login(
timeout_s: float = 600,
) -> XAIOAuthLoginFlow:
"""Create a non-blocking OAuth flow for browser or pasted-callback completion."""
+ return create_xai_oauth_login(proxy=proxy, timeout_s=timeout_s).start()
+
+
+def create_xai_oauth_login(
+ *,
+ proxy: str | None = None,
+ timeout_s: float = 600,
+) -> XAIOAuthLoginFlow:
+ """Prepare the flow so a gateway can own it before starting its threads."""
discovery = _discover(proxy)
verifier, challenge = _generate_pkce()
state = secrets.token_urlsafe(32)
@@ -475,6 +501,10 @@ def _make_callback_server(
result_queue: queue.Queue[_CallbackResult],
) -> ThreadingHTTPServer:
class CallbackHandler(BaseHTTPRequestHandler):
+ def setup(self) -> None:
+ super().setup()
+ self.connection.settimeout(5)
+
def do_OPTIONS(self) -> None: # noqa: N802
if self.path.split("?", 1)[0] != "/callback":
self.send_error(HTTPStatus.NOT_FOUND)
@@ -530,7 +560,11 @@ def _make_callback_server(
# Callback query strings contain an authorization code.
return
- return ThreadingHTTPServer(("127.0.0.1", 0), CallbackHandler)
+ server = ThreadingHTTPServer(("127.0.0.1", 0), CallbackHandler)
+ # The listener's server_close must join accepted requests too, not merely
+ # close the listening socket while handlers still run application code.
+ server.daemon_threads = False
+ return server
def _serve_callback_server(
diff --git a/nanobot/release_feed.py b/nanobot/release_feed.py
new file mode 100644
index 000000000..402f100ec
--- /dev/null
+++ b/nanobot/release_feed.py
@@ -0,0 +1,382 @@
+"""Resolve and revalidate exact release artifacts without installing anything.
+
+Stable releases are read from PyPI; previews use the project's protected catalogue.
+Neither source can provide commands, another repository, or arbitrary download hosts.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import hashlib
+import platform
+import re
+from collections.abc import AsyncGenerator
+from contextlib import asynccontextmanager
+from email.parser import BytesParser
+from pathlib import Path
+from typing import Literal, Self
+from urllib.parse import unquote, urljoin, urlsplit
+from uuid import uuid4
+from zipfile import ZipFile
+
+import httpx
+from filelock import FileLock
+from packaging.specifiers import SpecifierSet
+from packaging.tags import Tag, sys_tags
+from packaging.utils import canonicalize_name, parse_wheel_filename
+from packaging.version import Version
+from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
+
+from nanobot.release_trust import verify_release_approval
+from nanobot.releases import (
+ RELEASE_DOWNLOAD,
+ Channel,
+ ReleaseArtifact,
+ ReleaseCatalogue,
+ ReleaseManifest,
+ ReleasePointer,
+ ReleaseRecord,
+ release_filenames,
+ release_version,
+)
+from nanobot.security.network import PinnedDNSAsyncTransport
+from nanobot.utils.atomic_file import atomic_write_lines
+
+CATALOGUE_URL = "https://raw.githubusercontent.com/HKUDS/nanobot/release-index/catalogue.json"
+PYPI_URL = "https://pypi.org/pypi/nanobot-ai"
+_DOWNLOAD_HOSTS = {"github.com", "release-assets.githubusercontent.com", "objects.githubusercontent.com",
+ "files.pythonhosted.org"}
+_METADATA_HOSTS = {"pypi.org", "raw.githubusercontent.com", *_DOWNLOAD_HOSTS}
+
+
+class ReleaseFeedError(RuntimeError):
+ """No verified update can be offered or downloaded."""
+
+ def __init__(self, message: str, *, code: Literal["unavailable", "publishing", "unsupported", "withdrawn"] = "unavailable") -> None:
+ super().__init__(message)
+ self.code = code
+
+
+def _url(url: str, hosts: set[str]) -> str:
+ parsed = urlsplit(url)
+ if (parsed.scheme != "https" or parsed.hostname not in hosts
+ or parsed.username is not None or parsed.password is not None
+ or parsed.port not in (None, 443) or parsed.fragment):
+ raise ValueError("Release URL must use an approved HTTPS host")
+ return url
+
+
+class ReleaseTarget(ReleaseRecord):
+ version: str
+ artifact: ReleaseArtifact
+ url: str
+ source: Literal["pypi", "github"]
+ pointer: ReleasePointer | None = None
+ catalogue_generation: int = Field(default=0, ge=0)
+
+ _version = field_validator("version")(release_version)
+
+ @model_validator(mode="after")
+ def validate_identity(self) -> Self:
+ name, version, _, tags = parse_wheel_filename(self.artifact.filename)
+ if name != "nanobot-ai" or str(version) != self.version or any(t.platform == "any" for t in tags):
+ raise ValueError("Expected a matching native nanobot wheel")
+ _url(self.url, {"files.pythonhosted.org"} if self.source == "pypi" else {"github.com"})
+ if unquote(urlsplit(self.url).path.rsplit("/", 1)[-1]) != self.artifact.filename:
+ raise ValueError("Wheel URL and filename differ")
+ if self.source == "github":
+ expected = f"https://github.com/HKUDS/nanobot/releases/download/v{self.version}/{self.artifact.filename}"
+ if self.url != expected or not self.pointer or self.pointer.version != self.version or self.catalogue_generation < 1:
+ raise ValueError("GitHub target must identify the exact official candidate")
+ elif self.pointer is not None or self.catalogue_generation or Version(self.version).is_prerelease:
+ raise ValueError("PyPI discovery is for stable releases")
+ return self
+
+
+class _PyPIInfo(BaseModel):
+ name: str
+ version: str
+ requires_python: str
+
+
+class _PyPIFile(BaseModel):
+ model_config = ConfigDict(strict=True)
+ filename: str
+ size: int = Field(gt=0, le=2 * 1024**3)
+ url: str
+ digests: dict[str, str]
+ yanked: bool
+ requires_python: str | None = None
+
+
+class _PyPIRelease(BaseModel):
+ info: _PyPIInfo
+ urls: list[_PyPIFile] = Field(min_length=1, max_length=100)
+
+
+class _CatalogueCache(ReleaseRecord):
+ catalogue: ReleaseCatalogue
+ etag: str | None = Field(default=None, max_length=200)
+
+ @field_validator("etag")
+ @classmethod
+ def header_value(cls, value: str | None) -> str | None:
+ if value is not None and ("\r" in value or "\n" in value):
+ raise ValueError("Invalid catalogue ETag")
+ return value
+
+
+class ReleaseFeed:
+ """One bounded HTTP client for checking, exact-target revalidation and download.
+
+ The cache is only a generation/ETag guard. Network failure is never a successful
+ fresh check. A supplied transport is the test seam; production uses pinned DNS.
+ """
+
+ def __init__(self, cache_dir: Path, *, transport: httpx.AsyncBaseTransport | None = None,
+ python_version: str | None = None, supported_tags: list[Tag] | None = None) -> None:
+ self.cache_dir = cache_dir
+ self.python_version = python_version or platform.python_version()
+ self.tags = list(sys_tags()) if supported_tags is None else supported_tags
+ self.client = httpx.AsyncClient(
+ transport=transport or PinnedDNSAsyncTransport(), trust_env=False,
+ timeout=20, follow_redirects=False,
+ headers={"User-Agent": "nanobot-release-check", "Accept-Encoding": "identity"},
+ )
+
+ async def __aenter__(self) -> Self:
+ return self
+
+ async def __aexit__(self, *_: object) -> None:
+ await self.client.aclose()
+
+ @asynccontextmanager
+ async def _stream(self, url: str, *, hosts: set[str], etag: str | None = None) -> AsyncGenerator[httpx.Response]:
+ """Validate every redirect and keep the final response open for its reader."""
+ headers = {"If-None-Match": etag} if etag else {}
+ for _ in range(4):
+ _url(url, hosts)
+ async with self.client.stream("GET", url, headers=headers) as response:
+ if response.status_code in {301, 302, 303, 307, 308}:
+ location = response.headers.get("location")
+ if not location:
+ raise ReleaseFeedError("Release redirect has no destination")
+ url = urljoin(url, location)
+ headers = {}
+ continue
+ yield response
+ return
+ raise ReleaseFeedError("Too many release redirects")
+
+ async def _read(self, url: str, *, limit: int, etag: str | None = None) -> tuple[bytes | None, str | None]:
+ async with self._stream(url, hosts=_METADATA_HOSTS, etag=etag) as response:
+ if response.status_code == 304 and etag is not None:
+ return None, etag
+ response.raise_for_status()
+ data = bytearray()
+ async for chunk in response.aiter_bytes():
+ data.extend(chunk)
+ if len(data) > limit:
+ raise ReleaseFeedError("Release metadata exceeds its size limit")
+ return bytes(data), response.headers.get("etag")
+
+ def _cached(self) -> _CatalogueCache | None:
+ path = self.cache_dir / "catalogue.json"
+ if not path.exists():
+ return None
+ if path.stat().st_size > 512 * 1024:
+ raise ReleaseFeedError("Release cache is invalid; no update was selected")
+ return _CatalogueCache.model_validate_json(path.read_bytes())
+
+ async def catalogue(self) -> ReleaseCatalogue:
+ cached = self._cached()
+ payload, etag = await self._read(CATALOGUE_URL, limit=256 * 1024, etag=cached.etag if cached else None)
+ if payload is None:
+ if cached is None:
+ raise ReleaseFeedError("Release catalogue returned no data")
+ candidate = cached
+ else:
+ candidate = _CatalogueCache(catalogue=ReleaseCatalogue.model_validate_json(payload), etag=etag)
+ self.cache_dir.mkdir(parents=True, exist_ok=True, mode=0o700)
+ with FileLock(str(self.cache_dir / "catalogue.lock"), timeout=5):
+ previous = self._cached()
+ if previous:
+ try:
+ candidate.catalogue.validate_successor(previous.catalogue)
+ except ValueError as exc:
+ raise ReleaseFeedError(str(exc)) from exc
+ atomic_write_lines(self.cache_dir / "catalogue.json", [candidate.model_dump_json()])
+ return candidate.catalogue
+
+ async def stable(self, version: str | None = None) -> ReleaseTarget:
+ suffix = f"/{release_version(version)}" if version else ""
+ payload, _ = await self._read(f"{PYPI_URL}{suffix}/json", limit=4 * 1024 * 1024)
+ release = _PyPIRelease.model_validate_json(payload or b"")
+ identity = release_version(release.info.version)
+ if canonicalize_name(release.info.name) != "nanobot-ai" or Version(identity).is_prerelease:
+ raise ReleaseFeedError("PyPI did not return a stable nanobot release")
+ if version and identity != version:
+ raise ReleaseFeedError("PyPI returned a different version than requested")
+ required = {name for name in release_filenames(identity) if name.endswith((".whl", ".tar.gz"))}
+ if {file.filename for file in release.urls} != required or len(release.urls) != len(required):
+ raise ReleaseFeedError("The stable release is incomplete; no source-build fallback was selected", code="publishing")
+ if any(file.yanked for file in release.urls):
+ raise ReleaseFeedError("The release has been withdrawn from PyPI", code="withdrawn")
+ if not SpecifierSet(release.info.requires_python).contains(self.python_version, prereleases=True):
+ raise ReleaseFeedError(f"Release requires Python {release.info.requires_python}", code="unsupported")
+ for tag in self.tags:
+ for file in release.urls:
+ if not file.filename.endswith(".whl") or tag not in parse_wheel_filename(file.filename)[3]:
+ continue
+ if file.requires_python and not SpecifierSet(file.requires_python).contains(self.python_version, prereleases=True):
+ continue
+ return ReleaseTarget(
+ version=identity, source="pypi", url=file.url,
+ artifact=ReleaseArtifact(filename=file.filename, size=file.size, sha256=file.digests["sha256"]),
+ )
+ raise ReleaseFeedError("No compatible wheel is available for this Python and platform", code="unsupported")
+
+ async def latest(self, channel: Channel) -> ReleaseTarget:
+ if channel == "stable":
+ return await self.stable()
+ catalogue = await self.catalogue()
+ pointer = catalogue.latest(channel)
+ if pointer is None:
+ raise ReleaseFeedError("No eligible preview is available")
+ return await self._from_pointer(pointer, catalogue.generation)
+
+ async def discover(self, channel: Channel, current_version: str) -> tuple[ReleaseTarget | None, bool]:
+ """Select from one catalogue snapshot and report withdrawal independently.
+
+ Stable installations do not depend on the Preview catalogue. A preview
+ leaving that channel still checks its withdrawal status until replaced.
+ """
+ if channel == "stable" and not Version(current_version).is_prerelease:
+ return await self.stable(), False
+ try:
+ catalogue = await self.catalogue()
+ except (ReleaseFeedError, httpx.HTTPError, ValueError, OSError):
+ if channel != "stable":
+ raise
+ # An unavailable Preview index must not prevent leaving Preview for
+ # a verified newer final. Do not infer that the installed preview is
+ # safe/current when no such successor can replace it.
+ target = await self.stable()
+ if Version(target.version) <= Version(current_version):
+ raise
+ return target, False
+ withdrawn = current_version in catalogue.withdrawn
+ try:
+ if channel == "stable":
+ return await self.stable(), withdrawn
+ pointer = catalogue.latest(channel)
+ return (await self._from_pointer(pointer, catalogue.generation) if pointer else None), withdrawn
+ except (ReleaseFeedError, httpx.HTTPError, ValueError):
+ if withdrawn:
+ # A missing/incompatible replacement must not hide a freshly
+ # verified warning about the version already running.
+ return None, True
+ raise
+
+ async def _from_pointer(self, pointer: ReleasePointer, generation: int) -> ReleaseTarget:
+ payload, _ = await self._read(pointer.manifest_url, limit=64 * 1024)
+ manifest = pointer.verify_manifest(payload or b"")
+ try:
+ artifact = manifest.wheel_for(python_version=self.python_version, supported_tags=self.tags)
+ except ValueError as exc:
+ raise ReleaseFeedError("No compatible Preview wheel is available", code="unsupported") from exc
+ # A stable successor in the Preview channel must still be available on PyPI.
+ if not Version(manifest.version).is_prerelease:
+ stable = await self.stable(manifest.version)
+ if stable.artifact != artifact:
+ raise ReleaseFeedError("GitHub and PyPI stable artifacts differ")
+ return ReleaseTarget(version=manifest.version, artifact=artifact, source="github",
+ url=manifest.artifact_url(artifact).split("#", 1)[0],
+ pointer=pointer, catalogue_generation=generation)
+
+ async def revalidate(self, target: ReleaseTarget) -> None:
+ """Validate the approved target, never replace it with a new latest version."""
+ if target.source == "pypi":
+ current = await self.stable(target.version)
+ else:
+ catalogue = await self.catalogue()
+ if catalogue.generation < target.catalogue_generation:
+ raise ReleaseFeedError("Release catalogue predates the approved target")
+ if target.version in catalogue.withdrawn:
+ raise ReleaseFeedError(f"Release withdrawn: {catalogue.withdrawn[target.version]}")
+ assert target.pointer is not None # Validated by ReleaseTarget.
+ current = await self._from_pointer(target.pointer, catalogue.generation)
+ if (current.artifact, current.url) != (target.artifact, target.url):
+ raise ReleaseFeedError("The approved release artifact has changed")
+ await self._authorize(target)
+
+ async def _authorize(self, target: ReleaseTarget) -> None:
+ """A matching index checksum is not permission to execute new code.
+
+ Apply equally to PyPI/stable and GitHub/Preview, including revalidation
+ before handoff. Discovery remains possible for older unsigned releases,
+ but they cannot enter an automatic installation transaction.
+ """
+ base = f"{RELEASE_DOWNLOAD}/v{target.version}/release-manifest.json"
+ payload, _ = await self._read(base, limit=64 * 1024)
+ signature, _ = await self._read(base + ".sigstore.json", limit=256 * 1024)
+ try:
+ await asyncio.wait_for(
+ asyncio.to_thread(verify_release_approval, payload or b"", signature or b""), timeout=30,
+ )
+ except TimeoutError as exc:
+ # The verifier thread can only read/refresh public trust metadata;
+ # it has no installation capability even if its IO finishes later.
+ raise ReleaseFeedError("Release approval verification timed out; keep the current version and retry") from exc
+ manifest = ReleaseManifest.model_validate_json(payload or b"")
+ if manifest.version != target.version or target.artifact not in manifest.artifacts:
+ raise ReleaseFeedError("Release approval does not match the selected package")
+ if target.pointer is not None:
+ target.pointer.verify_manifest(payload or b"")
+
+ async def download(self, target: ReleaseTarget, directory: Path) -> Path:
+ """Stage one verified wheel. No execution, install, or extraction occurs."""
+ await self.revalidate(target)
+ directory.mkdir(parents=True, exist_ok=True, mode=0o700)
+ destination = directory / target.artifact.filename
+ if destination.exists() or destination.is_symlink():
+ _verify_wheel(destination, target)
+ return destination
+ temporary = directory / f".{uuid4().hex}.part"
+ try:
+ async with self._stream(target.url, hosts=_DOWNLOAD_HOSTS) as response:
+ response.raise_for_status()
+ size = 0
+ with temporary.open("xb") as handle:
+ async for chunk in response.aiter_bytes():
+ size += len(chunk)
+ if size > target.artifact.size:
+ raise ReleaseFeedError("Release download exceeds its verified size")
+ handle.write(chunk)
+ _verify_wheel(temporary, target)
+ # Never clobber a file another update already staged.
+ try:
+ destination.hardlink_to(temporary)
+ except FileExistsError:
+ _verify_wheel(destination, target)
+ return destination
+ finally:
+ temporary.unlink(missing_ok=True)
+
+
+def _verify_wheel(path: Path, target: ReleaseTarget) -> None:
+ if path.is_symlink() or not path.is_file() or path.stat().st_size != target.artifact.size:
+ raise ReleaseFeedError("Staged wheel size or file type does not match")
+ with path.open("rb") as handle:
+ if hashlib.file_digest(handle, "sha256").hexdigest() != target.artifact.sha256:
+ raise ReleaseFeedError("Staged wheel checksum does not match")
+ with ZipFile(path) as wheel:
+ metadata_name = f"nanobot_ai-{target.version}.dist-info/METADATA"
+ names = wheel.namelist()
+ if len(names) != len(set(names)) or any(re.search(r"(^/|\\|(?:^|/)\.\.(?:/|$))", name) for name in names):
+ raise ReleaseFeedError("Invalid wheel member paths")
+ if wheel.getinfo(metadata_name).file_size > 256 * 1024:
+ raise ReleaseFeedError("Wheel metadata exceeds its size limit")
+ metadata = BytesParser().parsebytes(wheel.read(metadata_name))
+ if metadata["Name"] != "nanobot-ai" or metadata["Version"] != target.version:
+ raise ReleaseFeedError("Wheel metadata does not match the approved release")
diff --git a/nanobot/release_trust.py b/nanobot/release_trust.py
new file mode 100644
index 000000000..ac8a1da71
--- /dev/null
+++ b/nanobot/release_trust.py
@@ -0,0 +1,44 @@
+"""Authenticate release approval separately from the download service's hashes.
+
+The installed verifier owns the trust policy. Neither a feed, a signature bundle,
+nor an environment variable may choose the signing identity or trust root.
+"""
+
+from __future__ import annotations
+
+RELEASE_IDENTITY = (
+ "https://github.com/HKUDS/nanobot/.github/workflows/release-approve.yml@refs/heads/main"
+)
+RELEASE_ISSUER = "https://token.actions.githubusercontent.com"
+
+
+def verify_release_approval(payload: bytes, signature: bytes) -> None:
+ """Require the official, manually approved workflow's logged signature.
+
+ Sigstore verifies the certificate chain, transparency-log inclusion and
+ artifact signature. Refreshing its production TUF root is fail-closed; do
+ not replace this with an unverified local cache or a root from the release.
+ Imports are lazy so a broken/missing verifier cannot prevent gateway startup
+ or the independent recovery worker from running.
+ """
+ if not payload or len(payload) > 64 * 1024 or not signature or len(signature) > 256 * 1024:
+ raise ValueError("Release approval is missing or exceeds its size limit")
+ try:
+ from sigstore.models import Bundle
+ from sigstore.verify import Verifier
+ from sigstore.verify.policy import AllOf, GitHubWorkflowTrigger, Identity
+
+ policy = AllOf([
+ Identity(identity=RELEASE_IDENTITY, issuer=RELEASE_ISSUER),
+ GitHubWorkflowTrigger("workflow_dispatch"),
+ ])
+ # Reject malformed remote input before refreshing the trust service.
+ # Parsing a bundle grants no authority: the fixed verifier still checks
+ # its certificate, log proof, policy and signature over the exact bytes.
+ bundle = Bundle.from_json(signature)
+ Verifier.production().verify_artifact(payload, bundle, policy)
+ except Exception as exc:
+ # Keep library/network/certificate details out of the public job. A
+ # missing verifier, unavailable trust service or invalid proof all deny
+ # installation; none authorize a checksum-only fallback.
+ raise ValueError("Could not verify the official release approval; the current installation was not changed") from exc
diff --git a/nanobot/releases.py b/nanobot/releases.py
new file mode 100644
index 000000000..ac84cd2f9
--- /dev/null
+++ b/nanobot/releases.py
@@ -0,0 +1,169 @@
+"""Release identities shared by packaging and channel-aware update discovery.
+
+This module validates data and selects artifacts. It never installs packages, trusts
+arbitrary download URLs, or treats a build manifest as publication approval.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import re
+from collections.abc import Iterable
+from typing import Annotated, Literal, Self
+
+from packaging.specifiers import SpecifierSet
+from packaging.tags import Tag
+from packaging.utils import parse_wheel_filename
+from packaging.version import Version
+from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
+
+Channel = Literal["stable", "preview"]
+Sha256 = Annotated[str, Field(pattern=r"^[0-9a-f]{64}$")]
+Commit = Annotated[str, Field(pattern=r"^[0-9a-f]{40}$")]
+
+# Minimums verified against BOTH Bun and the embedded OpenTUI library.
+PLATFORMS = {
+ "darwin-arm64": "macosx_13_0_arm64",
+ "darwin-x64": "macosx_13_0_x86_64",
+ "linux-arm64": "manylinux_2_17_aarch64",
+ "linux-x64": "manylinux_2_17_x86_64",
+ "win32-x64": "win_amd64",
+}
+RELEASE_DOWNLOAD = "https://github.com/HKUDS/nanobot/releases/download"
+
+
+def release_version(value: str) -> str:
+ """Accept canonical versions we publish, not epochs, local builds or refs."""
+ if not re.fullmatch(r"\d+\.\d+\.\d+(?:\.dev\d+|\.post\d+)?", value):
+ raise ValueError("Expected a stable or development release version")
+ if str(Version(value)) != value:
+ raise ValueError("Release version must be canonical")
+ return value
+
+
+def release_filenames(version: str) -> set[str]:
+ """The complete upload set, excluding the intermediate universal wheel."""
+ release_version(version)
+ names = {f"nanobot_ai-{version}-py3-none-{platform}.whl" for platform in PLATFORMS.values()}
+ names.add(f"nanobot_ai-{version}.tar.gz")
+ for target in PLATFORMS:
+ asset = f"nanobot-tui-{target}" + (".exe" if target == "win32-x64" else "")
+ names.update((f"{asset}.zip", f"{asset}.zip.sha256"))
+ return names
+
+
+class ReleaseRecord(BaseModel):
+ model_config = ConfigDict(extra="forbid", frozen=True, strict=True)
+
+
+class ReleaseArtifact(ReleaseRecord):
+ filename: str = Field(pattern=r"^[A-Za-z0-9_.-]+$", max_length=200)
+ size: int = Field(gt=0, le=2 * 1024**3)
+ sha256: Sha256
+
+
+class ReleaseManifest(ReleaseRecord):
+ schema_version: Literal[1] = 1
+ version: str
+ source_commit: Commit
+ candidate_commit: Commit
+ requires_python: str
+ artifacts: list[ReleaseArtifact] = Field(min_length=16, max_length=16)
+
+ _version = field_validator("version")(release_version)
+
+ @field_validator("requires_python")
+ @classmethod
+ def validate_python(cls, value: str) -> str:
+ if not value or len(value) > 200:
+ raise ValueError("A bounded Python version requirement is required")
+ SpecifierSet(value)
+ return value
+
+ @model_validator(mode="after")
+ def complete_artifacts(self) -> Self:
+ if {item.filename for item in self.artifacts} != release_filenames(self.version):
+ raise ValueError("Manifest must contain the complete, matching five-platform release")
+ return self
+
+ def wheel_for(self, *, python_version: str, supported_tags: Iterable[Tag]) -> ReleaseArtifact:
+ """Select using the target interpreter's tags, never the browser platform."""
+ if not SpecifierSet(self.requires_python).contains(python_version, prereleases=True):
+ raise ValueError(f"Release {self.version} requires Python {self.requires_python}")
+ wheels = {
+ tag: artifact
+ for artifact in self.artifacts if artifact.filename.endswith(".whl")
+ for tag in parse_wheel_filename(artifact.filename)[3]
+ }
+ for tag in supported_tags:
+ if tag in wheels:
+ return wheels[tag]
+ raise ValueError("No compatible release wheel; use the documented source/classic path")
+
+ def artifact_url(self, artifact: ReleaseArtifact) -> str:
+ if artifact not in self.artifacts:
+ raise ValueError("Artifact does not belong to this release")
+ return f"{RELEASE_DOWNLOAD}/v{self.version}/{artifact.filename}#sha256={artifact.sha256}"
+
+
+class ReleasePointer(ReleaseRecord):
+ version: str
+ candidate_commit: Commit
+ manifest_sha256: Sha256
+
+ _version = field_validator("version")(release_version)
+
+ @property
+ def manifest_url(self) -> str:
+ return f"{RELEASE_DOWNLOAD}/v{self.version}/release-manifest.json"
+
+ def verify_manifest(self, payload: bytes) -> ReleaseManifest:
+ if len(payload) > 64 * 1024 or hashlib.sha256(payload).hexdigest() != self.manifest_sha256:
+ raise ValueError("Release manifest size or checksum mismatch")
+ manifest = ReleaseManifest.model_validate_json(payload)
+ if (manifest.version, manifest.candidate_commit) != (self.version, self.candidate_commit):
+ raise ValueError("Release manifest identity does not match the selected candidate")
+ return manifest
+
+
+class ReleaseCatalogue(ReleaseRecord):
+ schema_version: Literal[1] = 1
+ generation: int = Field(gt=0)
+ stable: ReleasePointer | None = None
+ preview: ReleasePointer | None = None
+ withdrawn: dict[str, str] = Field(default_factory=dict, max_length=1000)
+
+ @model_validator(mode="after")
+ def validate_channels(self) -> Self:
+ if self.stable and Version(self.stable.version).is_prerelease:
+ raise ValueError("Stable channel cannot contain a prerelease")
+ if self.preview and not Version(self.preview.version).is_devrelease:
+ raise ValueError("Preview pointer must identify a development release")
+ for version, reason in self.withdrawn.items():
+ release_version(version)
+ if not reason.strip() or len(reason) > 2000:
+ raise ValueError("A bounded withdrawal reason is required")
+ return self
+
+ def validate_successor(self, previous: Self) -> None:
+ """A new index generation cannot rewrite already observed releases."""
+ if self.generation < previous.generation or (self.generation == previous.generation and self != previous):
+ raise ValueError("Release catalogue changed without a newer generation")
+ if not previous.withdrawn.keys() <= self.withdrawn.keys():
+ raise ValueError("Release catalogue cannot reinstate withdrawn versions")
+ for old, new in ((previous.stable, self.stable), (previous.preview, self.preview)):
+ if old is None:
+ continue
+ if new is None:
+ raise ValueError("Release channel cannot erase a published pointer; withdraw the version instead")
+ if Version(new.version) < Version(old.version):
+ raise ValueError("Release channel cannot move to an older version")
+ if new.version == old.version and new != old:
+ raise ValueError("Published version cannot change its commit or manifest")
+
+ def latest(self, channel: Channel, *, minimum_generation: int = 0) -> ReleasePointer | None:
+ if self.generation < minimum_generation:
+ raise ValueError("Release catalogue is older than the last accepted generation")
+ candidates = [self.stable] if channel == "stable" else [self.stable, self.preview]
+ eligible = [item for item in candidates if item and item.version not in self.withdrawn]
+ return max(eligible, key=lambda item: Version(item.version), default=None)
diff --git a/nanobot/runtime_admission.py b/nanobot/runtime_admission.py
new file mode 100644
index 000000000..83c646dc2
--- /dev/null
+++ b/nanobot/runtime_admission.py
@@ -0,0 +1,115 @@
+"""Event-loop-local task admission during an explicitly requested maintenance window.
+
+This gate coordinates work in one runtime. It is not an installation/data lock or
+proof that another process, a channel, or an external store has stopped writing.
+The update owner must still stop and flush those writers before backup/install.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from collections.abc import Callable, Generator
+from contextlib import contextmanager
+
+
+class RuntimeMaintenanceError(RuntimeError):
+ """New work cannot enter a runtime held for maintenance."""
+
+
+class RuntimeBusyError(RuntimeError):
+ """Maintenance would interrupt accepted work."""
+
+
+class RuntimeAdmission:
+ """Share between the gateway's bus, agent, cron and local trigger intake.
+
+ All methods run on their owning event-loop thread. Checking, counting work
+ and closing admission are synchronous: no task can enter between the idle
+ check and the pause. Do not call this object from an installer worker thread.
+ """
+
+ def __init__(self) -> None:
+ self._paused = False
+ self._active = 0
+ self._pending_checks: list[Callable[[], bool]] = []
+ self._open = asyncio.Event()
+ self._open.set()
+
+ @property
+ def paused(self) -> bool:
+ return self._paused
+
+ def check(self) -> None:
+ if self._paused:
+ raise RuntimeMaintenanceError(
+ "nanobot is preparing an update. Try again after maintenance finishes."
+ )
+
+ async def wait_until_open(self) -> None:
+ """Pause scheduler intake without consuming or rescheduling pending work."""
+ while self._paused:
+ await self._open.wait()
+
+ def register_pending_work(self, check: Callable[[], bool]) -> Callable[[], None]:
+ """Account for an owner's queued/detached work until it is shut down.
+
+ Like activity(), registration and inspection are event-loop-local. The
+ owner removes its check only after closing its writers. Checks must not
+ mutate state or yield, so admission can close without an idle-check gap.
+ """
+ self.check()
+ self._pending_checks.append(check)
+ registered = True
+
+ def remove() -> None:
+ nonlocal registered
+ if registered:
+ self._pending_checks.remove(check)
+ registered = False
+
+ return remove
+
+ @contextmanager
+ def activity(self) -> Generator[None, None, None]:
+ """Account for accepted work, including its awaited cleanup."""
+ self.check()
+ self._active += 1
+ try:
+ yield
+ finally:
+ self._active -= 1
+
+ @contextmanager
+ def pause_if_idle(self, has_pending_work: Callable[[], bool]) -> Generator[None, None, None]:
+ """Refuse busy runtimes without cancelling work or leaving intake closed.
+
+ The owner supplies a synchronous view of queued/detached work which
+ outlives an ``activity`` call. Hold this context through the handoff;
+ releasing it after a refused/aborted update restores prior admission.
+ """
+ self.check()
+ if self._active or has_pending_work() or any(check() for check in self._pending_checks):
+ raise RuntimeBusyError(
+ "nanobot has pending work. Finish active tasks and retry the update."
+ )
+ with self.pause_before_start():
+ yield
+
+ @contextmanager
+ def pause_before_start(self) -> Generator[None, None, None]:
+ """Hold a fresh runtime before starting any consumers or external intake.
+
+ Startup may already have reconstructed a durable recovery queue. It must
+ not execute that queue until activation. Running gateways must instead
+ use pause_if_idle, which also checks their owner's pending-work view.
+ """
+ self.check()
+ if self._active:
+ raise RuntimeBusyError("Runtime work has already started")
+ self._paused = True
+ self._open.clear()
+ try:
+ yield
+ finally:
+ self._paused = False
+ self._open.set()
diff --git a/nanobot/triggers/local_runner.py b/nanobot/triggers/local_runner.py
index 39f82c1c0..1e7b19b3e 100644
--- a/nanobot/triggers/local_runner.py
+++ b/nanobot/triggers/local_runner.py
@@ -11,6 +11,7 @@ from loguru import logger
from nanobot.agent.automation_turns import AutomationTurnError
from nanobot.bus.events import InboundMessage, OutboundMessage
+from nanobot.runtime_admission import RuntimeAdmission
from nanobot.triggers.local_session_turns import LOCAL_TRIGGER_META
from nanobot.triggers.local_store import LocalTriggerStore
from nanobot.triggers.local_types import LocalTrigger, TriggerDelivery
@@ -24,11 +25,14 @@ async def run_local_trigger_queue(
is_channel_enabled: Callable[[str], bool],
poll_interval_s: float = 0.5,
batch_size: int = 20,
+ admission: RuntimeAdmission | None = None,
) -> None:
"""Poll local trigger deliveries and submit them as session turns."""
if submit_turn is None:
raise ValueError("run_local_trigger_queue requires submit_turn")
+ gate = admission if admission is not None else RuntimeAdmission()
logger.info("Local trigger queue started")
+ await gate.wait_until_open()
recovered = store.recover_processing_deliveries()
if recovered:
logger.warning(
@@ -36,91 +40,69 @@ async def run_local_trigger_queue(
recovered,
)
while True:
- deliveries = store.claim_deliveries(limit=batch_size)
- if not deliveries:
- await asyncio.sleep(poll_interval_s)
- continue
-
- for delivery in deliveries:
- try:
- await _deliver_delivery(
- store,
- delivery,
- submit_turn=submit_turn,
+ await gate.wait_until_open()
+ with gate.activity():
+ deliveries = store.claim_deliveries(limit=batch_size)
+ for delivery in deliveries:
+ await _run_delivery(
+ store, delivery, submit_turn=submit_turn,
is_channel_enabled=is_channel_enabled,
)
- store.complete_delivery(delivery)
- except asyncio.CancelledError as exc:
- store.retry_delivery(delivery, str(exc) or exc.__class__.__name__)
- _write_delivery_run_record(
- store,
- delivery,
- status="interrupted",
- error=str(exc) or exc.__class__.__name__,
- )
- raise
- except _TerminalDeliveryError as exc:
- store.record_delivery(
- delivery.trigger_id,
- status="error",
- error=str(exc),
- run_at_ms=delivery.created_at_ms,
- )
- _write_delivery_run_record(
- store,
- delivery,
- status="error",
- error=str(exc),
- )
- store.complete_delivery(delivery)
- logger.warning(
- "Trigger: dropped delivery {} for {}: {}",
- delivery.id,
- delivery.trigger_id,
- exc,
- )
- except AutomationTurnError as exc:
- error = str(exc) or exc.__class__.__name__
- store.record_delivery(
- delivery.trigger_id,
- status="error",
- error=error,
- run_at_ms=delivery.created_at_ms,
- )
- _write_delivery_run_record(
- store,
- delivery,
- status="error",
- error=error,
- )
- store.complete_delivery(delivery)
- logger.warning(
- "Trigger: delivery {} for {} reached the agent but failed: {}",
- delivery.id,
- delivery.trigger_id,
- error,
- )
- except Exception as exc:
- error = str(exc) or exc.__class__.__name__
- retried = store.retry_delivery(delivery, error)
- _write_delivery_run_record(
- store,
- delivery,
- status="retrying" if retried else "error",
- error=error,
- )
- store.record_delivery(
- delivery.trigger_id,
- status="error",
- error=error,
- run_at_ms=delivery.created_at_ms,
- )
- logger.exception(
- "Trigger: failed delivery {} for {}{}",
- delivery.id,
- delivery.trigger_id,
- "; queued retry" if retried else "; moved to failed queue",
- )
+ if not deliveries:
+ await asyncio.sleep(poll_interval_s)
+
+
+async def _run_delivery(
+ store: LocalTriggerStore,
+ delivery: TriggerDelivery,
+ *,
+ submit_turn: Callable[[InboundMessage], Awaitable[OutboundMessage | None]],
+ is_channel_enabled: Callable[[str], bool],
+) -> None:
+ try:
+ await _deliver_delivery(
+ store, delivery, submit_turn=submit_turn, is_channel_enabled=is_channel_enabled,
+ )
+ store.complete_delivery(delivery)
+ except asyncio.CancelledError as exc:
+ store.retry_delivery(delivery, str(exc) or exc.__class__.__name__)
+ _write_delivery_run_record(
+ store, delivery, status="interrupted", error=str(exc) or exc.__class__.__name__,
+ )
+ raise
+ except _TerminalDeliveryError as exc:
+ store.record_delivery(
+ delivery.trigger_id, status="error", error=str(exc), run_at_ms=delivery.created_at_ms,
+ )
+ _write_delivery_run_record(store, delivery, status="error", error=str(exc))
+ store.complete_delivery(delivery)
+ logger.warning(
+ "Trigger: dropped delivery {} for {}: {}", delivery.id, delivery.trigger_id, exc,
+ )
+ except AutomationTurnError as exc:
+ error = str(exc) or exc.__class__.__name__
+ store.record_delivery(
+ delivery.trigger_id, status="error", error=error, run_at_ms=delivery.created_at_ms,
+ )
+ _write_delivery_run_record(store, delivery, status="error", error=error)
+ store.complete_delivery(delivery)
+ logger.warning(
+ "Trigger: delivery {} for {} reached the agent but failed: {}",
+ delivery.id, delivery.trigger_id, error,
+ )
+ except Exception as exc:
+ error = str(exc) or exc.__class__.__name__
+ retried = store.retry_delivery(delivery, error)
+ _write_delivery_run_record(
+ store, delivery, status="retrying" if retried else "error", error=error,
+ )
+ store.record_delivery(
+ delivery.trigger_id, status="error", error=error, run_at_ms=delivery.created_at_ms,
+ )
+ logger.exception(
+ "Trigger: failed delivery {} for {}{}", delivery.id, delivery.trigger_id,
+ "; queued retry" if retried else "; moved to failed queue",
+ )
class _TerminalDeliveryError(RuntimeError):
diff --git a/nanobot/update.py b/nanobot/update.py
new file mode 100644
index 000000000..b4cf5582e
--- /dev/null
+++ b/nanobot/update.py
@@ -0,0 +1,329 @@
+"""Update the current installation from PyPI or an editable source checkout."""
+
+from __future__ import annotations
+
+import importlib
+import json
+import os
+import shutil
+import subprocess
+import sys
+import sysconfig
+import tempfile
+import tomllib
+import urllib.request
+from collections.abc import Callable, Generator
+from contextlib import contextmanager, suppress
+from importlib.metadata import MetadataPathFinder, PackageNotFoundError, distribution
+from pathlib import Path
+from typing import TypedDict
+
+from packaging.version import Version
+
+from nanobot import __version__
+from nanobot.bun import bun_environment, ensure_bun
+from nanobot.installation_lock import (
+ InstallationBusyError,
+ installation_access,
+ installation_id,
+ pending_update_path,
+)
+
+_SOURCE_URL = "https://github.com/HKUDS/nanobot.git"
+
+
+class UpdateError(RuntimeError):
+ """An update cannot proceed or did not finish successfully."""
+
+ def __init__(self, message: str, *, needs_repair: bool = False) -> None:
+ super().__init__(message)
+ self.needs_repair = needs_repair
+
+
+class UpdateResult(TypedDict):
+ version: str
+ source: str
+ requires_restart: bool
+
+
+def _run(
+ command: list[str], *, cwd: Path | None = None, env: dict[str, str] | None = None,
+) -> subprocess.CompletedProcess[str]:
+ try:
+ result = subprocess.run(
+ command, cwd=cwd, env=env, capture_output=True, text=True,
+ encoding="utf-8", errors="replace", timeout=900,
+ )
+ except (OSError, subprocess.TimeoutExpired) as exc:
+ raise UpdateError(f"Could not run {Path(command[0]).name}: {exc}") from exc
+ return result
+
+
+def _checked(command: list[str], *, cwd: Path | None = None) -> str:
+ result = _run(command, cwd=cwd)
+ if result.returncode:
+ raise UpdateError((result.stderr or result.stdout).strip()[-4000:])
+ return result.stdout.strip()
+
+
+def source_checkout() -> Path | None:
+ root = Path(__file__).resolve().parent.parent
+ if (root / "pyproject.toml").is_file() and (root / "tui/package.json").is_file():
+ return root
+ return None
+
+
+def latest_release() -> str:
+ """Read the current stable PyPI release; network failures are not 'up to date'."""
+ try:
+ with urllib.request.urlopen("https://pypi.org/pypi/nanobot-ai/json", timeout=15) as response:
+ payload = json.loads(response.read(4 * 1024 * 1024))
+ version = payload["info"]["version"]
+ if not isinstance(version, str) or not version:
+ raise ValueError("missing release version")
+ parsed = Version(version)
+ if parsed.is_prerelease or parsed.is_devrelease:
+ raise ValueError("PyPI returned a prerelease")
+ return str(parsed)
+ except (OSError, ValueError, KeyError, TypeError) as exc:
+ raise UpdateError(f"Could not check PyPI: {exc}") from exc
+
+
+def update_blocked_reason(*, dev: bool = False) -> str:
+ """Do not replace files owned by another deployment or package manager."""
+ if Path("/.dockerenv").exists() or os.environ.get("RENDER") == "true":
+ return "This installation is deployed in a container. Rebuild and redeploy its image."
+ prefix = Path(sys.prefix)
+ if (prefix / "uv-receipt.toml").exists():
+ return "Use `uv tool upgrade nanobot-ai` in the gateway's account to preserve its uv tool settings."
+ if (prefix / "pipx_metadata.json").exists():
+ return "Update through pipx in the gateway's account. Review its original constraints and installer options before upgrading; a generic pipx upgrade can discard them."
+ if sys.prefix == sys.base_prefix:
+ return "Use the installer or package manager that owns this Python installation. In-app updates require a virtual environment."
+ if not dev and source_checkout() is not None:
+ return (
+ "This gateway runs from source. Use the source update option to keep its checkout. "
+ "To switch to a release, stop nanobot, install it in a separate environment, "
+ "and launch it outside the checkout."
+ )
+ return ""
+
+
+def incomplete_update() -> bool:
+ """A marker survives failure or process termination after mutation begins."""
+ return pending_update_path().exists()
+
+
+def _mark_installing() -> None:
+ path = pending_update_path()
+ path.parent.mkdir(parents=True, exist_ok=True)
+ with path.open("w", encoding="utf-8") as marker:
+ marker.write("Installation may be incomplete. Stop nanobot and retry the update.\n")
+ marker.flush()
+ os.fsync(marker.fileno())
+
+
+def _verify_installation(expected: str, source: str) -> None:
+ # Match normal `python -m nanobot` restart resolution as well as isolated
+ # installed-package resolution. A version from dist-info alone can hide a
+ # checkout shadowing the installed wheel through cwd or PYTHONPATH.
+ probe = (
+ "import json, nanobot; from pathlib import Path; "
+ "print(json.dumps([nanobot.__version__, str(Path(nanobot.__file__).resolve())]))"
+ )
+ installed = json.loads(_checked([sys.executable, "-I", "-c", probe]))
+ restarted = json.loads(_checked([sys.executable, "-c", probe]))
+ if installed[0] != expected:
+ raise UpdateError(f"Installed version is {installed[0]}, expected {expected}. Check the installation environment.")
+ if installed != restarted:
+ raise UpdateError(
+ "The restart would load a different nanobot package. Stop nanobot and restart "
+ "outside the source checkout, without a source directory in PYTHONPATH."
+ )
+ if source != "pypi" and Path(installed[1]).parent != Path(source) / "nanobot":
+ raise UpdateError("The interpreter does not load the updated source checkout. Check the editable installation.")
+
+
+def _prepare_source(
+ output: Callable[[str], None], *, before_change: Callable[[], None] = lambda: None,
+) -> Path:
+ git = shutil.which("git")
+ if not git:
+ raise UpdateError("Source updates require Git. Install Git and retry, or use a release update.")
+ root = source_checkout()
+ if root is None:
+ root = Path.home() / ".nanobot" / "src" / installation_id()[:16]
+ root.parent.mkdir(parents=True, exist_ok=True)
+ if not root.exists():
+ output("Downloading nanobot source…")
+ with tempfile.TemporaryDirectory(prefix=".clone-", dir=root.parent) as temporary:
+ candidate = Path(temporary) / "nanobot"
+ _checked([git, "clone", "--depth", "1", "--branch", "main", _SOURCE_URL, str(candidate)])
+ candidate.rename(root)
+ if not (root / ".git").exists():
+ raise UpdateError(f"{root} is not a Git checkout. Update its sources manually.")
+ if _checked([git, "status", "--porcelain"], cwd=root):
+ raise UpdateError(f"Source checkout has local changes: {root}. Commit or move them before updating.")
+ branch = _checked([git, "branch", "--show-current"], cwd=root)
+ if not branch:
+ raise UpdateError("Source checkout has a detached HEAD. Select a branch before updating.")
+ remote_result = _run([git, "config", f"branch.{branch}.remote"], cwd=root)
+ remote = remote_result.stdout.strip()
+ if remote_result.returncode or not remote:
+ raise UpdateError("The source branch has no upstream. Configure its upstream before updating.")
+ output(f"Updating source branch {branch}…")
+ _checked([git, "fetch", "--", remote], cwd=root)
+ if _run([git, "merge-base", "--is-ancestor", "HEAD", "@{upstream}"], cwd=root).returncode:
+ raise UpdateError("The source branch cannot fast-forward to its upstream. Reconcile it manually.")
+ before_change()
+ _checked([git, "merge", "--ff-only", "@{upstream}"], cwd=root)
+ return root
+
+
+def _install(arguments: list[str], *, upgrade: bool = False) -> None:
+ from nanobot.optional_features import install_packages
+
+ with _release_windows_launchers():
+ result = install_packages(arguments, "nanobot update", upgrade=upgrade, runner=_run)
+ if not result.ok:
+ raise UpdateError(f"Package installation failed: {result.output[-4000:]}")
+
+
+@contextmanager
+def _release_windows_launchers() -> Generator[None]:
+ """Windows permits renaming running launchers, but pip cannot overwrite them."""
+ moved: list[tuple[Path, Path]] = []
+ try:
+ if sys.platform == "win32":
+ import gc
+
+ # Metadata discovery can keep the launcher's embedded ZIP open on Windows.
+ importlib.invalidate_caches()
+ MetadataPathFinder().invalidate_caches()
+ gc.collect()
+ scripts = Path(sysconfig.get_path("scripts"))
+ for name in ("nanobot.exe", "nanobot-desktop-tui.exe"):
+ launcher = scripts / name
+ backup = scripts / f".{name}.update-backup"
+ try:
+ if backup.is_file() and not launcher.exists():
+ backup.rename(launcher)
+ else:
+ backup.unlink(missing_ok=True)
+ except PermissionError as exc:
+ raise UpdateError("Restart running nanobot processes before updating again.") from exc
+ if launcher.is_file():
+ try:
+ launcher.rename(backup)
+ except PermissionError as exc:
+ raise UpdateError(
+ "Stop other nanobot processes and retry with `python -m nanobot update`."
+ ) from exc
+ moved.append((launcher, backup))
+ yield
+ finally:
+ for launcher, backup in reversed(moved):
+ if not launcher.exists():
+ backup.rename(launcher)
+ else:
+ # An old gateway/console may still hold this file; the next update cleans it.
+ with suppress(PermissionError):
+ backup.unlink(missing_ok=True)
+
+
+def _is_editable() -> bool:
+ try:
+ raw = distribution("nanobot-ai").read_text("direct_url.json")
+ return bool(raw and json.loads(raw).get("dir_info", {}).get("editable"))
+ except (PackageNotFoundError, ValueError):
+ return False
+
+
+def _installed_version() -> Version:
+ # Another gateway or CLI process may have changed this shared environment
+ # since __version__ was imported. Read the interpreter's current metadata.
+ probe = (
+ "from importlib.metadata import version, PackageNotFoundError\n"
+ "try: print(version('nanobot-ai'))\n"
+ "except PackageNotFoundError: print('')\n"
+ )
+ return Version(_checked([sys.executable, "-I", "-c", probe]) or __version__)
+
+
+def update_installation(
+ *, dev: bool = False, allow_downgrade: bool = False, output: Callable[[str], None] = print,
+) -> UpdateResult:
+ """Update application files and verify their version in a fresh interpreter."""
+ reason = update_blocked_reason(dev=dev)
+ if reason:
+ raise UpdateError(reason)
+ try:
+ with installation_access(updating=True):
+ if incomplete_update():
+ with pending_update_path().open("rb") as marker:
+ legacy_marker = marker.read(31).startswith(b"Installation may be incomplete.")
+ if not legacy_marker:
+ raise UpdateError(
+ "A saved update job owns this installation. Resume that exact job; "
+ "the legacy updater cannot replace it with a new target.", needs_repair=True,
+ )
+ if dev:
+ bun = ensure_bun(output=output)
+ root = _prepare_source(output, before_change=_mark_installing)
+ output("Preparing TUI dependencies…")
+ with bun_environment(bun) as env:
+ result = _run([bun, "install", "--frozen-lockfile"], cwd=root / "tui", env=env)
+ if result.returncode:
+ raise UpdateError(f"TUI dependencies failed: {(result.stderr or result.stdout)[-4000:]}")
+ output("Building WebUI…")
+ from nanobot.webui.build import build_webui_bundle
+
+ build_webui_bundle(
+ source_dir=root / "webui", dist_dir=root / "nanobot/web/dist",
+ runner=bun, output=output,
+ )
+ output("Synchronizing Python dependencies…")
+ _install(["--editable", str(root)])
+ expected = str(tomllib.loads((root / "pyproject.toml").read_text(encoding="utf-8"))["project"]["version"])
+ source = str(root)
+ else:
+ expected = latest_release()
+ installed = _installed_version()
+ current = max(installed, Version(__version__))
+ if Version(expected) < current and not allow_downgrade:
+ raise UpdateError(
+ f"Current version {current} is newer than stable {expected}. "
+ "No files changed. Back up your data before an intentional downgrade, "
+ "then run `nanobot update --allow-downgrade`."
+ )
+ target = f"nanobot-ai=={expected}"
+ editable = _is_editable()
+ repairing = incomplete_update()
+ if Version(expected) == installed and not editable and not repairing:
+ _verify_installation(expected, "pypi")
+ return {
+ "version": expected, "source": "pypi",
+ "requires_restart": installed != Version(__version__),
+ }
+ output(f"Installing nanobot {expected} from PyPI…")
+ _mark_installing()
+ _install([target], upgrade=True)
+ if repairing or (editable and _is_editable()):
+ # Same-version metadata does not prove files survived an interrupted
+ # install. Resolve dependencies above, then replace application files.
+ _install(["--force-reinstall", "--no-deps", target])
+ source = "pypi"
+ output("Verifying the installed version…")
+ _verify_installation(expected, source)
+ pending_update_path().unlink()
+ return {"version": expected, "source": source, "requires_restart": True}
+ except InstallationBusyError as exc:
+ raise UpdateError(str(exc), needs_repair=incomplete_update()) from exc
+ except Exception as exc:
+ if incomplete_update():
+ raise UpdateError(
+ f"{exc}\nInstallation may be incomplete. Stop nanobot and retry the same update "
+ "from its Python environment before restarting. No automatic rollback was performed.",
+ needs_repair=True,
+ ) from exc
+ raise
diff --git a/nanobot/update_backup.py b/nanobot/update_backup.py
new file mode 100644
index 000000000..5ee15c28e
--- /dev/null
+++ b/nanobot/update_backup.py
@@ -0,0 +1,217 @@
+"""Private, scoped pre-update snapshots for the standalone update worker.
+
+Only named nanobot stores are included, never the whole home or user project.
+The caller must stop writers first; checking a stable inventory detects concurrent
+changes but is not a substitute for that ownership handoff. This module deliberately
+does not implement automatic restore or claim to snapshot external services.
+"""
+
+from __future__ import annotations
+
+import errno
+import hashlib
+import json
+import os
+import shutil
+import stat
+import tempfile
+import time
+from contextlib import suppress
+from dataclasses import asdict, dataclass
+from pathlib import Path
+from typing import Literal, cast
+from zipfile import ZIP_STORED, ZipFile
+
+from nanobot.utils.atomic_file import atomic_write_lines
+
+_MAX_ENTRIES = 100_000
+_MAX_BYTES = 10 * 1024**3
+
+
+@dataclass(frozen=True)
+class BackupSource:
+ path: str
+
+ @classmethod
+ def parse(cls, value: object) -> BackupSource:
+ if not isinstance(value, dict):
+ raise ValueError("Invalid backup source")
+ path = cast(dict[object, object], value).get("path")
+ if not isinstance(path, str) or not Path(path).is_absolute() or len(path) > 4096 or "\0" in path:
+ raise ValueError("Backup sources must be bounded absolute paths")
+ return cls(path)
+
+
+def unique_sources(sources: list[BackupSource]) -> tuple[BackupSource, ...]:
+ return tuple(BackupSource(path) for path in sorted({source.path for source in sources}))
+
+
+@dataclass(frozen=True)
+class _Entry:
+ path: str
+ kind: Literal["file", "directory", "missing"]
+ size: int
+ mode: int
+ mtime_ns: int
+ ctime_ns: int
+ device: int
+ inode: int
+
+
+def _entry(path: Path) -> _Entry:
+ try:
+ info = path.lstat()
+ except FileNotFoundError:
+ return _Entry(str(path), "missing", 0, 0, 0, 0, 0, 0)
+ if stat.S_ISLNK(info.st_mode) or getattr(info, "st_file_attributes", 0) & stat.FILE_ATTRIBUTE_REPARSE_POINT:
+ raise ValueError("A backup store contains a symlink or reparse point; review its external data before updating")
+ if not stat.S_ISREG(info.st_mode) and not stat.S_ISDIR(info.st_mode):
+ raise ValueError("A backup store contains a special file; stop its owner before updating")
+ if path.resolve() != path:
+ raise ValueError("A backup store has a redirected parent path; review its data location before updating")
+ kind = "directory" if stat.S_ISDIR(info.st_mode) else "file"
+ return _Entry(str(path), kind, info.st_size if kind == "file" else 0, stat.S_IMODE(info.st_mode),
+ info.st_mtime_ns, info.st_ctime_ns, info.st_dev, info.st_ino)
+
+
+def _inventory(sources: tuple[BackupSource, ...]) -> list[_Entry]:
+ entries: dict[str, _Entry] = {}
+ pending = [Path(source.path) for source in sources]
+ total = 0
+ while pending:
+ path = pending.pop()
+ if str(path) in entries:
+ continue
+ item = _entry(path)
+ entries[item.path] = item
+ total += item.size
+ if len(entries) > _MAX_ENTRIES or total > _MAX_BYTES:
+ raise ValueError("The managed backup exceeds 100,000 entries or 10 GiB; use an explicit maintenance backup")
+ if item.kind == "directory":
+ with os.scandir(path) as children:
+ for child in children:
+ pending.append(Path(child.path))
+ if len(pending) + len(entries) > _MAX_ENTRIES:
+ raise ValueError("The managed backup has too many entries; use an explicit maintenance backup")
+ return sorted(entries.values(), key=lambda entry: entry.path)
+
+
+def _sources_digest(sources: tuple[BackupSource, ...]) -> str:
+ return hashlib.sha256(json.dumps([asdict(source) for source in sources], sort_keys=True).encode()).hexdigest()
+
+
+def _inventory_digest(entries: list[_Entry]) -> str:
+ return hashlib.sha256(json.dumps([asdict(entry) for entry in entries], sort_keys=True).encode()).hexdigest()
+
+
+def _file_digest(path: Path) -> str:
+ with path.open("rb") as stream:
+ return hashlib.file_digest(stream, "sha256").hexdigest()
+
+
+def current_file_hashes(sources: tuple[BackupSource, ...]) -> dict[str, str]:
+ """Compare user contents with a backup using the same bounded path policy."""
+ entries = _inventory(sources)
+ result = {item.path: _file_digest(Path(item.path)) for item in entries if item.kind == "file"}
+ if _inventory(sources) != entries:
+ raise ValueError("User data changed during recovery verification")
+ return result
+
+
+def verify_backup(directory: Path, sources: tuple[BackupSource, ...], request_sha256: str, *, unchanged: bool = False) -> Path:
+ """Verify the original snapshot; before first mutation, require unchanged data."""
+ root = directory / "backup"
+ receipt, archive = root / "receipt.json", root / "data.zip"
+ if root.is_symlink() or receipt.is_symlink() or receipt.stat().st_size > 16 * 1024:
+ raise ValueError("Invalid pre-update backup receipt")
+ raw: object = json.loads(receipt.read_bytes())
+ if not isinstance(raw, dict):
+ raise ValueError("Invalid pre-update backup receipt")
+ record = cast(dict[str, object], raw)
+ if (record.get("schema_version") != 1 or record.get("request_sha256") != request_sha256 or
+ record.get("sources_sha256") != _sources_digest(sources)):
+ raise ValueError("The pre-update backup belongs to a different update or data scope")
+ info = archive.lstat()
+ if not stat.S_ISREG(info.st_mode) or archive.is_symlink() or info.st_size != record.get("archive_size"):
+ raise ValueError("The original pre-update backup is missing or changed; do not replace it with current data")
+ if _file_digest(archive) != record.get("archive_sha256"):
+ raise ValueError("The original pre-update backup checksum changed; installation is blocked")
+ if unchanged and _inventory_digest(_inventory(sources)) != record.get("inventory_sha256"):
+ raise ValueError("Data changed after backup but before installation; prepare a new update plan and preserve this backup")
+ return archive
+
+
+def ensure_backup(directory: Path, sources: tuple[BackupSource, ...], request_sha256: str, *, mutated: bool) -> Path:
+ """Commit one complete backup, or retain it unchanged across exact-job retries."""
+ final = directory / "backup"
+ if final.exists() or final.is_symlink():
+ return verify_backup(directory, sources, request_sha256, unchanged=not mutated)
+ if mutated:
+ raise ValueError("The original pre-update backup is missing; repair cannot snapshot already changed data")
+ for source in sources:
+ if directory.resolve().is_relative_to(Path(source.path)):
+ raise ValueError("Backup scope includes the update job itself")
+ entries = _inventory(sources)
+ total = sum(item.size for item in entries)
+ if shutil.disk_usage(directory).free < total + 16 * 1024**2 + len(entries) * 1024:
+ raise ValueError("Not enough space for the required pre-update backup; no packages were changed")
+ # A crash leaves a private incomplete attempt, never a plausible completed
+ # backup. A retry uses a new attempt; no original recovery material is deleted.
+ staging = Path(tempfile.mkdtemp(prefix=".backup-", dir=directory))
+ archive = staging / "data.zip"
+ records: list[dict[str, object]] = []
+ with archive.open("xb") as output:
+ os.chmod(archive, 0o600)
+ with ZipFile(output, "w", compression=ZIP_STORED, allowZip64=True) as bundle:
+ for index, item in enumerate(entries):
+ record: dict[str, object] = {**asdict(item)}
+ if item.kind == "file":
+ path = Path(item.path)
+ if _entry(path) != item:
+ raise ValueError("Data changed while preparing its backup; stop writers and retry")
+ flags = (os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)
+ | getattr(os, "O_BINARY", 0))
+ with os.fdopen(os.open(path, flags), "rb") as source:
+ opened = os.fstat(source.fileno())
+ if not stat.S_ISREG(opened.st_mode) or (opened.st_dev, opened.st_ino) != (item.device, item.inode):
+ raise ValueError("A backup file was replaced while opening it")
+ name, digest, copied = f"files/{index}", hashlib.sha256(), 0
+ with bundle.open(name, "w", force_zip64=True) as target:
+ while chunk := source.read(1024 * 1024):
+ copied += len(chunk)
+ if copied > item.size:
+ raise ValueError("Data grew during backup; stop writers and retry")
+ digest.update(chunk)
+ target.write(chunk)
+ if copied != item.size or _entry(path) != item:
+ raise ValueError("Data changed during backup; stop writers and retry")
+ record.update(member=name, sha256=digest.hexdigest())
+ records.append(record)
+ if _inventory(sources) != entries:
+ raise ValueError("Data changed during backup; stop writers and retry")
+ bundle.writestr("manifest.json", json.dumps({
+ "schema_version": 1, "scope": "named nanobot stores from recorded gateway profiles",
+ "excluded": ["arbitrary project files", "installed integration binaries and caches", "external services and custom stores"],
+ "sources": [asdict(s) for s in sources], "entries": records,
+ }, separators=(",", ":")))
+ output.flush()
+ os.fsync(output.fileno())
+ record = {"schema_version": 1, "request_sha256": request_sha256, "sources_sha256": _sources_digest(sources),
+ "inventory_sha256": _inventory_digest(entries),
+ "archive_size": archive.stat().st_size, "archive_sha256": _file_digest(archive),
+ "entries": len(entries), "source_bytes": total, "created_at": int(time.time())}
+ atomic_write_lines(staging / "receipt.json", [json.dumps(record, sort_keys=True)])
+ (staging / "receipt.json").chmod(0o600)
+ os.rename(staging, final)
+ # Publish the directory durably; Windows may not permit directory fsync.
+ with suppress(PermissionError):
+ descriptor = os.open(directory, os.O_RDONLY)
+ try:
+ try:
+ os.fsync(descriptor)
+ except OSError as exc:
+ if exc.errno != errno.EINVAL:
+ raise
+ finally:
+ os.close(descriptor)
+ return final / "data.zip"
diff --git a/nanobot/update_channel.py b/nanobot/update_channel.py
new file mode 100644
index 000000000..53decdefa
--- /dev/null
+++ b/nanobot/update_channel.py
@@ -0,0 +1,48 @@
+"""Installation-owned update preference, separate from versions and consent."""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Literal
+
+from pydantic import Field
+
+from nanobot.installation_lock import installation_state_dir
+from nanobot.releases import Channel, ReleaseRecord
+from nanobot.utils.atomic_file import atomic_write_lines, read_atomic_bytes
+
+
+class UpdateChannel(ReleaseRecord):
+ schema_version: Literal[1] = 1
+ channel: Channel = "stable"
+ revision: int = Field(default=0, ge=0)
+
+
+class UpdateChannelRequest(ReleaseRecord):
+ channel: Channel
+ revision: int = Field(ge=0)
+
+
+def read_update_channel(environment: str | Path | None = None) -> UpdateChannel:
+ path = installation_state_dir(environment) / "channel.json"
+ try:
+ if path.is_symlink():
+ raise ValueError("Invalid update channel record")
+ return UpdateChannel.model_validate_json(read_atomic_bytes(path, max_bytes=4097))
+ except FileNotFoundError:
+ # Existing installations remain on Stable. A dev version is not consent.
+ return UpdateChannel()
+
+
+def write_update_channel(selection: UpdateChannel, environment: str | Path | None = None) -> None:
+ """Caller holds channel.lock and has checked the active job lifecycle."""
+ root = installation_state_dir(environment)
+ root.mkdir(parents=True, exist_ok=True, mode=0o700)
+ path = root / "channel.json"
+ atomic_write_lines(path, [selection.model_dump_json()])
+ path.chmod(0o600)
+
+
+def validate_channel_revision(revision: int | None, environment: str) -> None:
+ if (revision or 0) != read_update_channel(environment).revision:
+ raise ValueError("Update channel changed; review a new update before confirming")
diff --git a/nanobot/update_contract.json b/nanobot/update_contract.json
new file mode 100644
index 000000000..36273eb2c
--- /dev/null
+++ b/nanobot/update_contract.json
@@ -0,0 +1,4 @@
+{
+ "schema_version": 1,
+ "handoff_protocols": [1]
+}
diff --git a/nanobot/update_fallback.py b/nanobot/update_fallback.py
new file mode 100644
index 000000000..b350c3e05
--- /dev/null
+++ b/nanobot/update_fallback.py
@@ -0,0 +1,375 @@
+"""Frozen service recovery for one explicitly confirmed update.
+
+Keep this module stdlib-only. A program snapshot is not a data backup: recovery
+never restores user stores. Same-filesystem renames retain both program generations.
+The caller must hold exclusive installation/data leases before snapshot or restore.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import os
+import re
+import shutil
+import stat
+import subprocess
+import time
+from contextlib import suppress
+from importlib.metadata import distributions
+from pathlib import Path
+from typing import TYPE_CHECKING
+from zipfile import ZipFile
+
+from nanobot.installation_lock import (
+ InstallationBusyError,
+ file_access,
+ installation_access,
+ installation_state_dir,
+ pending_update_path,
+)
+
+if TYPE_CHECKING:
+ from nanobot.update_worker import EnvironmentSnapshot, WorkerSpec
+
+
+def _digest(path: Path) -> str:
+ with path.open("rb") as stream:
+ return hashlib.file_digest(stream, "sha256").hexdigest()
+
+
+def _sync_directory(path: Path) -> None:
+ # Windows does not expose POSIX directory fsync through this interface.
+ if os.name != "nt":
+ descriptor = os.open(path, os.O_RDONLY)
+ try:
+ os.fsync(descriptor)
+ finally:
+ os.close(descriptor)
+
+
+def _inspect_metadata(spec: WorkerSpec) -> EnvironmentSnapshot:
+ """Read ownership without executing a possibly broken candidate's site hooks."""
+ from nanobot.update_worker import EnvironmentSnapshot
+
+ root = Path(spec.baseline.environment)
+ sites = [root / "Lib/site-packages"] if os.name == "nt" else list((root / "lib").glob("python*/site-packages"))
+ if len(sites) != 1 or not sites[0].is_dir() or sites[0].is_symlink():
+ raise ValueError("The selected installation's package location changed")
+ items: dict[str, str] = {}
+ versions: dict[str, str] = {}
+ records: dict[str, str] = {}
+ for distribution in distributions(path=[str(sites[0])]):
+ raw_name, version = distribution.metadata["Name"], distribution.version
+ if not raw_name or not version:
+ # Interrupted pip transactions can leave an incomplete dist-info.
+ # Missing targets are allowed by check_environment(repairing=True);
+ # missing unrelated distributions still fail its baseline comparison.
+ continue
+ name = re.sub(r"[-_.]+", "-", raw_name).lower()
+ payload = "\n".join(distribution.read_text(f) or "" for f in ("METADATA", "RECORD", "direct_url.json"))
+ items[name] = hashlib.sha256(payload.encode()).hexdigest()
+ versions[name] = version
+ if name == "nanobot-ai":
+ records = {key: hashlib.sha256((distribution.read_text(key) or "").encode()).hexdigest()
+ for key in ("RECORD", "direct_url.json")}
+ return EnvironmentSnapshot(str(root), spec.baseline.python, spec.baseline.base_python,
+ _digest(root / "pyvenv.cfg"), items, versions, versions.get("nanobot-ai", ""), records,
+ _digest(root / "uv-receipt.toml") if (root / "uv-receipt.toml").exists() else None,
+ _digest(root / "nanobot-install.json") if (root / "nanobot-install.json").exists() else None)
+
+
+def _tree(root: Path) -> dict[str, tuple[str, str, int]]:
+ """Hash files and preserve symlinks without following them outside the venv."""
+ result: dict[str, tuple[str, str, int]] = {}
+ for directory, folders, files in os.walk(root, followlinks=False):
+ for name in [*folders, *files]:
+ path = Path(directory) / name
+ info = path.lstat()
+ key = str(path.relative_to(root))
+ mode = stat.S_IMODE(info.st_mode)
+ if path.is_symlink():
+ result[key] = ("link", os.readlink(path), mode)
+ elif getattr(info, "st_file_attributes", 0) & stat.FILE_ATTRIBUTE_REPARSE_POINT:
+ raise ValueError("The program environment contains a redirected directory")
+ elif stat.S_ISDIR(info.st_mode):
+ result[key] = ("directory", "", mode)
+ elif stat.S_ISREG(info.st_mode):
+ result[key] = ("file", _digest(path), mode)
+ else:
+ raise ValueError("The program environment contains a special file; it cannot be preserved safely")
+ return result
+
+
+def _tree_digest(root: Path) -> str:
+ return hashlib.sha256(json.dumps(_tree(root), sort_keys=True).encode()).hexdigest()
+
+
+def _paths(spec: WorkerSpec) -> tuple[Path, Path, Path]:
+ environment = Path(spec.baseline.environment)
+ # No user-supplied restore destination or recursive deletion. The original
+ # venv path remains its identity (and keeps console-script shebangs valid).
+ if environment.is_symlink() or environment.parent == environment or environment == Path.home():
+ raise ValueError("Invalid program restoration destination")
+ return (environment, environment.with_name(f".nanobot-original-{spec.plan_id}"),
+ environment.with_name(f".nanobot-failed-{spec.plan_id}"))
+
+
+def _copy_program_file(source: str, destination: str) -> str:
+ shutil.copyfile(source, destination)
+ # Windows fsync requires a writable handle. Open it before copystat restores
+ # a package file's read-only flag; keep that handle through metadata sync.
+ with Path(destination).open("rb+") as stream:
+ shutil.copystat(source, destination)
+ os.fsync(stream.fileno())
+ return destination
+
+
+def preserve_program(directory: Path, spec: WorkerSpec) -> None:
+ from nanobot.update_worker import read_record, write_record
+
+ if not spec.automatic_recovery or spec.uv is not None:
+ return
+ environment, original, _ = _paths(spec)
+ receipt = directory / "program-backup.json"
+ if receipt.exists():
+ record = read_record(receipt)
+ if record.get("request_sha256") != _digest(directory / "request.json") or record.get("sha256") != _tree_digest(original):
+ raise ValueError("The original program snapshot changed")
+ return
+ if original.exists() or original.is_symlink():
+ raise ValueError("An incomplete program snapshot already exists; keep it for diagnosis")
+ # Refuse nested data: a program-only restoration must never move user data.
+ if any(Path(source.path).is_relative_to(environment) and Path(source.path) not in {
+ environment / "pyvenv.cfg", environment / "nanobot-install.json",
+ } for source in spec.backup_sources):
+ raise ValueError("User data is inside the program environment; automatic program restoration is unsafe")
+ size = sum(path.stat().st_size for path in environment.rglob("*") if path.is_file() and not path.is_symlink())
+ if shutil.disk_usage(environment.parent).free < size + 32 * 1024**2:
+ raise ValueError("Not enough space to preserve the original program; no packages were changed")
+ before = _tree_digest(environment)
+ shutil.copytree(environment, original, symlinks=True, copy_function=_copy_program_file)
+ original.chmod(0o700)
+ # File copies are durable; flush directory entries before the receipt.
+ for root, _, _ in os.walk(original, topdown=False, followlinks=False):
+ _sync_directory(Path(root))
+ if _tree_digest(original) != before or _tree_digest(environment) != before:
+ raise ValueError("The program changed during its snapshot; no packages were changed")
+ write_record(receipt, {"plan_id": spec.plan_id, "request_sha256": _digest(directory / "request.json"), "sha256": before})
+ _sync_directory(original.parent)
+
+
+def require_unchanged_user_data(directory: Path, spec: WorkerSpec) -> None:
+ """Compare contents, not mtimes; never write a byte to a user store."""
+ from nanobot.update_backup import BackupSource, current_file_hashes, verify_backup
+
+ digest = _digest(directory / "request.json")
+ archive = verify_backup(directory, spec.backup_sources, digest)
+ environment = Path(spec.baseline.environment)
+ profiles = installation_state_dir(spec.baseline.environment) / "profiles"
+ sources = [Path(source.path) for source in spec.backup_sources
+ if not Path(source.path).is_relative_to(environment) and not Path(source.path).is_relative_to(profiles)]
+ with ZipFile(archive) as bundle:
+ manifest = json.loads(bundle.read("manifest.json"))
+ expected = {item["path"]: item["sha256"] for item in manifest["entries"]
+ if item["kind"] == "file" and any(Path(item["path"]).is_relative_to(root) for root in sources)}
+ actual = current_file_hashes(tuple(BackupSource(str(source)) for source in sources))
+ if actual != expected:
+ raise ValueError("User data changed after installation; keep the current program and original backup")
+
+
+def restore_program(directory: Path, spec: WorkerSpec) -> None:
+ from nanobot.update_worker import read_record, write_record
+
+ if spec.uv is not None:
+ raise ValueError("An external package manager owns this program; automatic downgrade is unavailable")
+ environment, original, failed = _paths(spec)
+ receipt = read_record(directory / "program-backup.json")
+ if receipt.get("plan_id") != spec.plan_id or receipt.get("request_sha256") != _digest(directory / "request.json"):
+ raise ValueError("The original program belongs to a different update")
+ if not original.exists():
+ # A crash after the second rename is a completed restoration, not a
+ # reason to snapshot or replace the environment again.
+ if failed.is_dir() and _tree_digest(environment) == receipt.get("sha256"):
+ write_record(directory / "restoration.json", {"plan_id": spec.plan_id, "state": "restarting"})
+ return
+ raise ValueError("The original program snapshot is unavailable")
+ if original.is_symlink() or _tree_digest(original) != receipt.get("sha256"):
+ raise ValueError("The original program snapshot changed")
+ write_record(directory / "restoration.json", {"plan_id": spec.plan_id, "state": "restoring"})
+ if environment.exists():
+ if failed.exists() or failed.is_symlink():
+ raise ValueError("A failed program generation already exists; refusing to replace it")
+ os.rename(environment, failed)
+ _sync_directory(environment.parent)
+ os.rename(original, environment)
+ _sync_directory(environment.parent)
+ # Journal publication follows renames. Both generations remain recoverable.
+ write_record(directory / "restoration.json", {"plan_id": spec.plan_id, "state": "restarting"})
+
+
+def _shutdown_committed(spec: WorkerSpec) -> bool:
+ from nanobot.update_worker import read_record
+
+ try:
+ stop = read_record(installation_state_dir(spec.baseline.environment) / "stop.json")
+ except FileNotFoundError:
+ return False
+ return stop.get("plan_id") == spec.plan_id and stop.get("phase") in {"commit", "stopped"}
+
+
+def restore_service(directory: Path, *, confirmation_id: str | None = None) -> None:
+ from nanobot.update_worker import (
+ JobStatus,
+ Phase,
+ WorkerSpec,
+ check_approval,
+ check_environment,
+ read_record,
+ require_pending_owner,
+ restart_runtime,
+ write_record,
+ )
+
+ spec = WorkerSpec.read(directory)
+ root = installation_state_dir(spec.baseline.environment)
+ with file_access(root / "worker.lock", exclusive=True):
+ status = JobStatus.read(directory)
+ if status.phase in {Phase.SUCCEEDED, Phase.RESTORED, Phase.CANCELLED}:
+ return
+ restoration_path = directory / "restoration.json"
+ if restoration_path.exists():
+ restoration = read_record(restoration_path)
+ if (restoration == {"plan_id": spec.plan_id, "state": "restarting"}
+ and status.phase in {Phase.RESTARTING, Phase.ACTIVATING, Phase.FINALIZING, Phase.RESTART_FAILED}):
+ # Program restoration already committed. Resume only its runtime
+ # handoff, including cleanup after old-version activation.
+ if confirmation_id is not None:
+ check_approval(directory, spec, handoff=True, confirmation_id=confirmation_id, check_expiry=False)
+ restart_runtime(directory, spec)
+ return
+ if restoration not in ({"plan_id": spec.plan_id, "state": "restoring"},
+ {"plan_id": spec.plan_id, "state": "restarting"}):
+ raise ValueError("Invalid original-program restoration journal")
+ # Durable activation can mean the new runtime has accepted tasks. Never
+ # downgrade or roll data back after that point.
+ if (directory / "activation.json").exists():
+ raise ValueError("The new runtime was activated; only same-version repair is safe")
+ check_approval(directory, spec, handoff=True, confirmation_id=confirmation_id, check_expiry=False)
+ if not _shutdown_committed(spec):
+ if not status.mutation_started:
+ status.advance(directory, Phase.HANDOFF_FAILED, "Shutdown was not committed; review the update again", mutation_started=False)
+ return # A refused preflight left the original service running.
+ with file_access(root / "handoff-child.lock", exclusive=True):
+ pass
+ restoring = restoration_path.exists()
+ with spec.mutation_access() as (_, data):
+ require_pending_owner(spec)
+ if not restoring or not status.mutation_started:
+ check_environment(spec, repairing=status.mutation_started, current=_inspect_metadata(spec))
+ if status.mutation_started:
+ require_unchanged_user_data(directory, spec)
+ restore_program(directory, spec)
+ else:
+ write_record(directory / "restoration.json", {"plan_id": spec.plan_id, "state": "restarting"})
+ data.reserve()
+ pending = pending_update_path(spec.baseline.environment)
+ pending.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
+ write_record(pending, {
+ "schema_version": 2, "job_id": spec.plan_id, "version": spec.baseline.app_version,
+ })
+ status.advance(directory, Phase.RESTARTING, "Restoring the original service without changing user data")
+ restart_runtime(directory, spec)
+
+
+def supervise(directory: Path, arguments: list[str]) -> None:
+ """One child execution, one exact-target repair, then safe program restoration."""
+ from nanobot.update_worker import (
+ JobStatus,
+ Phase,
+ WorkerSpec,
+ check_approval,
+ read_record,
+ write_record,
+ )
+
+ spec = WorkerSpec.read(directory)
+ if not spec.automatic_recovery or not spec.restart_profiles:
+ raise ValueError("This job did not prepare automatic service recovery")
+ with file_access(installation_state_dir(spec.baseline.environment) / "supervisor.lock", exclusive=True):
+ journal = directory / "supervision.json"
+ confirmation = arguments[2] if len(arguments) == 3 and arguments[0] == "--confirmed-handoff" else None
+ if journal.exists():
+ previous = read_record(journal)
+ if confirmation is None or previous.get("confirmation_id") == confirmation:
+ return # Duplicate/delayed launch is not another recovery budget.
+ # Validate even the first journal publication: a delayed launcher may
+ # have been replaced before any supervisor acquired this lease.
+ if confirmation is not None:
+ check_approval(directory, spec, handoff=True, confirmation_id=confirmation)
+ write_record(journal, {"plan_id": spec.plan_id, "confirmation_id": confirmation, "started_at": int(time.time())})
+ command = [spec.baseline.base_python, "-I", "-S", str(directory / "worker.pyz")]
+ try:
+ subprocess.run([*command, *arguments], check=False, timeout=1800)
+ except subprocess.TimeoutExpired:
+ pass # Orphan children still own leases; recovery cannot race them.
+ status = JobStatus.read(directory)
+ if status.phase in {Phase.SUCCEEDED, Phase.RESTORED, Phase.CANCELLED}:
+ if status.phase == Phase.SUCCEEDED:
+ _discard_program_snapshot(directory, spec)
+ return
+ if (status.phase == Phase.HANDOFF_FAILED and not status.mutation_started
+ and not _shutdown_committed(spec)):
+ # A busy gateway correctly refused shutdown and retains its runtime
+ # lease. Waiting for that lease would hide the refusal for five minutes.
+ return
+ if confirmation is not None:
+ check_approval(directory, spec, handoff=True, confirmation_id=confirmation, check_expiry=False)
+ # Retry only admitted work. No second stop request, download or release
+ # resolution. Lease-owning orphan children must finish before recovery.
+ deadline = time.monotonic() + 300
+ while time.monotonic() < deadline and not (directory / "activation.json").exists():
+ try:
+ with (installation_access(updating=True, environment=spec.baseline.environment),
+ file_access(installation_state_dir(spec.baseline.environment) / "handoff-child.lock", exclusive=True)):
+ break
+ except (InstallationBusyError, BlockingIOError):
+ time.sleep(0.2)
+ if (directory / "approval.json").exists() and not (directory / "restoration.json").exists():
+ try:
+ subprocess.run([*command, "--recover", str(directory)], check=False, timeout=1800)
+ except subprocess.TimeoutExpired:
+ pass
+ if JobStatus.read(directory).phase == Phase.SUCCEEDED:
+ _discard_program_snapshot(directory, spec)
+ return
+ try:
+ try:
+ restore_service(directory, confirmation_id=confirmation)
+ except OSError:
+ # A transient filesystem error between the two renames must
+ # not leave an absent venv. Replay the journal once, retaining
+ # the same snapshot, ownership checks and recovery budget.
+ restore_service(directory, confirmation_id=confirmation)
+ except (OSError, ValueError, RuntimeError, subprocess.SubprocessError):
+ # Keep fences, snapshots and the exact failure state. A hardware,
+ # ownership or changed-data failure is not permission to discard data.
+ status = JobStatus.read(directory)
+ status.advance(directory, status.phase,
+ "Automatic recovery could not safely finish; original backup and program generations are retained")
+ write_record(journal, {"plan_id": spec.plan_id, "confirmation_id": confirmation, "state": "needs_attention"})
+
+
+def _discard_program_snapshot(directory: Path, spec: WorkerSpec) -> None:
+ """Remove only this successful job's redundant program copy, never its data backup."""
+ from nanobot.update_worker import read_record
+
+ _, original, _ = _paths(spec)
+ # Cleanup is not part of gateway readiness. Failed cleanup retains evidence
+ # and must not turn an already usable update into another recovery attempt.
+ with suppress(OSError, ValueError):
+ record = read_record(directory / "program-backup.json")
+ if (not original.is_symlink() and record.get("plan_id") == spec.plan_id
+ and original.is_dir() and _tree_digest(original) == record.get("sha256")):
+ shutil.rmtree(original)
+ _sync_directory(original.parent)
diff --git a/nanobot/update_guidance.py b/nanobot/update_guidance.py
new file mode 100644
index 000000000..9f43a1747
--- /dev/null
+++ b/nanobot/update_guidance.py
@@ -0,0 +1,108 @@
+"""Read-only, installation-bound instructions; never an alternative executor."""
+
+from __future__ import annotations
+
+import os
+import platform
+import shlex
+import shutil
+from pathlib import Path
+from typing import TYPE_CHECKING, Literal
+
+from packaging.version import Version
+
+from nanobot.installation_receipt import RECEIPT_NAME
+from nanobot.releases import ReleaseRecord
+
+if TYPE_CHECKING:
+ from nanobot.update_plan import InstallationSnapshot
+
+Method = Literal["managed", "uv", "pipx", "pip", "source", "container", "system"]
+
+
+def installation_method(installation: InstallationSnapshot) -> Method:
+ if installation.owner == "venv":
+ return "managed" if RECEIPT_NAME in installation.records else "pip"
+ return installation.owner
+
+
+def shell_command(arguments: list[str], *, windows: bool, environment: tuple[str, str] | None = None) -> str:
+ """Bind a manager root without changing the user's persistent shell settings."""
+ if not windows:
+ return shlex.join(["env", "=".join(environment), *arguments] if environment else arguments)
+ def quote(value: str) -> str:
+ return "'" + value.replace("'", "''") + "'"
+ command = "& " + " ".join(quote(value) for value in arguments)
+ if environment:
+ name, value = environment
+ command = (f"& {{ $nanobotPrevious = $env:{name}\n"
+ f" try {{ $env:{name} = {quote(value)}; {command} }}\n"
+ f" finally {{ $env:{name} = $nanobotPrevious }}\n}}")
+ return command
+
+
+class UpdateGuide(ReleaseRecord):
+ method: Method
+ host: str
+ environment: str
+ shell: Literal["sh", "powershell"]
+ inspect_command: str | None = None
+ update_command: str | None = None
+ verify_command: str | None = None
+ reason: Literal["registry", "preview", "policy", "extras", "manager", "source", "container", "system", "review", "restart"]
+
+
+def update_guide(installation: InstallationSnapshot, target_version: str, *,
+ extras: list[str] | None, current: bool = True) -> UpdateGuide:
+ """Only offer commands whose owner and environment have been identified.
+
+ uv retains recorded constraints and settings. Generic pipx upgrades are only
+ offered without recorded constraints or pip options. Neither promises our feed's
+ exact target; the UI explains this and requires checking the running version.
+ """
+ method = installation_method(installation)
+ windows = os.name == "nt"
+ guide = UpdateGuide(method=method, host=platform.node(), environment=installation.environment,
+ shell="powershell" if windows else "sh", reason="review")
+ if not current or Version(target_version) < Version(installation.installed_version) or any(ord(char) < 32 for value in (installation.python, installation.environment,
+ installation.running_package) for char in value):
+ return guide
+ guide = guide.model_copy(update={"verify_command": shell_command([installation.python, "-I", "-m", "nanobot", "--version"], windows=windows)})
+ if Version(target_version) == Version(installation.installed_version) and method != "container":
+ return guide.model_copy(update={"reason": "restart"})
+ if method == "container":
+ # Container paths/hostname are not the deployment host or service name.
+ return guide.model_copy(update={"reason": "container", "verify_command": None})
+ elif method == "source":
+ root = str(Path(installation.running_package).parent.parent)
+ return guide.model_copy(update={"reason": "source", "inspect_command": shell_command(["git", "-C", root, "status", "--short", "--branch"], windows=windows)})
+ elif method == "system":
+ return guide.model_copy(update={"reason": "system"})
+ elif method in {"uv", "pipx"}:
+ directory = Path(installation.environment)
+ manager = shutil.which(method)
+ policy = installation.manager
+ if not manager or (method == "uv" and directory.name != "nanobot-ai") or (method == "pipx" and (directory.parent.name != "venvs" or not directory.name.startswith("nanobot-ai"))):
+ return guide.model_copy(update={"reason": "manager"})
+ root = ("UV_TOOL_DIR", str(directory.parent)) if method == "uv" else ("PIPX_HOME", str(directory.parent.parent))
+ prefix = [manager, "tool"] if method == "uv" else [manager]
+ guide = guide.model_copy(update={"inspect_command": shell_command([*prefix, "list"], windows=windows, environment=root)})
+ if policy is None or policy.source != "registry" or policy.restriction(target_version):
+ return guide.model_copy(update={"reason": "policy"})
+ elif Version(target_version).is_prerelease:
+ return guide.model_copy(update={"reason": "preview"})
+ else:
+ return guide.model_copy(update={"reason": "registry", "update_command": shell_command([*prefix, "upgrade", directory.name], windows=windows, environment=root)})
+ elif Version(target_version).is_prerelease:
+ return guide.model_copy(update={"reason": "preview"})
+ elif extras is None:
+ # A venv populated with `uv pip` need not contain pip itself. Inspect
+ # metadata with the standard library, without guessing its original extras.
+ inspect = [installation.python, "-I", "-c",
+ "import importlib.metadata,sys; d=importlib.metadata.distribution(sys.argv[1]); "
+ "print(d.metadata[sys.argv[2]], d.version); print(d.locate_file(sys.argv[3]))",
+ "nanobot-ai", "Name", "."]
+ return guide.model_copy(update={"reason": "extras", "inspect_command": shell_command(inspect, windows=windows)})
+ else:
+ requirement = "nanobot-ai" + (f"[{','.join(extras)}]" if extras else "") + f"=={target_version}"
+ return guide.model_copy(update={"reason": "registry", "update_command": shell_command([installation.python, "-I", "-m", "pip", "install", "--upgrade", requirement], windows=windows)})
diff --git a/nanobot/update_handoff.py b/nanobot/update_handoff.py
new file mode 100644
index 000000000..f00de1ed5
--- /dev/null
+++ b/nanobot/update_handoff.py
@@ -0,0 +1,57 @@
+"""Old-runtime preflight for the immutable, detached update owner.
+
+Entered by the frozen worker only after taking this installation's shared lease.
+This child must exit before the base-Python parent approves package mutation.
+No client route calls it, and it never launches an installer itself.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from pathlib import Path
+
+from nanobot.data_access import require_no_pending_data_update
+from nanobot.installation_lock import installation_state_dir
+from nanobot.release_feed import ReleaseFeed
+from nanobot.update_plan import UpdatePlan
+from nanobot.update_stop import stop_reviewed_gateways
+from nanobot.update_worker import (
+ JobStatus,
+ Phase,
+ WorkerSpec,
+ check_environment,
+ current_environment,
+)
+
+
+async def _prepare(directory: Path) -> None:
+ spec = WorkerSpec.read(directory)
+ plan = UpdatePlan.model_validate_json((directory / "plan.json").read_bytes())
+ status = JobStatus.read(directory)
+ if status.phase != Phase.CHECKING or status.mutation_started:
+ raise ValueError("Shutdown preflight requires an unchanged prepared job")
+ try:
+ plan.validate_for(plan.installation)
+ # This process already owns the old runtime's lease, including startup
+ # and atexit. Do not create an unprotected nested interpreter here.
+ check_environment(spec, repairing=False, current=current_environment(uv=spec.uv is not None))
+ async with ReleaseFeed(installation_state_dir(spec.baseline.environment) / "releases") as feed:
+ await feed.revalidate(plan.target)
+ plan.validate_for(plan.installation)
+ require_no_pending_data_update()
+ status.advance(directory, Phase.STOPPING, "Waiting for the reviewed idle gateways to exit normally", mutation_started=False)
+ await stop_reviewed_gateways(directory)
+ except Exception:
+ current = JobStatus.read(directory)
+ message = (
+ "Release or installation revalidation failed; gateway shutdown was not requested"
+ if current.phase == Phase.CHECKING else
+ "Gateway shutdown did not complete; review the saved shutdown state before retrying"
+ )
+ status.advance(directory, Phase.HANDOFF_FAILED, message, mutation_started=False)
+ raise
+
+
+def prepare_handoff(directory: Path) -> None:
+ """Revalidate and cooperatively stop; installation remains unapproved."""
+ asyncio.run(_prepare(directory))
diff --git a/nanobot/update_jobs.py b/nanobot/update_jobs.py
new file mode 100644
index 000000000..2580861d2
--- /dev/null
+++ b/nanobot/update_jobs.py
@@ -0,0 +1,597 @@
+"""Prepare exact offline jobs and hand them to the standalone installer worker.
+
+The gateway controller keeps authenticated staging separate from execution consent.
+The caller owns explicit shutdown/restart selection. A detached worker revalidates,
+stops reviewed idle gateways, backs up data, installs, and restarts selected runtimes.
+Confirmed execution is idempotent; managed installs have bounded detached recovery.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import hashlib
+import os
+import platform
+import shlex
+import shutil
+import subprocess
+import sys
+import tempfile
+import time
+from contextlib import nullcontext
+from email.parser import BytesParser
+from pathlib import Path
+from urllib.parse import unquote, urlsplit
+from uuid import UUID, uuid4
+from zipfile import ZipFile, ZipInfo
+
+from packaging.utils import canonicalize_name, parse_wheel_filename
+from pydantic import BaseModel, ConfigDict, Field
+
+from nanobot.data_access import data_access
+from nanobot.installation_lock import (
+ file_access,
+ installation_access,
+ installation_id,
+ installation_state_dir,
+)
+from nanobot.installation_receipt import RECEIPT_NAME
+from nanobot.release_feed import ReleaseFeed
+from nanobot.releases import Channel, ReleaseRecord, Sha256
+from nanobot.update_backup import BackupSource, unique_sources
+from nanobot.update_plan import UpdatePlan
+from nanobot.update_process import PreparationProcess
+from nanobot.update_profiles import require_stopped_profiles, validate_profiles
+from nanobot.update_uv import UVPreparation, prepare_uv
+from nanobot.update_worker import (
+ ExecutionConfirmation,
+ JobStatus,
+ Phase,
+ StagedWheel,
+ WorkerSpec,
+ check_environment,
+ inspect_environment,
+ inspect_job_environment,
+ read_record,
+ verify_target_handoff,
+ write_record,
+)
+from nanobot.utils.atomic_file import atomic_write_lines
+from nanobot.utils.cancellation import shield_and_drain
+
+
+class UpdateJobNotFoundError(FileNotFoundError):
+ """No saved preparation or execution status exists for this installation."""
+
+
+class UpdateJobView(ReleaseRecord):
+ """Last durable facts only: not proof of a live worker or authority to retry."""
+
+ id: str
+ installation_id: str
+ host: str
+ previous_version: str
+ target_version: str
+ channel: Channel
+ recorded_phase: Phase
+ attempt: int
+ mutation_started: bool
+ updated_at: int
+ execution_confirmation_id: str | None = None
+ running_version: str = ""
+ recovery_command: str = ""
+ recovery_active: bool = False
+ service_restored: bool = False
+ automatic_recovery: bool = False
+
+
+def _recovery_command(plan_id: str) -> str:
+ # The installer accepts py or an explicit Python path. Neither guarantees
+ # python/python3 is on PATH after failure. Use the base interpreter outside
+ # the mutable venv, quoted for the operator's platform shell.
+ python: object = getattr(sys, "_base_executable")
+ if not isinstance(python, str):
+ raise ValueError("Recovery needs a known base Python")
+ # The operator's shell may have a different HOME from the gateway.
+ launcher = str(installation_state_dir().parent / "recover.py")
+ if platform.system() == "Windows":
+ quoted = "'" + python.replace("'", "''") + "'"
+ quoted_launcher = "'" + launcher.replace("'", "''") + "'"
+ return f'& {quoted} -I -S {quoted_launcher} {plan_id} --repair'
+ return f'{shlex.quote(python)} -I -S {shlex.quote(launcher)} {plan_id} --repair'
+
+
+def read_update_job(plan_id: str) -> UpdateJobView:
+ """Read the journal scoped to this environment path, without probing Python.
+
+ No interpreter probe, network request or runtime lease is required. A failed
+ installation and an active writer must not hide its last recorded state.
+ This does not validate continued release eligibility, worker liveness or
+ that an environment reinstalled at this path is still the reviewed one.
+ """
+ UpdatePlan.canonical_id(plan_id)
+ directory = installation_state_dir() / "jobs" / plan_id
+ if directory.is_symlink():
+ raise ValueError("Invalid update job directory")
+ try:
+ plan = UpdatePlan.model_validate(read_record(directory / "plan.json"))
+ status = JobStatus.read(directory)
+ except FileNotFoundError as exc:
+ raise UpdateJobNotFoundError("No saved update job is available") from exc
+ if plan.id != plan_id or plan.installation.installation_id != installation_id():
+ raise ValueError("Update job belongs to a different installation or plan")
+ confirmation = ExecutionConfirmation.read(directory)
+ # Local diagnostic messages may contain paths or exception details. Clients
+ # receive typed facts and can localize phases, never raw journal messages.
+ from nanobot import __version__
+
+ recovery_active = False
+ supervision = directory / "supervision.json"
+ recovery_failed = False
+ if supervision.exists():
+ record = read_record(supervision)
+ if record.get("plan_id") == plan_id:
+ recovery_failed = (record.get("state") == "needs_attention"
+ and status.phase not in {Phase.SUCCEEDED, Phase.RESTORED, Phase.CANCELLED})
+ try:
+ with file_access(installation_state_dir() / "supervisor.lock", exclusive=True):
+ pass
+ except BlockingIOError:
+ recovery_active = True
+
+ return UpdateJobView(
+ id=plan_id, installation_id=plan.installation.installation_id, host=platform.node(),
+ previous_version=plan.installation.installed_version, target_version=plan.target.version,
+ # Older clients know FAILED and must not display a rolled-back update
+ # as successful. New clients use the additive service result below.
+ channel=plan.channel, recorded_phase=Phase.FAILED if status.phase == Phase.RESTORED or recovery_failed else status.phase,
+ attempt=status.attempt,
+ mutation_started=status.mutation_started, updated_at=status.updated_at,
+ execution_confirmation_id=confirmation.id if confirmation else None,
+ running_version=__version__,
+ recovery_command=_recovery_command(plan_id),
+ recovery_active=recovery_active,
+ service_restored=status.phase == Phase.RESTORED,
+ automatic_recovery=WorkerSpec.recovery_selected(directory),
+ )
+
+
+class _Metadata(BaseModel):
+ name: str
+ version: str
+
+
+class _Hashes(BaseModel):
+ sha256: Sha256
+
+
+class _Archive(BaseModel):
+ hashes: _Hashes
+
+
+class _Download(BaseModel):
+ url: str
+ archive_info: _Archive
+
+
+class _Install(BaseModel):
+ metadata: _Metadata
+ download_info: _Download
+
+
+class _Report(BaseModel):
+ model_config = ConfigDict(strict=True)
+ version: str
+ install: list[_Install] = Field(max_length=500)
+
+
+def _pip(process: PreparationProcess, python: str, *arguments: str) -> None:
+ result = process.run(python, ["-m", "pip", "--disable-pip-version-check", "--no-input", *arguments])
+ if result.returncode:
+ # Index URLs and resolver output may contain credentials. Do not put them
+ # in the durable job or the WebUI response.
+ raise ValueError("Could not prepare the pip transaction; check the installation's package-manager configuration")
+
+
+def _worker_archive(path: Path) -> str:
+ sources = Path(__file__).parent
+ # The frozen worker must not shadow the newly installed application when
+ # handing off to its runtime. Keep only the copied stdlib helpers in this
+ # private namespace; intentional application imports retain `nanobot`.
+ modules = ("update_worker", "update_uv", "update_process", "update_backup", "update_fallback",
+ "update_restart", "data_access", "installation_lock", "utils.atomic_file")
+ with ZipFile(path, "x") as bundle:
+ files = {"__main__.py": b"from _nanobot_update.update_worker import main\nmain()\n",
+ "_nanobot_update/__init__.py": b"", "_nanobot_update/utils/__init__.py": b""}
+ for module in modules:
+ name = module.replace(".", "/") + ".py"
+ source = (sources / name).read_text(encoding="utf-8")
+ for dependency in modules:
+ source = source.replace(f"from nanobot.{dependency} import", f"from _nanobot_update.{dependency} import")
+ files[f"_nanobot_update/{name}"] = source.encode("utf-8")
+ for name, data in files.items():
+ bundle.writestr(ZipInfo(name), data)
+ path.chmod(0o600)
+ return hashlib.sha256(path.read_bytes()).hexdigest()
+
+
+def _stage_app(plan: UpdatePlan, app_wheel: Path, directory: Path) -> StagedWheel:
+ wheels = directory / "wheels"
+ wheels.mkdir(mode=0o700, exist_ok=True)
+ artifact = plan.target.artifact
+ app = StagedWheel(artifact.filename, "nanobot-ai", plan.target.version, artifact.size, artifact.sha256)
+ destination = wheels / artifact.filename
+ if not destination.exists():
+ shutil.copyfile(app_wheel, destination)
+ verified = app.verify(wheels)
+ with ZipFile(verified) as archive:
+ if plan.restart_profiles:
+ verify_target_handoff(archive)
+ metadata = BytesParser().parsebytes(archive.read(f"nanobot_ai-{app.version}.dist-info/METADATA"))
+ available = {canonicalize_name(extra) for extra in metadata.get_all("Provides-Extra", [])}
+ if not set(plan.extras or []).issubset(available):
+ raise ValueError("The target release does not provide all confirmed extras")
+ return app
+
+
+def _prepare_wheels(plan: UpdatePlan, app_wheel: Path, directory: Path,
+ process: PreparationProcess) -> tuple[StagedWheel, ...]:
+ app = _stage_app(plan, app_wheel, directory)
+ wheels = directory / "wheels"
+ records = [app]
+ python = plan.installation.python
+ _pip(process, python, "check")
+ with tempfile.TemporaryDirectory(prefix=".resolve-", dir=directory) as temporary:
+ root = Path(temporary)
+ report_path = root / "report.json"
+ extras = f"[{','.join(plan.extras)}]" if plan.extras else ""
+ _pip(process, python, "install", "--dry-run", "--only-binary=:all:", "--upgrade",
+ "--upgrade-strategy", "only-if-needed", "--report", str(report_path),
+ f"nanobot-ai{extras} @ {app_wheel.as_uri()}")
+ if report_path.stat().st_size > 8 * 1024 * 1024:
+ raise ValueError("Package-manager report exceeds its size limit")
+ report = _Report.model_validate_json(report_path.read_bytes())
+ if report.version != "1":
+ raise ValueError("Unsupported pip report version")
+ requirements: list[str] = []
+ dependencies: list[tuple[str, str, str, str]] = []
+ for item in report.install:
+ name = canonicalize_name(item.metadata.name)
+ if name == "nanobot-ai":
+ if (item.metadata.version, item.download_info.archive_info.hashes.sha256) != (app.version, app.sha256):
+ raise ValueError("Resolver changed the approved nanobot target")
+ continue
+ url = item.download_info.url
+ if any(character.isspace() for character in url) or urlsplit(url).scheme not in {"https", "file"}:
+ raise ValueError("An update dependency must be an exact HTTPS or local wheel")
+ filename = Path(unquote(urlsplit(url).path)).name
+ wheel_name, version, _, _ = parse_wheel_filename(filename)
+ if (wheel_name, str(version)) != (name, item.metadata.version) or name == "pip":
+ raise ValueError("Resolver returned an unsupported dependency artifact")
+ digest = item.download_info.archive_info.hashes.sha256
+ requirements.append(f"{name} @ {url} --hash=sha256:{digest}")
+ dependencies.append((filename, name, str(version), digest))
+ if requirements:
+ request = root / "requirements.txt"
+ request.write_text("\n".join(requirements), encoding="utf-8")
+ request.chmod(0o600)
+ downloads = root / "downloads"
+ _pip(process, python, "download", "--no-deps", "--only-binary=:all:", "--require-hashes",
+ "--dest", str(downloads), "--requirement", str(request))
+ for filename, name, version, digest in dependencies:
+ path = downloads / filename
+ record = StagedWheel(filename, name, version, path.stat().st_size, digest)
+ record.verify(downloads)
+ shutil.copyfile(path, wheels / filename)
+ records.append(record)
+ return tuple(records)
+
+
+def _prepare_transaction(plan: UpdatePlan, app_wheel: Path, directory: Path,
+ process: PreparationProcess) -> tuple[tuple[StagedWheel, ...], UVPreparation | None]:
+ if plan.installation.owner != "uv":
+ return _prepare_wheels(plan, app_wheel, directory, process), None
+ executable = shutil.which("uv")
+ if executable is None:
+ raise ValueError("The installation's uv manager is not available")
+ app = _stage_app(plan, app_wheel, directory)
+ prepared = prepare_uv(environment=plan.installation.environment, python=plan.installation.python,
+ receipt_sha256=plan.installation.records["uv-receipt.toml"],
+ app_wheel=directory / "wheels" / app.filename, version=plan.target.version,
+ extras=plan.extras or [], directory=directory, executable=executable, process=process)
+ return (app,), prepared
+
+
+def validate_preparation(plan: UpdatePlan) -> None:
+ """Check the supported preparation contract, without touching the environment."""
+ if plan.installation.owner not in {"venv", "uv"} or plan.extras is None:
+ raise ValueError("The worker requires a supported dedicated environment and explicitly confirmed extras")
+ if plan.installation.owner == "uv" and (os.name != "posix" or plan.installation.manager is None):
+ raise ValueError("This uv installation needs its owner's external update workflow")
+ if plan.owner_restriction:
+ raise ValueError(plan.owner_restriction)
+ if plan.action != "upgrade":
+ raise ValueError("This executor prepares upgrades only; no-op, restart and downgrade need their own review")
+ plan.validate_for(plan.installation)
+
+
+async def prepare_job(plan: UpdatePlan, feed: ReleaseFeed) -> Path:
+ """Stage a supported job without granting execution or changing installed files."""
+ validate_preparation(plan)
+ native_uv = plan.installation.owner == "uv"
+ root = installation_state_dir(plan.installation.environment)
+ # A stable stdlib-only entrypoint survives missing application dependencies.
+ # It selects the immutable per-job worker, not code in site-packages.
+ recovery = root.parent / "recover.py"
+ source = Path(__file__).with_name("update_recovery.py").read_text()
+ if recovery.exists() and (recovery.is_symlink() or not recovery.read_text().startswith(
+ '\"\"\"nanobot standalone recovery launcher, protocol 1.')):
+ raise ValueError("The recovery launcher path is already owned by another file")
+ atomic_write_lines(recovery, source.splitlines())
+ recovery.chmod(0o600)
+ with (file_access(root / "channel.lock", exclusive=False),
+ installation_access(environment=plan.installation.environment), file_access(root / "prepare.lock", exclusive=True)):
+ validate_preparation(plan)
+ directory = root / "jobs" / plan.id
+ directory.mkdir(parents=True, exist_ok=True, mode=0o700)
+ if (directory / "request.json").exists():
+ spec = WorkerSpec.read(directory)
+ saved = (directory / "plan.json").read_bytes()
+ if (UpdatePlan.model_validate_json(saved) != plan
+ or spec.plan_sha256 != hashlib.sha256(saved).hexdigest()):
+ raise ValueError("This job already belongs to another approved plan")
+ return directory
+ if (directory / "status.json").exists() and JobStatus.read(directory).phase == Phase.PREPARING:
+ # A crashed preparer may have left a native child writing staging.
+ # Absence of its Python task/lease is not proof that child exited.
+ raise ValueError("A previous preparation did not settle; inspect this job before retrying or cleaning it up")
+ plan_path = directory / "plan.json"
+ if plan_path.exists() and UpdatePlan.model_validate_json(plan_path.read_bytes()) != plan:
+ raise ValueError("This preparation already belongs to another reviewed plan")
+ if not plan_path.exists():
+ atomic_write_lines(plan_path, [plan.model_dump_json()])
+ plan_path.chmod(0o600)
+ # An orphan native command retains this installation-wide lease. Never
+ # replace its archive or begin another preparation while it is active.
+ with file_access(root / "prepare-native.lock", exclusive=True):
+ archive = directory / "worker.pyz"
+ archive.unlink(missing_ok=True) # No committed request exists above.
+ _worker_archive(archive)
+ process = PreparationProcess.create(directory, plan.installation.environment)
+ JobStatus(plan.id, Phase.PREPARING, 0, False,
+ "Checking the installation and preparing the exact package", int(time.time())).save(directory)
+ try:
+ return await _prepare_inputs(plan, feed, root, directory, process, native_uv=native_uv)
+ except asyncio.CancelledError:
+ JobStatus(plan.id, Phase.PREPARATION_FAILED, 0, False,
+ "Preparation cancelled after its workers exited; no installation was started",
+ int(time.time())).save(directory)
+ raise
+ except Exception as exc:
+ # Resolver/network exceptions can contain index credentials or paths.
+ JobStatus(plan.id, Phase.PREPARATION_FAILED, 0, False,
+ f"Preparation failed ({type(exc).__name__}); no installation was started",
+ int(time.time())).save(directory)
+ raise
+ finally:
+ process.close()
+
+
+async def _prepare_inputs(plan: UpdatePlan, feed: ReleaseFeed, root: Path, directory: Path,
+ process: PreparationProcess, *, native_uv: bool) -> Path:
+ baseline = await shield_and_drain(asyncio.to_thread(inspect_environment, plan.installation.python, uv=native_uv, process=process))
+ if (baseline.environment, baseline.python, baseline.app_version, baseline.receipt_sha) != (
+ plan.installation.environment, plan.installation.python, plan.installation.installed_version,
+ plan.installation.records.get("pyvenv.cfg"),
+ ) or any(plan.installation.records.get(name) != digest for name, digest in baseline.app_records.items()):
+ raise ValueError("The installation changed since this plan was prepared")
+ if native_uv and baseline.manager_receipt_sha != plan.installation.records.get("uv-receipt.toml"):
+ raise ValueError("The uv installation settings changed since this plan was prepared")
+ if baseline.installer_receipt_sha != plan.installation.records.get(RECEIPT_NAME):
+ raise ValueError("The installer selection changed since this plan was prepared")
+ validate_profiles(plan.profiles, plan.installation.environment)
+ JobStatus(plan.id, Phase.PREPARING, 0, False,
+ "Downloading and verifying the reviewed package", int(time.time())).save(directory)
+ app_wheel = await feed.download(plan.target, root / "downloads")
+ JobStatus(plan.id, Phase.PREPARING, 0, False,
+ "Preparing dependencies without changing the installation", int(time.time())).save(directory)
+ records, uv = await shield_and_drain(asyncio.to_thread(_prepare_transaction, plan, app_wheel, directory, process))
+ current = await shield_and_drain(asyncio.to_thread(inspect_environment, plan.installation.python, uv=native_uv, process=process))
+ if current != baseline:
+ raise ValueError("Installation changed while preparing the update")
+ plan.validate_for(plan.installation)
+ plan_path = directory / "plan.json"
+ archive = directory / "worker.pyz"
+ sources = [BackupSource(str(Path(baseline.environment) / "pyvenv.cfg"))]
+ if native_uv:
+ sources.append(BackupSource(str(Path(baseline.environment) / "uv-receipt.toml")))
+ if baseline.installer_receipt_sha is not None:
+ sources.append(BackupSource(str(Path(baseline.environment) / RECEIPT_NAME)))
+ for profile in plan.profiles:
+ receipt = profile.receipt
+ sources.extend(BackupSource.parse({"path": str(path)}) for path in receipt.data_paths)
+ sources.append(BackupSource(str(root / "profiles" / f"{receipt.id}.json")))
+ spec = WorkerSpec(plan.id, hashlib.sha256(plan_path.read_bytes()).hexdigest(), hashlib.sha256(archive.read_bytes()).hexdigest(),
+ baseline, plan.target.version, records, unique_sources(sources), tuple(plan.restart_profiles), uv,
+ automatic_recovery=bool(plan.restart_profiles) and baseline.installer_receipt_sha is not None)
+ for path in [archive, *(directory / "wheels" / item.filename for item in records)]:
+ path.chmod(0o600)
+ with path.open("r+b") as stream:
+ os.fsync(stream.fileno())
+ JobStatus(plan.id, Phase.READY, 0, False, "Files prepared; not installed", int(time.time())).save(directory)
+ # The immutable request is the commit record: its presence means every
+ # input and the initial status were flushed successfully.
+ spec.save(directory)
+ return directory
+
+
+def settle_interrupted_preparation(directory: Path) -> JobStatus:
+ """Revoke an abandoned, uncommitted preparation after its real child exits.
+
+ Internal recovery only: no install, directory deletion or automatic retry.
+ A record from the older parent-only lease scheme cannot establish this proof.
+ """
+ directory = directory.resolve()
+ process = PreparationProcess.load(directory)
+ root = installation_state_dir(process.environment)
+ with file_access(root / "prepare.lock", exclusive=True), file_access(root / "prepare-native.lock", exclusive=True):
+ if PreparationProcess.load(directory) != process:
+ raise ValueError("The preparation generation changed")
+ status = JobStatus.read(directory)
+ if status.phase != Phase.PREPARING or (directory / "request.json").exists() or status.mutation_started:
+ raise ValueError("Only an uncommitted preparation can be settled")
+ process.close()
+ status = JobStatus(directory.name, Phase.PREPARATION_FAILED, 0, False,
+ "Interrupted preparation stopped; no installation was started", int(time.time()))
+ status.save(directory)
+ return status
+
+
+async def start_job(directory: Path, feed: ReleaseFeed, *, repair: bool = False) -> subprocess.Popen[bytes]:
+ """Approve the exact staged job and start its detached worker.
+
+ Not called by a client route yet. The caller must quiesce/stop old runtimes;
+ the worker rechecks their leases before installation. Only explicitly saved
+ background participants may be restarted, never an external supervisor.
+ """
+ spec = WorkerSpec.read(directory)
+ plan = UpdatePlan.model_validate_json((directory / "plan.json").read_bytes())
+ runtime_phases = {Phase.RESTARTING, Phase.ACTIVATING, Phase.FINALIZING, Phase.RESTART_FAILED}
+ if JobStatus.read(directory).phase not in runtime_phases:
+ await feed.revalidate(plan.target)
+ with (file_access(installation_state_dir(spec.baseline.environment) / "channel.lock", exclusive=False),
+ file_access(installation_state_dir(spec.baseline.environment) / "worker.lock", exclusive=True)):
+ state = JobStatus.read(directory)
+ if state.phase in {Phase.INSTALLED, Phase.CANCELLED, Phase.SUCCEEDED, Phase.RESTORED}:
+ raise ValueError("This job is already finished; it cannot be started again")
+ restarting = state.phase in runtime_phases
+ if state.mutation_started and not repair:
+ raise ValueError("This interrupted job requires an explicit repair confirmation")
+ if repair and not state.mutation_started:
+ raise ValueError("Repair is only available after this job began replacing files")
+ current = await shield_and_drain(asyncio.to_thread(inspect_job_environment, directory, spec))
+ with (installation_access(updating=not restarting, allow_incomplete=restarting,
+ environment=spec.baseline.environment),
+ nullcontext() if state.phase == Phase.FINALIZING else
+ data_access((source.path for source in spec.backup_sources), updating=not restarting, job_id=spec.plan_id)):
+ check_environment(spec, repairing=state.mutation_started, current=current)
+ if not restarting:
+ require_stopped_profiles(plan.profiles, spec.baseline.environment)
+ spec.verify_inputs(directory)
+ now = int(time.time())
+ if not repair:
+ plan.validate_for(plan.installation, now=now)
+ write_record(directory / "approval.json", {
+ "plan_id": spec.plan_id, "request_sha256": hashlib.sha256((directory / "request.json").read_bytes()).hexdigest(),
+ "created_at": now, "expires_at": now + 900 if repair else min(plan.expires_at, now + 900),
+ })
+ return _spawn_worker(directory, spec)
+
+
+def start_handoff(directory: Path, *, once: bool = False) -> subprocess.Popen[bytes] | None:
+ """Confirm an exact prepared plan and detach before the requesting gateway exits.
+
+ Unlike start_job (already-stopped installations/repair), release revalidation
+ and cooperative shutdown run independently of the caller. No installation
+ approval is written until that child exits and exclusive leases are held.
+ With once=True, persist one confirmation and never launch again for a repeated
+ request. A missing response, failed launch or failed job is not retry authority.
+ """
+ return _start_handoff(directory, once=once)
+
+
+def retry_handoff(directory: Path, previous_confirmation_id: str) -> subprocess.Popen[bytes] | None:
+ """Consume explicit recovery consent for one unmodified handoff generation.
+
+ A stale predecessor is a read, not another retry. A live owner, surviving
+ preflight child, expired plan or package mutation requires a different action.
+ """
+ if UUID(previous_confirmation_id).hex != previous_confirmation_id:
+ raise ValueError("Invalid previous execution confirmation")
+ return _start_handoff(directory, once=True, previous_confirmation_id=previous_confirmation_id)
+
+
+def _start_handoff(directory: Path, *, once: bool,
+ previous_confirmation_id: str | None = None) -> subprocess.Popen[bytes] | None:
+ spec = WorkerSpec.read(directory)
+ plan = UpdatePlan.model_validate_json((directory / "plan.json").read_bytes())
+ root = installation_state_dir(spec.baseline.environment)
+
+ def already_confirmed() -> bool:
+ current = ExecutionConfirmation.read(directory)
+ if previous_confirmation_id is not None:
+ if current is None:
+ raise ValueError("No execution confirmation is available to retry")
+ return current.id != previous_confirmation_id
+ return once and current is not None
+
+ if already_confirmed():
+ return None
+ confirmation = None
+ with (file_access(root / "supervisor.lock", exclusive=True) if spec.automatic_recovery else nullcontext(),
+ file_access(root / "channel.lock", exclusive=False),
+ file_access(root / "worker.lock", exclusive=True),
+ file_access(root / "handoff-child.lock", exclusive=True),
+ installation_access(environment=spec.baseline.environment)):
+ state = JobStatus.read(directory)
+ if already_confirmed():
+ return None
+ if once and previous_confirmation_id is None and state.phase != Phase.READY:
+ raise ValueError("Only a ready job can receive its first execution confirmation")
+ if state.mutation_started or state.phase not in {
+ Phase.READY, Phase.CHECKING, Phase.STOPPING, Phase.HANDOFF_FAILED,
+ }:
+ raise ValueError("Shutdown handoff requires an unmodified prepared job")
+ now = int(time.time())
+ plan.validate_for(plan.installation, now=now)
+ spec.verify_inputs(directory)
+ approval: dict[str, object] = {
+ "plan_id": spec.plan_id, "request_sha256": hashlib.sha256((directory / "request.json").read_bytes()).hexdigest(),
+ "created_at": now, "expires_at": min(plan.expires_at, now + 900),
+ }
+ if once:
+ confirmation = ExecutionConfirmation(
+ uuid4().hex, spec.plan_id, hashlib.sha256((directory / "request.json").read_bytes()).hexdigest(),
+ now, min(plan.expires_at, now + 900),
+ )
+ # Persist before any launch. If the requester dies here, repeated
+ # submissions read this record; recovery needs explicit new consent.
+ confirmation.save(directory)
+ approval["confirmation_id"] = confirmation.id
+ # Both owner leases are held. Revoking the old confirmation first
+ # makes its delayed launchers harmless, even across a crash here.
+ (directory / "confirmation-claimed.json").unlink(missing_ok=True)
+ write_record(directory / "handoff-approval.json", approval)
+ (directory / "approval.json").unlink(missing_ok=True)
+ JobStatus(spec.plan_id, Phase.CHECKING, state.attempt, False,
+ "Starting an independent update handoff", now).save(directory)
+ # Release the ownership lease before spawning: a fast child must be able to
+ # take it immediately. Duplicate launches still serialize in run_job.
+ try:
+ return _spawn_worker(directory, spec, handoff=True, confirmation_id=confirmation.id if confirmation else None)
+ except OSError:
+ with file_access(root / "worker.lock", exclusive=True):
+ state = JobStatus.read(directory)
+ current = ExecutionConfirmation.read(directory)
+ if (state.phase == Phase.CHECKING
+ and (confirmation is None or current == confirmation)):
+ JobStatus(spec.plan_id, Phase.HANDOFF_FAILED, state.attempt, False,
+ "Could not start the independent update process; no shutdown was requested",
+ int(time.time())).save(directory)
+ raise
+
+
+def _spawn_worker(directory: Path, spec: WorkerSpec, *, handoff: bool = False,
+ confirmation_id: str | None = None) -> subprocess.Popen[bytes]:
+ command = [spec.baseline.base_python, "-I", "-S", str(directory / "worker.pyz")]
+ if spec.automatic_recovery:
+ command.extend(["--supervise", str(directory)])
+ if confirmation_id is not None:
+ command.extend(["--confirmed-handoff", str(directory), confirmation_id])
+ else:
+ command.extend(["--handoff", str(directory)] if handoff else [str(directory)])
+ if os.name == "nt":
+ return subprocess.Popen(command, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
+ cwd=directory, creationflags=subprocess.CREATE_NEW_PROCESS_GROUP | subprocess.DETACHED_PROCESS)
+ return subprocess.Popen(command, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
+ cwd=directory, start_new_session=True)
diff --git a/nanobot/update_manager.py b/nanobot/update_manager.py
new file mode 100644
index 000000000..e3edd0dd1
--- /dev/null
+++ b/nanobot/update_manager.py
@@ -0,0 +1,167 @@
+"""Read package-manager intent without changing its receipt or exposing source URLs.
+
+These facts supplement an installation-bound update plan. They do not authorize an
+installer: the owning manager still resolves its full settings and dependencies.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import tomllib
+from pathlib import Path
+from typing import Literal
+from urllib.parse import urlsplit
+
+from packaging.requirements import InvalidRequirement, Requirement
+from packaging.specifiers import SpecifierSet
+from packaging.utils import canonicalize_name
+from pydantic import BaseModel, ConfigDict, Field, field_validator
+
+from nanobot.releases import ReleaseRecord, Sha256
+
+Source = Literal["registry", "artifact", "source", "unrecognized"]
+
+
+def _source(url: str | None) -> Source:
+ if url is None:
+ return "registry"
+ parsed = urlsplit(url)
+ return "artifact" if parsed.scheme in {"https", "http", "file"} and parsed.path.endswith(".whl") else "source"
+
+
+class ManagerPolicy(ReleaseRecord):
+ """Credential-free summary; the receipt hash binds the complete private record."""
+
+ manager: Literal["uv", "pipx"]
+ backend: Literal["uv", "pip"]
+ extras: list[str] | None
+ version_constraint: str = Field(default="", max_length=1000)
+ source: Source
+ pinned: bool = False
+ locked: bool = False
+ injected_packages: list[str] = Field(default_factory=list, max_length=500)
+ custom_pip_args: bool = False
+
+ @field_validator("version_constraint")
+ @classmethod
+ def valid_constraint(cls, value: str) -> str:
+ SpecifierSet(value)
+ return value
+
+ @field_validator("extras", "injected_packages")
+ @classmethod
+ def normalized_names(cls, value: list[str] | None) -> list[str] | None:
+ if value is not None and (len(value) > 500 or value != sorted(set(value)) or any(
+ canonicalize_name(name, validate=True) != name for name in value
+ )):
+ raise ValueError("Expected unique normalized package or extra names")
+ return value
+
+ def restriction(self, version: str) -> str | None:
+ """Why this target requires owner intervention, not permission to execute it."""
+ if self.pinned:
+ return "The package is pinned by its installation owner. Review that pin before updating."
+ if self.locked:
+ return "The environment uses an owner-managed lock file. Update through that lock workflow."
+ if self.manager == "pipx" and (self.version_constraint or self.custom_pip_args):
+ return "This pipx installation has constraints or installer options. Review them with its owner; a generic pipx upgrade can discard those settings."
+ if self.manager == "uv" and self.source == "artifact":
+ return "This uv tool is bound to a wheel URL. Change its source through the installation owner's workflow."
+ if self.source in {"source", "unrecognized"} or self.extras is None:
+ return "The recorded installation source needs manual review by its owner."
+ if not SpecifierSet(self.version_constraint).contains(version, prereleases=True):
+ return "This version is outside the installation's recorded version constraints."
+ return None
+
+
+class _UVRequirement(BaseModel):
+ model_config = ConfigDict(extra="allow", strict=True)
+ name: str
+ extras: list[str] = Field(default_factory=list)
+ specifier: str = ""
+ url: str | None = None
+ index: str | None = None
+ marker: str | None = None
+
+
+class _UVTool(BaseModel):
+ model_config = ConfigDict(strict=True)
+ requirements: list[_UVRequirement] = Field(min_length=1, max_length=500)
+
+
+class _UVReceipt(BaseModel):
+ tool: _UVTool
+
+
+class _PipxPackage(BaseModel):
+ model_config = ConfigDict(strict=True)
+ package: str
+ package_or_url: str
+ pinned: bool = False
+ lock_file: str | dict[str, str] | None = None
+ pip_args: list[str] = Field(default_factory=list)
+
+
+class _PipxReceipt(BaseModel):
+ model_config = ConfigDict(strict=True)
+ pipx_metadata_version: str
+ main_package: _PipxPackage
+ injected_packages: dict[str, _PipxPackage] = Field(default_factory=dict, max_length=500)
+ backend: Literal["pip", "uv"] = "pip"
+
+
+def read_manager_policy(environment: Path, manager: Literal["uv", "pipx"], expected_sha: Sha256) -> ManagerPolicy:
+ """Read the exact receipt observed by the fresh interpreter, without rewriting it."""
+ path = environment / ("uv-receipt.toml" if manager == "uv" else "pipx_metadata.json")
+ try:
+ if path.is_symlink() or not path.is_file():
+ raise ValueError("Invalid package-manager receipt")
+ with path.open("rb") as stream:
+ raw = stream.read(1024 * 1024 + 1)
+ if len(raw) > 1024 * 1024 or hashlib.sha256(raw).hexdigest() != expected_sha:
+ raise ValueError("Package-manager receipt changed or exceeds its size limit")
+ if manager == "uv":
+ receipt = _UVReceipt.model_validate(tomllib.loads(raw.decode("utf-8")))
+ main = [item for item in receipt.tool.requirements if canonicalize_name(item.name) == "nanobot-ai"]
+ if len(main) != 1:
+ raise ValueError("Ambiguous managed package")
+ requirement = main[0]
+ source = "unrecognized" if requirement.model_extra or requirement.marker else _source(requirement.url)
+ return ManagerPolicy(
+ manager=manager, backend="uv", source=source,
+ extras=sorted({canonicalize_name(extra, validate=True) for extra in requirement.extras}),
+ version_constraint=requirement.specifier,
+ injected_packages=sorted({canonicalize_name(item.name, validate=True)
+ for item in receipt.tool.requirements if item is not requirement}),
+ )
+ pipx = _PipxReceipt.model_validate_json(raw)
+ # The fields used here have matching semantics in receipts produced by
+ # pipx 1.7.1 (0.5) and 1.17.13 (0.12). Reading an older supported receipt
+ # must not require upgrading pipx or migrating its private metadata.
+ if pipx.pipx_metadata_version not in {"0.5", "0.12"}:
+ raise ValueError("Unknown pipx receipt schema")
+ if canonicalize_name(pipx.main_package.package) != "nanobot-ai":
+ raise ValueError("Receipt belongs to another package")
+ try:
+ requested = Requirement(pipx.main_package.package_or_url)
+ except InvalidRequirement:
+ requested = None
+ if requested is not None and canonicalize_name(requested.name) != "nanobot-ai":
+ raise ValueError("Receipt names a different package")
+ return ManagerPolicy(
+ manager=manager, backend=pipx.backend,
+ source="unrecognized" if requested is None or requested.marker else (
+ "source" if "--editable" in pipx.main_package.pip_args or "-e" in pipx.main_package.pip_args else (
+ _source(requested.url)
+ )
+ ),
+ extras=sorted({canonicalize_name(extra, validate=True) for extra in requested.extras})
+ if requested is not None else None,
+ version_constraint=str(requested.specifier) if requested is not None else "",
+ pinned=pipx.main_package.pinned, locked=pipx.main_package.lock_file is not None,
+ custom_pip_args=bool(pipx.main_package.pip_args),
+ injected_packages=sorted({canonicalize_name(name, validate=True) for name in pipx.injected_packages}),
+ )
+ except (OSError, ValueError, TypeError):
+ # Parse errors can embed credential-bearing URLs; never relay their text.
+ raise ValueError("Could not verify package-manager settings; inspect this installation before updating") from None
diff --git a/nanobot/update_plan.py b/nanobot/update_plan.py
new file mode 100644
index 000000000..bd5d9f066
--- /dev/null
+++ b/nanobot/update_plan.py
@@ -0,0 +1,460 @@
+"""Installation-bound, expiring release plans shared by update entrypoints.
+
+Planning never invokes an installer or changes the running gateway. The approved
+record is immutable; an executor must revalidate it before changing any package files.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import hashlib
+import json
+import os
+import platform
+import shutil
+import subprocess
+import sys
+import time
+from pathlib import Path
+from typing import Literal
+from uuid import UUID, uuid4
+
+from filelock import FileLock
+from packaging.version import Version
+from pydantic import Field, field_validator, model_validator
+
+import nanobot
+from nanobot.installation_lock import installation_access, installation_id, installation_state_dir
+from nanobot.installation_receipt import RECEIPT_NAME, managed_extras
+from nanobot.release_feed import ReleaseFeed, ReleaseTarget
+from nanobot.releases import Channel, ReleaseRecord, Sha256
+from nanobot.update_channel import read_update_channel, validate_channel_revision
+from nanobot.update_guidance import UpdateGuide, update_guide
+from nanobot.update_manager import ManagerPolicy, read_manager_policy
+from nanobot.update_process import inspect_python_environment
+from nanobot.update_profiles import (
+ ObservedProfile,
+ ProfileReceipt,
+ inspect_profiles,
+ validate_profiles,
+)
+from nanobot.update_uv import UV_TRANSACTION_VERSION
+from nanobot.utils.atomic_file import atomic_write_lines
+
+Owner = Literal["venv", "uv", "pipx", "source", "container", "system"]
+
+
+def _managed_background(profile: ProfileReceipt, environment: str) -> bool:
+ return (profile.environment == environment and profile.launch_mode == "background"
+ and profile.launch is not None and profile.launch.lifetime == "explicit")
+
+# Read fresh metadata using this installation's Python, not an executable from PATH
+# or this long-lived gateway's cached importlib.metadata state. No config is loaded.
+_PROBE = """
+import hashlib, json, sys, nanobot
+from pathlib import Path
+from importlib.metadata import distribution
+d = distribution('nanobot-ai')
+prefix = Path(sys.prefix).resolve()
+records = {}
+for name in ('pyvenv.cfg', 'uv-receipt.toml', 'pipx_metadata.json', 'nanobot-install.json'):
+ path = prefix / name
+ if path.is_file():
+ records[name] = hashlib.sha256(path.read_bytes()).hexdigest()
+records['RECORD'] = hashlib.sha256((d.read_text('RECORD') or '').encode()).hexdigest()
+records['direct_url.json'] = hashlib.sha256((d.read_text('direct_url.json') or '').encode()).hexdigest()
+print(json.dumps(dict(environment=str(prefix), python=str(Path(sys.executable).absolute()),
+ installed_version=d.version, package_path=str(Path(nanobot.__file__).resolve()),
+ records=records)))
+"""
+
+
+class _Probe(ReleaseRecord):
+ environment: str
+ python: str
+ installed_version: str
+ package_path: str
+ records: dict[str, Sha256]
+
+
+class InstallationSnapshot(_Probe):
+ running_version: str
+ running_package: str
+ owner: Owner
+ manager: ManagerPolicy | None = None
+ manager_version: str | None = Field(default=None, max_length=64)
+
+ @model_validator(mode="after")
+ def matching_manager(self) -> InstallationSnapshot:
+ if self.manager is not None and self.manager.manager != self.owner:
+ raise ValueError("Package-manager settings must belong to this installation owner")
+ return self
+
+ @field_validator("installed_version", "running_version")
+ @classmethod
+ def valid_version(cls, value: str) -> str:
+ Version(value)
+ return value
+
+ @property
+ def installation_id(self) -> str:
+ return installation_id(self.environment)
+
+ @property
+ def fingerprint(self) -> str:
+ payload = json.dumps(self.model_dump(mode="json"), sort_keys=True, separators=(",", ":"))
+ return hashlib.sha256(payload.encode()).hexdigest()
+
+
+def inspect_installation() -> InstallationSnapshot:
+ probe = inspect_python_environment(sys.executable, str(Path(sys.prefix).resolve()), _PROBE, timeout=10)
+ probe.check_returncode()
+ fresh = _Probe.model_validate_json(probe.stdout)
+ if Path(fresh.environment) != Path(sys.prefix).resolve():
+ raise RuntimeError("The update interpreter belongs to a different installation")
+ root = Path(nanobot.__file__).resolve().parent.parent
+ owner: Owner = "venv"
+ if Path("/.dockerenv").exists() or os.environ.get("RENDER") == "true":
+ owner = "container"
+ elif (root / "pyproject.toml").is_file() and (root / "tui/package.json").is_file():
+ owner = "source"
+ elif "uv-receipt.toml" in fresh.records:
+ owner = "uv"
+ elif "pipx_metadata.json" in fresh.records:
+ owner = "pipx"
+ elif sys.prefix == sys.base_prefix:
+ owner = "system"
+ manager = None
+ manager_version = None
+ if owner == "uv" or owner == "pipx":
+ receipt = "uv-receipt.toml" if owner == "uv" else "pipx_metadata.json"
+ manager = read_manager_policy(Path(fresh.environment), owner, fresh.records[receipt])
+ if owner == "uv" and (executable := shutil.which("uv")):
+ try:
+ result = subprocess.run([executable, "--version"], capture_output=True, text=True, timeout=5)
+ parts = result.stdout.split()
+ if result.returncode == 0 and len(parts) >= 2 and parts[0] == "uv" and len(parts[1]) <= 64:
+ manager_version = parts[1]
+ except (OSError, subprocess.SubprocessError):
+ pass # Unknown manager capability requires its external workflow.
+ return InstallationSnapshot(**fresh.model_dump(), running_version=nanobot.__version__,
+ running_package=str(Path(nanobot.__file__).resolve()), owner=owner, manager=manager,
+ manager_version=manager_version)
+
+
+class UpdatePlan(ReleaseRecord):
+ schema_version: Literal[1] = 1
+ id: str
+ installation: InstallationSnapshot
+ channel: Channel
+ channel_revision: int | None = Field(default=None, ge=0)
+ target: ReleaseTarget
+ extras: list[str] | None = None
+ profiles: list[ObservedProfile] = Field(default_factory=list, max_length=1024)
+ # Explicit consent to stop exact running instances, separate from restart.
+ stop_profiles: list[str] = Field(default_factory=list, max_length=1024)
+ # Inventory alone is not authority to start a previously stopped instance.
+ restart_profiles: list[str] = Field(default_factory=list, max_length=1024)
+ created_at: int = Field(ge=0)
+ expires_at: int = Field(gt=0)
+
+ @field_validator("id")
+ @classmethod
+ def canonical_id(cls, value: str) -> str:
+ if str(UUID(value)) != value:
+ raise ValueError("Invalid update plan identifier")
+ return value
+
+ @field_validator("extras")
+ @classmethod
+ def explicit_extras(cls, value: list[str] | None) -> list[str] | None:
+ import re
+
+ if value is not None and (len(value) > 50 or len(value) != len(set(value)) or any(
+ not re.fullmatch(r"[a-z0-9]+(?:-[a-z0-9]+)*", extra) for extra in value
+ )):
+ raise ValueError("Extras must be explicit, unique normalized names")
+ return value
+
+ @model_validator(mode="after")
+ def valid_plan(self) -> UpdatePlan:
+ if not self.created_at < self.expires_at <= self.created_at + 15 * 60:
+ raise ValueError("Update plan must expire within fifteen minutes")
+ if self.channel == "stable" and Version(self.target.version).is_prerelease:
+ raise ValueError("A stable plan cannot install a preview")
+ if self.installation.manager is not None and self.extras != self.installation.manager.extras:
+ raise ValueError("An update must preserve the installation owner's recorded extras")
+ profiles = {item.receipt.id: item.receipt for item in self.profiles}
+ if len(set(self.stop_profiles)) != len(self.stop_profiles):
+ raise ValueError("Shutdown participants must be unique")
+ for participant in self.stop_profiles:
+ profile = profiles.get(participant)
+ if (profile is None or not _managed_background(profile, self.installation.environment)
+ or profile.stop_protocol != 1
+ or not any(item.receipt.id == participant and item.state == "running" for item in self.profiles)):
+ raise ValueError("Shutdown requires a reviewed running gateway with cooperative stop support")
+ if len(set(self.restart_profiles)) != len(self.restart_profiles):
+ raise ValueError("Restart participants must be unique")
+ for participant in self.restart_profiles:
+ profile = profiles.get(participant)
+ if (profile is None or not _managed_background(profile, self.installation.environment)
+ or not profile.port):
+ raise ValueError("Restart requires a reviewed, explicitly managed background gateway")
+ return self
+
+ @property
+ def action(self) -> Literal["upgrade", "downgrade", "restart", "none"]:
+ target = Version(self.target.version)
+ installed = Version(self.installation.installed_version)
+ running = Version(self.installation.running_version)
+ if target < max(installed, running):
+ return "downgrade"
+ if target > installed:
+ return "upgrade"
+ if running != installed:
+ return "restart"
+ return "none"
+
+ @property
+ def owner_restriction(self) -> str | None:
+ manager = self.installation.manager
+ return manager.restriction(self.target.version) if manager is not None else None
+
+ @property
+ def can_restart_inline(self) -> bool:
+ """The review includes this gateway and every confirmed running peer."""
+ running = {item.receipt.id for item in self.profiles if item.state == "running"}
+ return (not any(item.state == "unconfirmed" for item in self.profiles)
+ and any(item.state == "running" and item.receipt.pid == os.getpid() for item in self.profiles)
+ and running == set(self.stop_profiles) == set(self.restart_profiles))
+
+ def validate_for(self, installation: InstallationSnapshot, *, now: int | None = None) -> None:
+ validate_channel_revision(self.channel_revision, self.installation.environment)
+ checked_at = int(time.time()) if now is None else now
+ if checked_at < self.created_at or checked_at >= self.expires_at:
+ raise ValueError("Update plan expired; check again before confirming")
+ if self.installation.fingerprint != installation.fingerprint:
+ raise ValueError("Installation changed since this plan; check again before confirming")
+
+
+class UpdatePlanNotFoundError(FileNotFoundError):
+ """The requested saved plan is absent, not an installation-probe failure."""
+
+
+class UpdatePlans:
+ """Persist plans outside replaceable package files, with a small caller Interface."""
+
+ def __init__(self, directory: Path) -> None:
+ self.directory = directory
+
+ def save(self, plan: UpdatePlan) -> UpdatePlan:
+ encoded = plan.model_dump_json()
+ if len(encoded.encode("utf-8")) + 1 > 1024 * 1024:
+ raise ValueError("Update plan exceeds its size limit")
+ self.directory.mkdir(parents=True, exist_ok=True, mode=0o700)
+ path = self.directory / f"{plan.id}.json"
+ with FileLock(str(self.directory / "plans.lock"), timeout=5):
+ if path.exists():
+ if self.load(plan.id) != plan:
+ raise ValueError("An approved update plan cannot be replaced")
+ return plan
+ atomic_write_lines(path, [encoded])
+ path.chmod(0o600)
+ return plan
+
+ def load(self, plan_id: str) -> UpdatePlan:
+ UpdatePlan.canonical_id(plan_id)
+ path = self.directory / f"{plan_id}.json"
+ try:
+ if path.is_symlink() or path.stat().st_size > 1024 * 1024:
+ raise ValueError("Invalid saved update plan")
+ encoded = path.read_bytes()
+ except FileNotFoundError as exc:
+ raise UpdatePlanNotFoundError("The saved update plan is no longer available") from exc
+ plan = UpdatePlan.model_validate_json(encoded)
+ if plan.id != plan_id:
+ raise ValueError("Saved update plan identity differs")
+ return plan
+
+ async def prepare(self, installation: InstallationSnapshot, channel: Channel, feed: ReleaseFeed,
+ *, now: int | None = None, restart_running: bool = False,
+ extras: list[str] | None = None, channel_revision: int | None = None) -> UpdatePlan:
+ target = await feed.latest(channel)
+ created_at = int(time.time()) if now is None else now
+ profiles = inspect_profiles(installation.environment)
+ if installation.manager is not None:
+ if extras is not None and extras != installation.manager.extras:
+ raise ValueError("The plan cannot change the installation owner's recorded extras")
+ extras = installation.manager.extras
+ elif installation.owner == "venv" and RECEIPT_NAME in installation.records:
+ recorded_extras = managed_extras(installation.environment, installation.records[RECEIPT_NAME])
+ if extras is not None and extras != recorded_extras:
+ raise ValueError("The plan cannot change the installer's recorded extras")
+ extras = recorded_extras
+ participants: list[str] = []
+ if restart_running:
+ for profile in profiles:
+ if profile.state == "running":
+ if (not _managed_background(profile.receipt, installation.environment) or not profile.receipt.port
+ or profile.receipt.stop_protocol != 1):
+ # Review must still explain an external owner's workflow.
+ # Such a plan is ineligible for inline execution below.
+ continue
+ participants.append(profile.receipt.id)
+ plan = UpdatePlan(id=str(uuid4()), installation=installation, channel=channel, target=target, extras=extras, profiles=profiles,
+ channel_revision=channel_revision,
+ stop_profiles=participants, restart_profiles=participants,
+ created_at=created_at, expires_at=created_at + 15 * 60)
+ return self.save(plan)
+
+ async def revalidate(self, plan_id: str, installation: InstallationSnapshot, feed: ReleaseFeed,
+ *, now: int | None = None) -> UpdatePlan:
+ plan = self.load(plan_id)
+ plan.validate_for(installation, now=now)
+ validate_profiles(plan.profiles, installation.environment)
+ await feed.revalidate(plan.target)
+ # Release discovery can yield to a profile restart or a long network wait.
+ plan.validate_for(installation, now=now)
+ validate_profiles(plan.profiles, installation.environment)
+ return plan
+
+
+class UpdatePlanRequest(ReleaseRecord):
+ """An intended change to review, never installation/shutdown permission."""
+
+ channel: Channel | None = None
+ restart_running: bool = False
+ extras: list[str] | None = None
+
+ @field_validator("extras")
+ @classmethod
+ def explicit_extras(cls, value: list[str] | None) -> list[str] | None:
+ return UpdatePlan.explicit_extras(value)
+
+
+class ProfileReview(ReleaseRecord):
+ id: str
+ workspace: str
+ reviewed_state: Literal["running", "stopped", "unconfirmed"]
+ stop: bool
+ restart: bool
+
+
+class UpdatePlanReview(ReleaseRecord):
+ """Client-safe facts, not execution approval or fresh release eligibility.
+
+ Validity describes the locally observed installation and review lifetime.
+ Reading a review never re-resolves its target or checks the release feed.
+ """
+
+ id: str
+ installation_id: str
+ host: str
+ owner: Owner
+ running_version: str
+ installed_version: str
+ target_version: str
+ channel: Channel
+ action: Literal["upgrade", "downgrade", "restart", "none"]
+ created_at: int
+ expires_at: int
+ validity: Literal["current", "expired", "installation_changed", "profiles_changed", "channel_changed"]
+ artifact_size: int
+ extras: list[str] | None
+ owner_restriction: str | None
+ profiles: list[ProfileReview]
+ execution_blocked_reason: str | None = None
+ automatic_recovery: bool = False
+ guide: UpdateGuide | None = None
+
+
+def review_plan(plan: UpdatePlan, installation: InstallationSnapshot, *, now: int | None = None,
+ profiles: list[ObservedProfile] | None = None) -> UpdatePlanReview:
+ checked_at = int(time.time()) if now is None else now
+ validity: Literal["current", "expired", "installation_changed", "profiles_changed", "channel_changed"] = "current"
+ if (plan.channel_revision or 0) != read_update_channel(plan.installation.environment).revision:
+ validity = "channel_changed"
+ elif plan.installation.fingerprint != installation.fingerprint:
+ validity = "installation_changed"
+ elif not plan.created_at <= checked_at < plan.expires_at:
+ validity = "expired"
+ elif profiles is not None and profiles != plan.profiles:
+ validity = "profiles_changed"
+ return UpdatePlanReview(
+ id=plan.id, installation_id=plan.installation.installation_id, host=platform.node(),
+ owner=plan.installation.owner, running_version=installation.running_version,
+ installed_version=installation.installed_version, target_version=plan.target.version,
+ channel=plan.channel, action=plan.action, created_at=plan.created_at, expires_at=plan.expires_at,
+ validity=validity, artifact_size=plan.target.artifact.size, extras=plan.extras,
+ owner_restriction=plan.owner_restriction, execution_blocked_reason=inline_update_blocked_reason(plan, validity),
+ automatic_recovery=bool(plan.restart_profiles) and RECEIPT_NAME in plan.installation.records,
+ guide=update_guide(installation, plan.target.version, extras=plan.extras, current=validity == "current"),
+ profiles=[ProfileReview(
+ id=item.receipt.id, workspace=item.receipt.workspace, reviewed_state=item.state,
+ stop=item.receipt.id in plan.stop_profiles, restart=item.receipt.id in plan.restart_profiles,
+ ) for item in plan.profiles],
+ )
+
+
+def inline_update_blocked_reason(plan: UpdatePlan, validity: str = "current") -> str | None:
+ """Eligibility is not approval: preparation and handoff recheck these facts."""
+ if validity != "current":
+ return "review_changed"
+ if plan.action != "upgrade":
+ return "not_upgrade"
+ if plan.installation.owner not in {"venv", "uv"}:
+ return "installation_owner"
+ if plan.installation.owner == "uv" and (os.name != "posix"
+ or plan.installation.manager_version != UV_TRANSACTION_VERSION):
+ return "installation_owner"
+ if plan.extras is None or plan.owner_restriction:
+ return "installation_policy"
+ if not plan.can_restart_inline:
+ return "external_restart"
+ return None
+
+
+def inspect_update_installation() -> InstallationSnapshot:
+ # Keep the complete snapshot (including owner receipt parsing) protected
+ # after request cancellation. The native child also holds its own lease,
+ # so loss of this process cannot leave site/import/exit cleanup unprotected.
+ with installation_access():
+ return inspect_installation()
+
+
+async def preview_release_update(channel: Channel | None = None, *, restart_running: bool = False,
+ extras: list[str] | None = None) -> UpdatePlan:
+ """Build a read-only installation plan for CLI and future gateway handoff."""
+ with installation_access():
+ installation = await asyncio.to_thread(inspect_update_installation)
+ directory = installation_state_dir(installation.environment)
+ selection = read_update_channel(installation.environment)
+ async with ReleaseFeed(directory / "releases") as feed:
+ plan = await UpdatePlans(directory / "plans").prepare(
+ installation, channel or selection.channel, feed, restart_running=restart_running, extras=extras,
+ channel_revision=selection.revision,
+ )
+ # External package managers do not participate in our lease. Discovery
+ # can be slow: do not return a freshly valid review of a replaced install.
+ plan.validate_for(await asyncio.to_thread(inspect_update_installation))
+ return plan
+
+
+async def read_release_plan(plan_id: str) -> UpdatePlanReview:
+ """Recover the exact review after refresh; do not query a newer release."""
+ UpdatePlan.canonical_id(plan_id)
+ with installation_access():
+ installation = await asyncio.to_thread(inspect_update_installation)
+ plan = UpdatePlans(installation_state_dir(installation.environment) / "plans").load(plan_id)
+ return review_plan(plan, installation, profiles=inspect_profiles(installation.environment))
+
+
+def describe_plan(plan: UpdatePlan) -> str:
+ """No promised install command until the owner/lifecycle executor is available."""
+ return json.dumps({
+ **plan.model_dump(mode="json"), "action": plan.action,
+ "installation_id": plan.installation.installation_id,
+ "owner_restriction": plan.owner_restriction,
+ "profile_notice": "Known profiles only; this does not prove all runtimes or supervisors are accounted for.",
+ "notice": "Plan only. No packages were changed or processes restarted.",
+ }, indent=2)
diff --git a/nanobot/update_process.py b/nanobot/update_process.py
new file mode 100644
index 000000000..910dc16eb
--- /dev/null
+++ b/nanobot/update_process.py
@@ -0,0 +1,207 @@
+"""Process-owned leases and protected startup for frozen updater children.
+
+Copied into the frozen worker; keep this module standard-library only. Commands
+come from the preparer's implementation, never from a client or release record.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import runpy
+import subprocess
+import sys
+from contextlib import ExitStack
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Literal, cast
+from uuid import UUID, uuid4
+
+from nanobot.installation_lock import (
+ InstallationBusyError,
+ file_access,
+ installation_access,
+ installation_state_dir,
+)
+from nanobot.utils.atomic_file import atomic_write_lines, io_path
+
+# This stack belongs only to the single-use frozen child. Do not close it on a
+# function return/SystemExit: pip/site atexit cleanup must still hold the leases.
+# Module teardown and process exit release them after Python's exit callbacks.
+child_leases = ExitStack()
+
+
+def initialize_runtime(python: str, environment: str) -> None:
+ """Initialize the target's site only after the caller acquired its own leases."""
+ if not sys.flags.isolated or not sys.flags.no_site:
+ raise ValueError("An update child must start with isolated, deferred site initialization")
+ if Path(sys.executable).absolute() != Path(python).absolute():
+ raise ValueError("Update child is using a different Python interpreter")
+ import site
+
+ site.main()
+ if Path(sys.prefix).resolve() != Path(environment).resolve():
+ raise ValueError("Update child is using a different installation")
+
+
+_INSPECTION_BOOTSTRAP = """
+import json, sys, types
+from contextlib import ExitStack
+from pathlib import Path
+request = json.load(sys.stdin)
+atomic = types.ModuleType('_nanobot_inspection_atomic')
+sys.modules[atomic.__name__] = atomic
+exec(compile(request['atomic'], '<inspection atomic I/O>', 'exec'), atomic.__dict__)
+locking = types.ModuleType('_nanobot_inspection_lock')
+sys.modules[locking.__name__] = locking
+exec(compile(request['locking'], '<inspection leases>', 'exec'), locking.__dict__)
+leases = ExitStack()
+try:
+ leases.enter_context(locking.installation_access(environment=request['environment'],
+ allow_incomplete=request['allow_incomplete']))
+except locking.InstallationBusyError:
+ raise SystemExit(11) from None
+exec(compile(request['startup'], '<inspection startup>', 'exec'))
+initialize_runtime(request['python'], request['environment'])
+sys.argv = ['-c', *request['arguments']]
+exec(compile(request['probe'], '<installation inspection>', 'exec'), {'__name__': '__main__'})
+"""
+
+
+def inspect_python_environment(python: str, environment: str, probe: str, *,
+ arguments: tuple[str, ...] = (), timeout: int = 15,
+ allow_incomplete: bool = False) -> subprocess.CompletedProcess[str]:
+ """Run a first-party read probe with child-owned startup/exit protection.
+
+ Planning has no staged worker yet. Freeze the existing stdlib lease and
+ startup implementations while holding the parent lease, then pass them over
+ stdin to an isolated child. No mutable package code runs before its lease;
+ the global child stack survives probe return and atexit after caller loss.
+ This is not an installer or a command interface for clients/release records.
+ """
+ import inspect
+
+ with installation_access(environment=environment, allow_incomplete=allow_incomplete):
+ # Lease acquisition needs the same frozen I/O helper as the worker. The
+ # child must not import either helper from the target before its lease.
+ atomic_module = io_path.__module__
+ locking = inspect.getsource(sys.modules[installation_access.__module__]).replace(
+ f"from {atomic_module} import io_path", "from _nanobot_inspection_atomic import io_path",
+ )
+ request = json.dumps(dict(
+ atomic=inspect.getsource(sys.modules[atomic_module]), locking=locking,
+ startup=inspect.getsource(initialize_runtime), python=python, environment=environment,
+ probe=probe, arguments=arguments, allow_incomplete=allow_incomplete,
+ ))
+ result = subprocess.run([python, "-I", "-S", "-c", _INSPECTION_BOOTSTRAP], input=request,
+ capture_output=True, text=True, timeout=timeout)
+ if result.returncode == 11:
+ raise InstallationBusyError("This installation is being updated; try checking again when it finishes")
+ return result
+
+
+@dataclass(frozen=True)
+class PreparationProcess:
+ directory: Path
+ environment: str
+ generation: str
+ active: bool = True
+
+ @classmethod
+ def create(cls, directory: Path, environment: str) -> PreparationProcess:
+ """Called with the parent and native preparation leases held."""
+ result = cls(directory.resolve(), str(Path(environment).resolve()), uuid4().hex)
+ result._save(active=True)
+ return result
+
+ @classmethod
+ def load(cls, directory: Path) -> PreparationProcess:
+ path = directory / "preparation.json"
+ if path.is_symlink():
+ raise ValueError("Invalid preparation identity")
+ with path.open("rb") as stream:
+ value = json.loads(stream.read(16_385))
+ if not isinstance(value, dict):
+ raise ValueError("Invalid preparation identity")
+ record = cast(dict[str, object], value)
+ if (type(record.get("active")) is not bool or not isinstance(record.get("environment"), str)
+ or not isinstance(record.get("generation"), str)):
+ raise ValueError("Invalid preparation identity")
+ environment, generation = cast(str, record["environment"]), cast(str, record["generation"])
+ if (UUID(generation).hex != generation or not Path(environment).is_absolute()
+ or directory != installation_state_dir(environment).resolve() / "jobs" / str(UUID(directory.name))):
+ raise ValueError("Preparation belongs to another installation")
+ return cls(directory, environment, generation, cast(bool, record["active"]))
+
+ def _save(self, *, active: bool) -> None:
+ path = self.directory / "preparation.json"
+ atomic_write_lines(path, [json.dumps(dict(environment=self.environment,
+ generation=self.generation, active=active))])
+ path.chmod(0o600)
+
+ def close(self) -> None:
+ """Revoke late children only after the actual native command has exited."""
+ self._save(active=False)
+
+ def run(self, executable: str, arguments: list[str], *, kind: Literal["python", "native"] = "python",
+ timeout: int = 900, env: dict[str, str] | None = None,
+ cwd: Path | None = None) -> subprocess.CompletedProcess[str]:
+ # Python commands run in their intended interpreter. Native uv uses the
+ # base interpreter only to acquire leases, then replaces that same PID.
+ base: object = getattr(sys, "_base_executable")
+ if not isinstance(base, str):
+ raise ValueError("Preparation needs a known base Python")
+ bootstrap = executable if kind == "python" else base
+ request = json.dumps(dict(generation=self.generation, kind=kind,
+ executable=executable, arguments=arguments))
+ # -S prevents site/.pth code in the mutable environment from running
+ # before this child has acquired its own leases.
+ return subprocess.run([bootstrap, "-I", "-S", str(self.directory / "worker.pyz"),
+ "--prepare-native", str(self.directory)], input=request,
+ capture_output=True, text=True, timeout=timeout, env=env, cwd=cwd)
+
+
+def run_preparation_child(directory: Path) -> None:
+ """Acquire our own leases before reading mutable packages or staging files."""
+ encoded = sys.stdin.read(1024 * 1024 + 1)
+ if len(encoded) > 1024 * 1024:
+ raise ValueError("Preparation command exceeds its size limit")
+ value = json.loads(encoded)
+ if not isinstance(value, dict):
+ raise ValueError("Invalid preparation command")
+ request = cast(dict[str, object], value)
+ kind, executable, arguments = request.get("kind"), request.get("executable"), request.get("arguments")
+ if (not isinstance(kind, str) or kind not in {"python", "native"} or not isinstance(executable, str)
+ or not Path(executable).is_absolute() or not isinstance(arguments, list)
+ or not arguments):
+ raise ValueError("Invalid preparation command")
+ if not all(isinstance(item, str) for item in cast(list[object], arguments)):
+ raise ValueError("Invalid preparation arguments")
+ args = cast(list[str], arguments)
+ identity = PreparationProcess.load(directory)
+ native = child_leases.enter_context(file_access(
+ installation_state_dir(identity.environment) / "prepare-native.lock", exclusive=True))
+ installation = child_leases.enter_context(installation_access(environment=identity.environment))
+ # Recovery/retry holds native.lock while revoking the generation. Check
+ # again inside the lease: a delayed child cannot use a replacement job.
+ if (not identity.active or PreparationProcess.load(directory) != identity
+ or request.get("generation") != identity.generation):
+ raise ValueError("The preparation generation changed")
+ if kind == "native":
+ if os.name != "posix":
+ raise ValueError("Native preparation needs a verified exec handoff on this platform")
+ with native.inherit_for_exec(), installation.inherit_for_exec():
+ os.execve(executable, [executable, *args], os.environ)
+ if len(args) < 2 or not (args[:1] == ["-c"] or args[:2] == ["-m", "pip"]):
+ raise ValueError("Unsupported preparation command")
+ # Use the same Python path on POSIX and Windows; byte-range leases cannot
+ # transfer through exec on Windows. Site startup and atexit stay protected.
+ sys.argv = ["pip" if args[0] == "-m" else "-c", *args[2:]]
+ # uv also probes its disposable prepared venv. The job's leases protect
+ # both that staging area and the live installation; they are not necessarily
+ # the environment whose Python this particular probe is running.
+ initialize_runtime(executable, str(Path(executable).parent.parent))
+ if args[0] == "-m":
+ runpy.run_module("pip", run_name="__main__")
+ else:
+ exec(compile(args[1], "<update preparation probe>", "exec"), {"__name__": "__main__"})
diff --git a/nanobot/update_profiles.py b/nanobot/update_profiles.py
new file mode 100644
index 000000000..c6a96036e
--- /dev/null
+++ b/nanobot/update_profiles.py
@@ -0,0 +1,285 @@
+"""Installation-scoped inventory of gateway profiles, not process-control authority.
+
+Receipts survive shutdown so a stopped profile's durable data is not forgotten by
+an update plan. Liveness is checked against the existing process identity, never a
+PID alone. This inventory cannot discover pre-receipt or other-account runtimes;
+the installation lease and an explicit process-owner handoff are still required.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import os
+import sys
+from collections.abc import Generator
+from contextlib import contextmanager
+from pathlib import Path
+from typing import Literal
+from uuid import uuid4
+
+from filelock import FileLock
+from pydantic import BaseModel, ConfigDict, Field, field_validator
+
+import nanobot
+from nanobot.config.home import get_home_path
+from nanobot.data_access import DataStartupGrant, profile_data_access, profile_data_paths
+from nanobot.gateway.runtime import (
+ GatewayHealthIdentity,
+ GatewayInstance,
+ GatewayRuntime,
+ GatewayRuntimePaths,
+ GatewayStartOptions,
+)
+from nanobot.installation_lock import installation_state_dir
+from nanobot.utils.atomic_file import atomic_write_lines, read_atomic_bytes
+
+
+class ProfileLaunch(BaseModel):
+ """Original selectors, not inferred arguments or an executable shell command."""
+
+ model_config = ConfigDict(extra="forbid", frozen=True, strict=True)
+
+ home: str | None
+ config_path: str | None
+ workspace: str | None
+ working_directory: str
+ verbose: bool
+ lifetime: Literal["explicit", "on_demand"]
+
+ @field_validator("home", "config_path", "workspace", "working_directory")
+ @classmethod
+ def bounded_path(cls, value: str | None) -> str | None:
+ if value is not None and (not Path(value).is_absolute() or len(value) > 4096 or "\0" in value):
+ raise ValueError("Launch selectors must be bounded absolute paths")
+ return value
+
+ def options(self, *, port: int) -> GatewayStartOptions:
+ return GatewayStartOptions(home=self.home, config_path=self.config_path,
+ workspace=self.workspace, port=port, verbose=self.verbose)
+
+
+class ProfileReceipt(BaseModel):
+ model_config = ConfigDict(extra="forbid", frozen=True, strict=True)
+
+ schema_version: Literal[1] = 1
+ id: str = Field(pattern=r"^[0-9a-f]{64}$")
+ run_id: str = Field(pattern=r"^[0-9a-f]{32}$")
+ environment: str
+ python: str
+ package: str
+ version: str
+ home: str
+ data_dir: str
+ config: str
+ workspace: str
+ state_path: str
+ log_path: str
+ port: int = Field(ge=0, le=65535)
+ launch_mode: Literal["foreground", "background", "unknown"]
+ pid: int = Field(gt=0)
+ process_identity: str | int | None
+ active: bool
+ # Older receipts remain useful data inventory, but cannot prove launch intent.
+ launch: ProfileLaunch | None = None
+ stop_protocol: Literal[1] | None = None
+ update_job_id: str | None = Field(default=None, pattern=r"^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$")
+
+ @field_validator("environment", "python", "package", "home", "data_dir", "config", "workspace", "state_path", "log_path")
+ @classmethod
+ def absolute_path(cls, value: str) -> str:
+ if not Path(value).is_absolute() or len(value) > 4096 or "\0" in value:
+ raise ValueError("Profile paths must be bounded absolute paths")
+ return value
+
+ @property
+ def health_identity(self) -> GatewayHealthIdentity:
+ return GatewayHealthIdentity(self.id, self.run_id, self.version)
+
+ @property
+ def runtime_paths(self) -> GatewayRuntimePaths:
+ state, log = Path(self.state_path), Path(self.log_path)
+ return GatewayRuntimePaths(run_dir=state.parent, logs_dir=log.parent, state_path=state, log_path=log)
+
+ @property
+ def data_paths(self) -> tuple[Path, ...]:
+ # Preserve individual store paths: leases and backups must reject links,
+ # not resolve them into additional read/write authority.
+ return profile_data_paths(home=Path(self.home), data_dir=Path(self.data_dir),
+ config=Path(self.config), workspace=Path(self.workspace))
+
+
+class ObservedProfile(BaseModel):
+ model_config = ConfigDict(extra="forbid", frozen=True, strict=True)
+ receipt: ProfileReceipt
+ state: Literal["running", "stopped", "unconfirmed"]
+
+
+class _RuntimeClaim(BaseModel):
+ model_config = ConfigDict(strict=True)
+ pid: int = Field(gt=0)
+ identity: str | int | None = None
+ stable_identity: str | int | None = None
+
+
+def _observe(receipt: ProfileReceipt) -> Literal["running", "stopped", "unconfirmed"]:
+ state_path = Path(receipt.state_path)
+ runtime = GatewayRuntime(paths=receipt.runtime_paths)
+ try:
+ if state_path.is_symlink() or state_path.stat().st_size > 32 * 1024:
+ return "unconfirmed"
+ claim = _RuntimeClaim.model_validate_json(read_atomic_bytes(state_path))
+ except FileNotFoundError:
+ claim = None
+ except (OSError, ValueError):
+ return "unconfirmed"
+ if claim is not None and runtime.process_is_running(claim.pid):
+ identity = claim.stable_identity if claim.stable_identity is not None else claim.identity
+ if identity is None:
+ return "unconfirmed"
+ match = runtime.process_identity_match(identity, claim.pid)
+ if match == "unknown":
+ return "unconfirmed"
+ if match == "match":
+ # The profile may now be used by a different installation. Its old
+ # inactive receipt does not grant a right to back up/restore live data.
+ if claim.pid != receipt.pid:
+ return "unconfirmed"
+ if receipt.process_identity is None:
+ return "unconfirmed"
+ own_match = runtime.process_identity_match(receipt.process_identity, receipt.pid)
+ if own_match != "match":
+ return "unconfirmed"
+ return "running" if receipt.active else "stopped"
+ if receipt.active and runtime.process_is_running(receipt.pid):
+ match = (runtime.process_identity_match(receipt.process_identity, receipt.pid)
+ if receipt.process_identity is not None else "unknown")
+ if match != "mismatch":
+ return "unconfirmed" # Live process, but its runtime claim disappeared.
+ return "stopped"
+
+
+def _profile_id(state_path: str) -> str:
+ return hashlib.sha256(os.fsencode(Path(state_path).resolve())).hexdigest()
+
+
+def _save(directory: Path, receipt: ProfileReceipt) -> None:
+ path = directory / f"{receipt.id}.json"
+ atomic_write_lines(path, [receipt.model_dump_json()])
+ path.chmod(0o600)
+
+
+@contextmanager
+def record_gateway_profile(instance: GatewayInstance, runtime: GatewayRuntime, *,
+ data_dir: Path, workspace: Path, port: int,
+ verbose: bool = False,
+ grant: DataStartupGrant | None = None,
+ cooperative_stop: bool = False) -> Generator[ProfileReceipt]:
+ """Record an already-claimed gateway and retain its profile after shutdown."""
+ state_path = str(instance.paths.state_path.resolve())
+ directory = installation_state_dir() / "profiles"
+ directory.mkdir(parents=True, exist_ok=True, mode=0o700)
+ status = runtime.status()
+ if not status.running or status.pid != os.getpid():
+ raise ValueError("Only the gateway that claimed this runtime may record its profile")
+ options = instance.start_options(port=port, verbose=verbose)
+ receipt = ProfileReceipt(
+ id=_profile_id(state_path), run_id=uuid4().hex,
+ environment=str(Path(sys.prefix).resolve()), python=str(Path(sys.executable).absolute()),
+ package=str(Path(nanobot.__file__).resolve()), version=nanobot.__version__,
+ home=str(get_home_path().resolve()), data_dir=str(data_dir.resolve()),
+ config=str(instance.config_path.resolve()), workspace=str(workspace.resolve()),
+ state_path=state_path, log_path=str(instance.paths.log_path.resolve()), port=port,
+ launch_mode=status.launch_mode, pid=os.getpid(),
+ process_identity=runtime.process_identity(os.getpid()), active=True,
+ update_job_id=grant.job_id if grant else None,
+ stop_protocol=1 if cooperative_stop else None,
+ launch=ProfileLaunch(home=options.home, config_path=options.config_path,
+ workspace=options.workspace, working_directory=str(Path.cwd().resolve()),
+ verbose=options.verbose, lifetime=status.lifetime),
+ )
+ if grant is not None and grant.participant != receipt.id:
+ raise ValueError("Startup grant belongs to a different gateway instance")
+ with profile_data_access(home=Path(receipt.home), data_dir=Path(receipt.data_dir),
+ config=Path(receipt.config), workspace=Path(receipt.workspace), grant=grant):
+ with FileLock(str(directory / "profiles.lock"), timeout=5):
+ _save(directory, receipt)
+ try:
+ yield receipt
+ finally:
+ with FileLock(str(directory / "profiles.lock"), timeout=5):
+ # Persist the inactive receipt before releasing the data leases.
+ # A receipt alone does not prove every external writer has stopped.
+ _save(directory, receipt.model_copy(update={"active": False}))
+
+
+def inspect_profiles(environment: str) -> list[ObservedProfile]:
+ """Read known profiles without writing their runtime files or contacting hosts."""
+ directory = installation_state_dir(environment) / "profiles"
+ if not directory.exists():
+ return []
+ profiles: list[ObservedProfile] = []
+ with FileLock(str(directory / "profiles.lock"), timeout=5):
+ for path in sorted(directory.glob("*.json")):
+ if len(profiles) >= 1024 or path.is_symlink() or path.stat().st_size > 32 * 1024:
+ raise ValueError("Invalid installation profile inventory")
+ receipt = ProfileReceipt.model_validate_json(read_atomic_bytes(path))
+ if (receipt.environment != str(Path(environment).resolve()) or
+ receipt.id != path.stem or receipt.id != _profile_id(receipt.state_path)):
+ raise ValueError("Profile receipt belongs to a different installation or instance")
+ profiles.append(ObservedProfile(receipt=receipt, state=_observe(receipt)))
+ return profiles
+
+
+def validate_profiles(expected: list[ObservedProfile], environment: str) -> None:
+ """Before confirming a plan, reject a newly started/reconfigured profile."""
+ if inspect_profiles(environment) != expected:
+ raise ValueError("Gateway profiles changed since this plan; check again before confirming")
+
+
+def require_stopped_profiles(expected: list[ObservedProfile], environment: str) -> None:
+ """Allow the reviewed gateways to exit, not a replacement or an unknown owner."""
+ current = inspect_profiles(environment)
+ # A graceful exit only changes `active`; a restart/reconfiguration creates a
+ # new run_id and needs a new plan even if the file paths are unchanged.
+ before = [item.receipt.model_dump(exclude={"active"}) for item in expected]
+ after = [item.receipt.model_dump(exclude={"active"}) for item in current]
+ if before != after:
+ raise ValueError("Gateway profiles changed since this plan; check again before confirming")
+ if any(item.state != "stopped" for item in current):
+ raise ValueError("A reviewed gateway profile is still in use or its process owner is unconfirmed")
+
+
+def validate_restart_identity(previous: ProfileReceipt, current: ProfileReceipt, *,
+ version: str, job_id: str | None = None) -> None:
+ """Validate a new claim without mistaking it for running/healthy evidence."""
+ if previous.launch is None:
+ raise ValueError("The original gateway launch identity is unknown")
+ changing = {"run_id", "pid", "process_identity", "version", "active", "update_job_id", "stop_protocol"}
+ if (current.model_dump(exclude=changing) != previous.model_dump(exclude=changing)
+ or current.version != version or current.run_id == previous.run_id
+ or current.process_identity == previous.process_identity or current.update_job_id != job_id):
+ raise ValueError("The restarted gateway differs from the reviewed instance or target version")
+
+
+def verify_restarted_profile(previous: ProfileReceipt, *, version: str,
+ job_id: str | None = None, maintenance: bool | None = None) -> ProfileReceipt:
+ """Verify a fresh run of the reviewed local profile; never start/stop it.
+
+ Call under the update owner's lifecycle/maintenance handoff. A receipt or an
+ HTTP 200 alone is insufficient, and this does not grant restart authority.
+ """
+ observed = next((item for item in inspect_profiles(previous.environment)
+ if item.receipt.id == previous.id), None)
+ if observed is None or observed.state != "running":
+ raise ValueError("The updated gateway is not running with a verified process identity")
+ current = observed.receipt
+ validate_restart_identity(previous, current, version=version, job_id=job_id)
+ runtime = GatewayRuntime(paths=current.runtime_paths)
+ if not runtime.verify_ready(current.health_identity, maintenance=maintenance):
+ raise ValueError("Gateway readiness did not confirm the updated instance, run and version")
+ # Re-read the receipt as well: a new claim can precede its new receipt.
+ final = next((item for item in inspect_profiles(previous.environment)
+ if item.receipt.id == previous.id), None)
+ if final != observed:
+ raise ValueError("The gateway changed during restart verification")
+ return current
diff --git a/nanobot/update_recovery.py b/nanobot/update_recovery.py
new file mode 100644
index 000000000..70fd9b064
--- /dev/null
+++ b/nanobot/update_recovery.py
@@ -0,0 +1,68 @@
+"""nanobot standalone recovery launcher, protocol 1.
+
+Copied outside the installed package before an update. Uses only the standard
+library and delegates to the exact saved worker, never imports a broken nanobot.
+"""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import os
+import subprocess
+from pathlib import Path
+from uuid import UUID
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description="Inspect or resume a saved nanobot update; never install latest")
+ parser.add_argument("job", help="Saved update ID shown in the WebUI")
+ parser.add_argument("--repair", action="store_true", help="Review and resume this exact offline update")
+ parser.add_argument("--yes", action="store_true", help="Confirm the reviewed exact repair without a prompt")
+ args = parser.parse_args()
+ if str(UUID(args.job)) != args.job:
+ parser.error("Use the complete saved update ID")
+ if args.yes and not args.repair:
+ parser.error("--yes requires --repair")
+ # This launcher is staged beside the installation journals. Preserve that
+ # gateway's HOME for the frozen worker's job binding, locks and restarts,
+ # even when the operator invokes the command from their ordinary terminal.
+ root = Path(__file__).resolve().parent
+ worker_env = dict(os.environ, HOME=str(root.parent.parent), USERPROFILE=str(root.parent.parent))
+ matches = [path for path in root.glob(f"*/jobs/{args.job}") if path.is_dir() and not path.is_symlink()]
+ if len(matches) != 1:
+ parser.error("No unique saved job exists for this OS account. Keep the original update directory.")
+ directory = matches[0]
+ request_path = directory / "request.json"
+ if request_path.is_symlink() or request_path.stat().st_size > 16 * 1024 * 1024:
+ parser.error("Invalid saved update request")
+ request = json.loads(request_path.read_bytes())
+ worker = directory / "worker.pyz"
+ if (worker.is_symlink() or worker.stat().st_size > 2 * 1024 * 1024
+ or hashlib.sha256(worker.read_bytes()).hexdigest() != request["worker_sha256"]):
+ parser.error("The saved worker changed. Preserve the backup; do not run another installation over it.")
+ python = request["baseline"]["base_python"]
+ if not Path(python).is_absolute() or not Path(python).is_file():
+ parser.error("The original base Python is missing. Restore it before repairing this environment.")
+ command = [python, "-I", "-S", str(worker)]
+ # The frozen worker validates the full request, directory and plan binding.
+ result = subprocess.run([*command, "--status", str(directory)], env=worker_env,
+ check=True, capture_output=True, text=True)
+ status = json.loads(result.stdout)
+ print(f"Update {args.job}: {status['phase']}")
+ print(f"Version: {request['baseline']['app_version']} -> {request['version']}")
+ print(f"Environment: {request['baseline']['environment']}")
+ print(f"Saved files and backup: {directory}")
+ if not args.repair:
+ print("Inspection only. Add --repair to review and resume this exact job.")
+ return
+ print("Repair reuses verified saved files and the original backup. It does not download a new release or roll back data.")
+ if not args.yes and input("Resume this exact update? [y/N] ").strip().lower() not in {"y", "yes"}:
+ print("No changes made.")
+ return
+ raise SystemExit(subprocess.call([*command, "--recover", str(directory)], env=worker_env))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/nanobot/update_restart.py b/nanobot/update_restart.py
new file mode 100644
index 000000000..e39c6ff98
--- /dev/null
+++ b/nanobot/update_restart.py
@@ -0,0 +1,234 @@
+"""Post-install handoff to reviewed, explicitly managed background gateways.
+
+Entered through the frozen worker while holding a shared installation lease. The
+coordinator grants scoped data initialization, verifies all parked runtimes, then
+durably authorizes those exact run identities to accept work. It never reinstalls
+packages, kills another owner, or invents launch options from resolved paths.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import os
+import subprocess
+import sys
+import time
+from dataclasses import asdict, dataclass, replace
+from pathlib import Path
+from typing import Any
+
+import nanobot
+from nanobot.data_access import (
+ DataStartupGrant,
+ data_access,
+ finish_data_handoff,
+)
+from nanobot.gateway.runtime import GatewayHealthIdentity, GatewayRuntime
+from nanobot.installation_lock import pending_update_path
+from nanobot.update_plan import UpdatePlan
+from nanobot.update_profiles import (
+ ProfileReceipt,
+ inspect_profiles,
+ validate_restart_identity,
+ verify_restarted_profile,
+)
+from nanobot.update_worker import JobStatus, Phase, WorkerSpec, read_record, write_record
+
+_TOKEN_ENV = "NANOBOT_UPDATE_STARTUP_TOKEN"
+_HANDOFF_PHASES = {Phase.RESTARTING, Phase.ACTIVATING, Phase.FINALIZING, Phase.RESTART_FAILED, Phase.SUCCEEDED, Phase.RESTORED}
+
+
+def _read_plan(directory: Path) -> tuple[WorkerSpec, UpdatePlan]:
+ spec = WorkerSpec.read(directory)
+ if (directory / "restoration.json").exists():
+ restoration = read_record(directory / "restoration.json")
+ if restoration != {"plan_id": spec.plan_id, "state": "restarting"}:
+ raise ValueError("The original program restoration has not completed")
+ spec = replace(spec, version=spec.baseline.app_version)
+ plan = UpdatePlan.model_validate_json((directory / "plan.json").read_bytes())
+ if (Path(sys.prefix).resolve() != Path(spec.baseline.environment)
+ or nanobot.__version__ != spec.version or plan.id != spec.plan_id
+ or tuple(plan.restart_profiles) != spec.restart_profiles or not spec.restart_profiles):
+ raise ValueError("Runtime handoff does not match the approved installation and target")
+ return spec, plan
+
+
+@dataclass(frozen=True)
+class GatewayStartup:
+ directory: Path
+ previous: ProfileReceipt
+ grant: DataStartupGrant
+
+ def validate_installation(self) -> None:
+ spec, plan = _read_plan(self.directory)
+ pending = read_record(pending_update_path())
+ selected = {item.receipt.id: item.receipt for item in plan.profiles}
+ if (pending.get("job_id") != self.grant.job_id or pending.get("version") != spec.version
+ or spec.plan_id != self.grant.job_id or self.grant.participant != self.previous.id
+ or self.previous.id not in spec.restart_profiles
+ or selected.get(self.previous.id) != self.previous
+ or JobStatus.read(self.directory).phase not in {Phase.RESTARTING, Phase.ACTIVATING}):
+ raise ValueError("This gateway has no current protected-startup handoff")
+
+ def validate_profile(self, current: ProfileReceipt) -> None:
+ validate_restart_identity(self.previous, current, version=nanobot.__version__, job_id=self.grant.job_id)
+
+ async def wait_for_activation(self, identity: GatewayHealthIdentity) -> None:
+ """An approval for an earlier attempt/run cannot activate this process."""
+ deadline = time.monotonic() + 240
+ while time.monotonic() < deadline:
+ status = JobStatus.read(self.directory)
+ if status.phase not in {Phase.RESTARTING, Phase.ACTIVATING, Phase.FINALIZING, Phase.SUCCEEDED, Phase.RESTORED}:
+ raise ValueError("Update handoff stopped before gateway activation")
+ try:
+ decision = read_record(self.directory / "activation.json")
+ except FileNotFoundError:
+ decision = {}
+ if (status.phase in {Phase.ACTIVATING, Phase.FINALIZING, Phase.SUCCEEDED, Phase.RESTORED}
+ and decision.get("plan_id") == self.grant.job_id
+ and decision.get(self.previous.id) == asdict(identity)):
+ return
+ await asyncio.sleep(0.1)
+ raise TimeoutError("Gateway activation was not verified in time")
+
+
+def run_gateway(directory: Path, participant: str) -> None:
+ # Remove the bearer before configuration, channels, MCP or tools can inherit it.
+ token = os.environ.pop(_TOKEN_ENV, "")
+ spec, plan = _read_plan(directory)
+ previous = next(item.receipt for item in plan.profiles if item.receipt.id == participant)
+ startup = GatewayStartup(directory, previous, DataStartupGrant(spec.plan_id, participant, token))
+ startup.validate_installation()
+ launch = previous.launch
+ if launch is None:
+ raise ValueError("Original gateway launch selectors are unavailable")
+
+ from nanobot.cli.entry import configure_windows_console
+ from nanobot.cli.gateway_runtime import _run_gateway
+ from nanobot.cli.process_identity import set_cli_process_identity
+ from nanobot.cli.runtime_config import _load_runtime_config
+ from nanobot.config.home import set_home_path
+ from nanobot.config.loader import get_config_path
+ from nanobot.gateway.runtime import GatewayInstance
+ from nanobot.utils.log_config import configure_console_logging
+ from nanobot.utils.rotating_output import configure_background_output_from_env
+
+ configure_background_output_from_env()
+ set_cli_process_identity(["gateway"])
+ configure_windows_console()
+ configure_console_logging(sys.stderr, level="DEBUG" if launch.verbose else "INFO")
+ if Path.cwd().resolve() != Path(launch.working_directory):
+ raise ValueError("Gateway restart used a different working directory")
+ set_home_path(Path(launch.home) if launch.home else None)
+ config = _load_runtime_config(launch.config_path, launch.workspace)
+ instance = GatewayInstance.resolve(config_path=get_config_path(), workspace=launch.workspace)
+ _run_gateway(config, port=previous.port, verbose=launch.verbose, gateway_instance=instance,
+ update_startup=startup)
+
+
+def _start_gateway(directory: Path, previous: ProfileReceipt, grant: DataStartupGrant) -> None:
+ launch = previous.launch
+ if launch is None:
+ raise ValueError("Original gateway launch selectors are unavailable")
+
+ def spawn(_command: list[str], **kwargs: Any) -> subprocess.Popen[bytes] | subprocess.Popen[str]:
+ # Preserve the existing runtime's detached-process and rotating-log setup.
+ kwargs["env"] = {**kwargs["env"], _TOKEN_ENV: grant.token}
+ return subprocess.Popen([previous.python, "-I", "-S", str(directory / "worker.pyz"),
+ "--gateway", str(directory), previous.id],
+ cwd=launch.working_directory, text=False, **kwargs)
+
+ runtime = GatewayRuntime(paths=previous.runtime_paths,
+ python_executable=previous.python, popen=spawn)
+ result = runtime.start_background(launch.options(port=previous.port))
+ if not result.ok:
+ raise ValueError("The reviewed gateway could not start; inspect its existing runtime log")
+
+
+def _wait_verified(profiles: list[ProfileReceipt], spec: WorkerSpec, *,
+ maintenance: bool | None, deadline: float) -> list[ProfileReceipt]:
+ while True:
+ try:
+ return [verify_restarted_profile(profile, version=spec.version, job_id=spec.plan_id,
+ maintenance=maintenance) for profile in profiles]
+ except ValueError:
+ if time.monotonic() >= deadline:
+ raise ValueError("The reviewed gateways did not confirm target-version readiness in time") from None
+ time.sleep(0.1)
+
+
+def run_restarts(directory: Path) -> None:
+ """Resume only this job's startup/activation; never rerun its pip transaction."""
+ spec, plan = _read_plan(directory)
+ status = JobStatus.read(directory)
+ if status.phase not in _HANDOFF_PHASES:
+ raise ValueError("Package verification has not handed off to gateway restart")
+ profiles = [item.receipt for item in plan.profiles if item.receipt.id in spec.restart_profiles]
+ deadline = time.monotonic() + 120
+ pending = pending_update_path()
+ restored = (directory / "restoration.json").exists()
+ final_phase = Phase.RESTORED if restored else Phase.SUCCEEDED
+ final_message = ("The original service is running; the update was not installed and user data was not restored"
+ if restored else "The reviewed gateways are running the verified target version")
+ if status.phase in {Phase.SUCCEEDED, Phase.RESTORED}:
+ # Completed jobs are history, not authority to relaunch stopped gateways.
+ return
+ if pending.exists() and read_record(pending).get("job_id") != spec.plan_id:
+ raise ValueError("The installation is reserved by another update")
+ if status.phase == Phase.FINALIZING:
+ # Verification was durably committed before either fence was cleared.
+ # Do not rerun or reactivate applications to recover only this cleanup.
+ finish_data_handoff((item.path for item in spec.backup_sources), job_id=spec.plan_id)
+ pending.unlink(missing_ok=True)
+ status.advance(directory, final_phase, final_message)
+ return
+ if not pending.exists():
+ raise ValueError("The runtime handoff no longer owns an installation fence")
+
+ with data_access((item.path for item in spec.backup_sources), job_id=spec.plan_id) as data:
+ observed = {item.receipt.id: item for item in inspect_profiles(spec.baseline.environment)}
+ if set(observed) != {item.receipt.id for item in plan.profiles}:
+ raise ValueError("Gateway inventory changed during the update")
+ # Do not start or ignore a newly changed, unreviewed runtime.
+ for item in plan.profiles:
+ current = observed[item.receipt.id]
+ previous = item.receipt
+ unchanged = (current.receipt.model_dump(exclude={"active"})
+ == previous.model_dump(exclude={"active"}))
+ if previous.id not in spec.restart_profiles:
+ if not unchanged or current.state != "stopped":
+ raise ValueError("An unselected gateway changed during the update")
+ elif current.state == "unconfirmed":
+ raise ValueError("The restart participant's process owner is unconfirmed")
+ elif not unchanged:
+ # A failed, parked candidate may have recorded its run before
+ # exiting. Its stopped receipt is history, not launch authority.
+ version = plan.target.version if restored and current.state == "stopped" else spec.version
+ validate_restart_identity(previous, current.receipt, version=version, job_id=spec.plan_id)
+ elif current.state != "stopped":
+ raise ValueError("An original gateway is still running")
+
+ status.advance(directory, Phase.RESTARTING, "Starting the reviewed gateways with task intake closed", mutation_started=True)
+ for previous in profiles:
+ if observed[previous.id].state == "stopped":
+ grant = data.grant_profile_startup(
+ previous.id, home=Path(previous.home), data_dir=Path(previous.data_dir),
+ config=Path(previous.config), workspace=Path(previous.workspace),
+ )
+ _start_gateway(directory, previous, grant)
+
+ # A resumed activation can include already active runs; their durable
+ # job identity still has to match. A fresh handoff must prove intake shut.
+ resuming_activation = (directory / "activation.json").exists()
+ parked = _wait_verified(profiles, spec, maintenance=None if resuming_activation else True, deadline=deadline)
+ status.advance(directory, Phase.ACTIVATING, "Verified runtime identities; enabling the reviewed gateways", mutation_started=True)
+ write_record(directory / "activation.json", {
+ "plan_id": spec.plan_id, **{item.id: asdict(item.health_identity) for item in parked},
+ })
+ _wait_verified(profiles, spec, maintenance=False, deadline=deadline)
+ status.advance(directory, Phase.FINALIZING, "Verified running gateways; completing maintenance cleanup", mutation_started=True)
+ # Clearing data first retains the installation fence if either operation
+ # fails. Active participants continue holding their own shared leases.
+ data.release_reservation()
+ pending.unlink()
+ status.advance(directory, final_phase, final_message)
diff --git a/nanobot/update_service.py b/nanobot/update_service.py
new file mode 100644
index 000000000..36219b6b6
--- /dev/null
+++ b/nanobot/update_service.py
@@ -0,0 +1,273 @@
+"""Own exact-plan staging and execution consent independently of a client.
+
+Staging does not grant installation consent. Each explicit execution confirmation
+can launch its detached owner once; repeating an ID reads the durable record.
+No phase automatically retries work. Clients do not own installer lifetimes.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import subprocess
+import time
+from contextlib import ExitStack
+from pathlib import Path
+
+from pydantic import Field, field_validator
+
+from nanobot.installation_lock import (
+ file_access,
+ installation_access,
+ installation_id,
+ installation_state_dir,
+ pending_update_path,
+)
+from nanobot.release_feed import ReleaseFeed
+from nanobot.releases import ReleaseRecord
+from nanobot.update_channel import (
+ UpdateChannel,
+ UpdateChannelRequest,
+ read_update_channel,
+ write_update_channel,
+)
+from nanobot.update_jobs import (
+ UpdateJobNotFoundError,
+ UpdateJobView,
+ prepare_job,
+ read_update_job,
+ retry_handoff,
+ settle_interrupted_preparation,
+ start_handoff,
+ validate_preparation,
+)
+from nanobot.update_plan import UpdatePlan, UpdatePlans
+from nanobot.update_worker import JobStatus, Phase, read_record
+from nanobot.utils.atomic_file import atomic_write_lines
+from nanobot.utils.cancellation import shield_and_drain
+
+
+class UpdateJobRequest(ReleaseRecord):
+ id: str
+
+ @field_validator("id")
+ @classmethod
+ def canonical_id(cls, value: str) -> str:
+ return UpdatePlan.canonical_id(value)
+
+
+class UpdateExecutionRequest(UpdateJobRequest):
+ confirm_restart: bool
+
+ @field_validator("confirm_restart")
+ @classmethod
+ def explicit_restart(cls, value: bool) -> bool:
+ if not value:
+ raise ValueError("Confirm the reviewed shutdown and restart before updating")
+ return value
+
+
+class UpdateRetryRequest(UpdateExecutionRequest):
+ previous_confirmation_id: str = Field(pattern=r"^[0-9a-f]{32}$")
+
+
+class UpdateJobService:
+ def __init__(self) -> None:
+ self._task: asyncio.Task[None] | None = None
+ self._closing = False
+ self._reapers: set[asyncio.Task[None]] = set()
+
+ def has_pending_work(self) -> bool:
+ return self._task is not None and not self._task.done()
+
+ def change_channel(self, request: UpdateChannelRequest) -> UpdateChannel:
+ """Change subscription only; retire inactive staged jobs, never rollback."""
+ from nanobot.update_stop import settle_uncommitted_handoff
+
+ root = installation_state_dir()
+ with (file_access(root / "channel.lock", exclusive=True),
+ file_access(root / "preparation-controller.lock", exclusive=True),
+ installation_access(allow_incomplete=True)):
+ current = read_update_channel()
+ if request.revision != current.revision:
+ raise ValueError("Update channel changed in another client; check again")
+ if request.channel == current.channel:
+ return current
+ if self._closing or pending_update_path().exists():
+ raise ValueError("Recover the current update before changing channels")
+ staged: list[Path] = []
+ for path in (root / "jobs").glob("*/status.json"):
+ state = JobStatus.read(path.parent)
+ if state.phase in {Phase.SUCCEEDED, Phase.RESTORED, Phase.CANCELLED, Phase.PREPARATION_FAILED}:
+ continue
+ if state.phase not in {Phase.READY, Phase.HANDOFF_FAILED} or state.mutation_started:
+ raise ValueError("Finish or recover the current update before changing channels")
+ staged.append(path.parent)
+ # Existing settlement checks real worker leases, shutdown commit and
+ # install admission. Changing preference cannot discard pending work.
+ for directory in staged:
+ settle_uncommitted_handoff(directory)
+ selected = UpdateChannel(channel=request.channel, revision=current.revision + 1)
+ write_update_channel(selected)
+ return selected
+
+ def prepare(self, plan_id: str) -> UpdateJobView:
+ """Acknowledge one durable staging request; never install or restart."""
+ if self._closing:
+ raise RuntimeError("The update service is shutting down")
+ loop = asyncio.get_running_loop()
+ root = installation_state_dir()
+ plan = UpdatePlans(root / "plans").load(plan_id)
+ if plan.installation.installation_id != installation_id():
+ raise ValueError("The plan belongs to another installation")
+ try:
+ return read_update_job(plan_id)
+ except UpdateJobNotFoundError:
+ pass
+ # Acquire synchronously before acknowledging or starting a task. Another
+ # profile may return this job's journal, but cannot start competing work.
+ leases = ExitStack()
+ try:
+ leases.enter_context(file_access(root / "channel.lock", exclusive=False))
+ leases.enter_context(file_access(root / "preparation-controller.lock", exclusive=True))
+ leases.enter_context(installation_access())
+ validate_preparation(plan)
+ directory = root / "jobs" / plan_id
+ if directory.is_symlink():
+ raise ValueError("Invalid update job directory")
+ directory.mkdir(parents=True, exist_ok=True, mode=0o700)
+ plan_path = directory / "plan.json"
+ if plan_path.exists():
+ if UpdatePlan.model_validate(read_record(plan_path)) != plan:
+ raise ValueError("The job belongs to another plan")
+ else:
+ atomic_write_lines(plan_path, [plan.model_dump_json()])
+ plan_path.chmod(0o600)
+ # Recheck after taking the lease: a second process might have
+ # finished between the first lookup and acquisition.
+ if (directory / "status.json").exists():
+ return read_update_job(plan_id)
+ JobStatus(plan_id, Phase.PREPARATION_REQUESTED, 0, False,
+ "Preparation requested; no installation approved", int(time.time())).save(directory)
+ result = read_update_job(plan_id)
+ owned = leases.pop_all()
+ self._task = loop.create_task(self._prepare(plan, owned), name="nanobot-update-prepare")
+ # Also release if loop shutdown cancels before the coroutine enters.
+ self._task.add_done_callback(lambda _: owned.close())
+ return result
+ finally:
+ leases.close()
+
+ async def _prepare(self, plan: UpdatePlan, leases: ExitStack) -> None:
+ root = installation_state_dir()
+ directory = root / "jobs" / plan.id
+ with leases:
+ try:
+ async with ReleaseFeed(root / "releases") as feed:
+ # Revalidate the reviewed target, never resolve `latest`.
+ # prepare_job probes the actual environment under native
+ # child-owned leases before downloads or dependency work.
+ await feed.revalidate(plan.target)
+ await prepare_job(plan, feed)
+ except (Exception, asyncio.CancelledError) as exc:
+ # Raw errors can include private index URLs. Cancellation is
+ # recorded only after prepare_job has settled native work.
+ # A cancellation while closing the HTTP client cannot undo the
+ # durable staging commit which prepare_job already completed.
+ if not (directory / "request.json").exists():
+ JobStatus(plan.id, Phase.PREPARATION_FAILED, 0, False,
+ f"Preparation stopped ({type(exc).__name__}); no installation was started",
+ int(time.time())).save(directory)
+
+ def settle(self, plan_id: str) -> UpdateJobView:
+ """Settle inactive work before a new review; never retry or install."""
+ job = read_update_job(plan_id)
+ root = installation_state_dir()
+ directory = root / "jobs" / plan_id
+ with file_access(root / "preparation-controller.lock", exclusive=True):
+ if job.recorded_phase == Phase.PREPARATION_REQUESTED:
+ # No native child can start before PREPARING is persisted.
+ with file_access(root / "prepare.lock", exclusive=True):
+ state = JobStatus.read(directory)
+ if state.phase != Phase.PREPARATION_REQUESTED or state.mutation_started or (directory / "request.json").exists():
+ raise ValueError("The preparation state changed")
+ JobStatus(plan_id, Phase.PREPARATION_FAILED, 0, False,
+ "Interrupted request settled; no installation was started", int(time.time())).save(directory)
+ elif job.recorded_phase == Phase.PREPARING:
+ settle_interrupted_preparation(directory)
+ elif job.recorded_phase in {Phase.READY, Phase.HANDOFF_FAILED, Phase.CANCELLED}:
+ from nanobot.update_stop import settle_uncommitted_handoff
+
+ settle_uncommitted_handoff(directory)
+ else:
+ raise ValueError("Only an interrupted preparation or uncommitted handoff can be settled")
+ return read_update_job(plan_id)
+
+ async def execute(self, plan_id: str, *, previous_confirmation_id: str | None = None) -> UpdateJobView:
+ """Confirm once, or explicitly retry the supplied previous confirmation.
+
+ Repeating either request reads the durable result; it cannot launch twice.
+
+ This handoff does not count itself as pending runtime work: its detached
+ owner must be able to stop the requesting gateway. All unrelated work
+ still participates in the cooperative idle-admission check.
+ """
+ if self._closing:
+ raise RuntimeError("The update service is shutting down")
+ job = read_update_job(plan_id)
+ if previous_confirmation_id is not None:
+ if job.execution_confirmation_id is None:
+ raise ValueError("No execution confirmation is available to retry")
+ if job.execution_confirmation_id != previous_confirmation_id:
+ return job
+ elif job.execution_confirmation_id is not None:
+ return job
+ directory = installation_state_dir() / "jobs" / plan_id
+ plan = UpdatePlan.model_validate(read_record(directory / "plan.json"))
+ if not plan.can_restart_inline:
+ raise ValueError("Inline updates require reviewed shutdown and restart of this gateway and every running peer")
+ loop = asyncio.get_running_loop()
+
+ def launch() -> None:
+ process = (start_handoff(directory, once=True) if previous_confirmation_id is None
+ else retry_handoff(directory, previous_confirmation_id))
+ if process is not None:
+ # Transfer the child even if cancellation means the HTTP caller
+ # will never receive the thread's return value.
+ loop.call_soon_threadsafe(self._track_worker, process)
+
+ try:
+ await shield_and_drain(asyncio.to_thread(launch))
+ except (OSError, RuntimeError):
+ # The launcher may have failed after persisting consent, or another
+ # tab may already own the worker. Return durable facts, not a retry.
+ latest = read_update_job(plan_id)
+ if latest.execution_confirmation_id in {None, previous_confirmation_id}:
+ raise
+ return read_update_job(plan_id)
+
+ def _track_worker(self, process: subprocess.Popen[bytes]) -> None:
+ reaper = asyncio.create_task(self._reap(process), name="nanobot-update-reap")
+ self._reapers.add(reaper)
+ reaper.add_done_callback(self._reapers.discard)
+
+ @staticmethod
+ async def _reap(process: subprocess.Popen[bytes]) -> None:
+ # Do not put process.wait in the default thread pool: gateway shutdown
+ # would join that thread while this child is waiting for the gateway.
+ while process.poll() is None:
+ await asyncio.sleep(0.2)
+
+ async def close(self) -> None:
+ self._closing = True
+ if self._task is not None:
+ # Browser requests never own this task. Shutdown must also wait for
+ # the real preparation, not release ownership on cancellation.
+ while not self._task.done():
+ try:
+ await asyncio.shield(self._task)
+ except asyncio.CancelledError:
+ continue
+ self._task.result()
+ for reaper in self._reapers:
+ reaper.cancel()
+ await asyncio.gather(*self._reapers, return_exceptions=True)
diff --git a/nanobot/update_stop.py b/nanobot/update_stop.py
new file mode 100644
index 000000000..f3f3e58b3
--- /dev/null
+++ b/nanobot/update_stop.py
@@ -0,0 +1,301 @@
+"""Cooperative pre-install shutdown of explicitly reviewed gateway runs.
+
+The private local mailbox carries identities, never commands or arbitrary paths.
+Preparation is reversible: every participant must hold its idle admission gate
+before the coordinator commits normal shutdown. A committed stop is not an
+installation approval, and the installer must still acquire exclusive leases.
+Only a detached update owner runs this protocol, never a request awaiting its own exit.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import os
+import time
+from collections.abc import Callable
+from contextlib import AbstractContextManager, ExitStack
+from pathlib import Path
+from typing import Literal
+from uuid import uuid4
+
+from pydantic import BaseModel, ConfigDict, Field
+
+from nanobot.gateway.runtime import GatewayRuntime
+from nanobot.installation_lock import file_access, installation_access, installation_state_dir
+from nanobot.runtime_admission import RuntimeBusyError, RuntimeMaintenanceError
+from nanobot.update_plan import UpdatePlan
+from nanobot.update_profiles import ProfileReceipt, require_stopped_profiles, validate_profiles
+from nanobot.update_worker import JobStatus, Phase, WorkerSpec, read_record, write_record
+from nanobot.utils.atomic_file import io_path, read_atomic_bytes
+
+_POLL_SECONDS = 0.1
+
+
+class _Request(BaseModel):
+ model_config = ConfigDict(extra="forbid", frozen=True, strict=True)
+
+ plan_id: str = Field(pattern=r"^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$")
+ attempt: str = Field(pattern=r"^[0-9a-f]{32}$")
+ phase: Literal["prepare", "commit", "abort", "stopped"]
+ # Monotonic timestamps coordinate processes on this host, not other hosts.
+ deadline: float = Field(gt=0, allow_inf_nan=False)
+
+
+class _Reply(BaseModel):
+ model_config = ConfigDict(extra="forbid", frozen=True, strict=True)
+
+ attempt: str = Field(pattern=r"^[0-9a-f]{32}$")
+ run_id: str = Field(pattern=r"^[0-9a-f]{32}$")
+ state: Literal["ready", "busy", "released", "stopping", "refused"]
+
+
+def _request_path(environment: str) -> Path:
+ return installation_state_dir(environment) / "stop.json"
+
+
+def _read_request(environment: str) -> _Request | None:
+ try:
+ return _Request.model_validate(read_record(_request_path(environment), max_bytes=2048))
+ except FileNotFoundError:
+ return None
+
+
+def _job(environment: str, identifier: str) -> tuple[Path, UpdatePlan]:
+ directory = installation_state_dir(environment) / "jobs" / identifier
+ spec = WorkerSpec.read(directory)
+ plan = UpdatePlan.model_validate_json(read_atomic_bytes(directory / "plan.json"))
+ status = JobStatus.read(directory)
+ if (spec.baseline.environment != environment or plan.installation.environment != environment
+ or spec.plan_id != plan.id or tuple(plan.restart_profiles) != spec.restart_profiles
+ or spec.version != plan.target.version
+ or status.phase not in {Phase.READY, Phase.CHECKING, Phase.STOPPING} or status.mutation_started):
+ raise ValueError("Gateway shutdown requires an unchanged, prepared update job")
+ return directory, plan
+
+
+def _reply(directory: Path, request: _Request, profile: ProfileReceipt,
+ state: Literal["ready", "busy", "released", "stopping", "refused"]) -> None:
+ path = directory / "stop-replies" / f"{profile.id}.json"
+ io_path(path.parent).mkdir(exist_ok=True, mode=0o700)
+ write_record(path, _Reply(attempt=request.attempt, run_id=profile.run_id, state=state).model_dump())
+
+
+def _coordinator_present(environment: str) -> bool:
+ try:
+ with file_access(installation_state_dir(environment) / "stop.lock", exclusive=True):
+ return False
+ except BlockingIOError:
+ return True
+
+
+async def watch_gateway_stop(
+ profile: ProfileReceipt,
+ maintenance: Callable[[], AbstractContextManager[None]],
+ shutdown_event: asyncio.Event,
+ shutdown_gate: ExitStack,
+) -> None:
+ """Serve this run's mailbox on the same event loop as task admission.
+
+ The runtime must retain shutdown_gate until its consumers and cleanup finish.
+ Cancellation before commit restores intake; after commit the outer runtime
+ owns the gate, so cancelling this watcher cannot reopen task intake.
+ """
+ seen: str | None = None
+ while not shutdown_event.is_set():
+ try:
+ request = _read_request(profile.environment)
+ if request is not None and request.attempt != seen:
+ seen = request.attempt
+ if (request.phase == "prepare" and time.monotonic() < request.deadline
+ and _coordinator_present(profile.environment)):
+ await _prepare_gateway_stop(profile, request, maintenance, shutdown_event, shutdown_gate)
+ except (OSError, ValueError):
+ # A malformed/stale local record must not crash an otherwise healthy
+ # gateway. The coordinator times out; it never treats silence as ready.
+ pass
+ await asyncio.sleep(_POLL_SECONDS)
+
+
+async def _prepare_gateway_stop(
+ profile: ProfileReceipt,
+ request: _Request,
+ maintenance: Callable[[], AbstractContextManager[None]],
+ shutdown_event: asyncio.Event,
+ shutdown_gate: ExitStack,
+) -> None:
+ directory, plan = _job(profile.environment, request.plan_id)
+ selected = next((item for item in plan.profiles if item.receipt.id == profile.id), None)
+ if profile.id not in plan.stop_profiles:
+ return
+ if selected is None or selected.receipt != profile or selected.state != "running":
+ _reply(directory, request, profile, "refused")
+ return
+ plan.validate_for(plan.installation)
+ committed = False
+ with ExitStack() as gate:
+ try:
+ gate.enter_context(maintenance())
+ except (RuntimeBusyError, RuntimeMaintenanceError):
+ _reply(directory, request, profile, "busy")
+ return
+ try:
+ _reply(directory, request, profile, "ready")
+ while not shutdown_event.is_set():
+ current = _read_request(profile.environment)
+ if (current is None or current.plan_id != request.plan_id
+ or current.attempt != request.attempt or current.phase not in {"prepare", "commit"}):
+ return
+ if current.phase == "commit":
+ # Commit is durable and irrevocable even if its coordinator
+ # exits. Only a prepared run can accept it; startup replay
+ # or a new run identity cannot enter this branch.
+ shutdown_gate.enter_context(gate.pop_all())
+ committed = True
+ shutdown_event.set()
+ _reply(directory, request, profile, "stopping")
+ return
+ if not _coordinator_present(profile.environment):
+ # The owner may have committed just before exiting. Read
+ # once more after observing its released lease, rather than
+ # undoing that durable decision from an earlier prepare read.
+ latest = _read_request(profile.environment)
+ if (latest is not None and latest.attempt == request.attempt
+ and latest.plan_id == request.plan_id and latest.phase == "commit"):
+ continue
+ return
+ # While its lease remains held, the coordinator owns the
+ # deadline decision. Independently expiring a ready participant
+ # could reopen intake between the ready check and commit.
+ await asyncio.sleep(_POLL_SECONDS)
+ finally:
+ if not committed:
+ # Release before publishing the acknowledgement. A failed write
+ # cannot keep task intake closed after refusal/cancellation.
+ gate.close()
+ _reply(directory, request, profile, "released")
+
+
+async def stop_reviewed_gateways(directory: Path, *, timeout: float = 30) -> None:
+ """Stop only the plan's selected runs, or abort before any stop is committed.
+
+ Call from the detached update owner, not a gateway request awaiting its own
+ shutdown. Cancellation before commit aborts all holds. After commit, callers
+ must report/recover the saved handoff rather than promise that nobody stopped.
+ The caller revalidates release eligibility and installation identity before
+ requesting shutdown. This operation neither approves nor launches installation.
+ """
+ if not 0 < timeout <= 120:
+ raise ValueError("Shutdown timeout must be between zero and 120 seconds")
+ spec = WorkerSpec.read(directory)
+ environment = spec.baseline.environment
+ root = installation_state_dir(environment)
+ # The detached parent owns worker.lock. This coordinator owns the stop
+ # mailbox and a runtime lease instead, also protecting standalone callers
+ # and an orphan child when its parent exits before the handoff completes.
+ with (installation_access(environment=environment), file_access(root / "stop.lock", exclusive=True),
+ file_access(root / "prepare.lock", exclusive=True), file_access(root / "prepare-native.lock", exclusive=True)):
+ _, plan = _job(environment, spec.plan_id)
+ participants = [item.receipt for item in plan.profiles if item.receipt.id in plan.stop_profiles]
+ if any(item.pid == os.getpid() for item in participants):
+ raise ValueError("The shutdown coordinator must run outside the selected gateways")
+ previous = _read_request(environment)
+ resuming = previous is not None and previous.plan_id == plan.id and previous.phase in {"commit", "stopped"}
+ if previous is not None and previous.phase == "commit" and not resuming:
+ raise ValueError("A committed gateway shutdown needs to be resolved before another handoff")
+ if not resuming:
+ plan.validate_for(plan.installation)
+ # Refuse missing/changed staged inputs before disturbing a running
+ # gateway. Installation will independently recheck them after exit.
+ await asyncio.to_thread(spec.verify_inputs, directory)
+ plan.validate_for(plan.installation)
+ validate_profiles(plan.profiles, environment)
+ if any(item.state == "unconfirmed" or
+ (item.state == "running" and item.receipt.id not in plan.stop_profiles)
+ for item in plan.profiles):
+ raise ValueError("Every running gateway must have a confirmed shutdown selection")
+ request = _Request(plan_id=plan.id, attempt=uuid4().hex, phase="prepare",
+ deadline=time.monotonic() + timeout)
+ write_record(_request_path(environment), request.model_dump())
+ try:
+ while True:
+ ready: set[str] = set()
+ for profile in participants:
+ path = directory / "stop-replies" / f"{profile.id}.json"
+ try:
+ reply = _Reply.model_validate(read_record(path, max_bytes=2048))
+ except FileNotFoundError:
+ continue
+ if reply.attempt != request.attempt:
+ continue
+ if reply.run_id != profile.run_id:
+ raise ValueError("A selected gateway run changed; no stop was committed")
+ if reply.state != "ready":
+ raise ValueError("A selected gateway is busy or refused shutdown; no stop was committed")
+ ready.add(profile.id)
+ if len(ready) == len(participants):
+ plan.validate_for(plan.installation)
+ validate_profiles(plan.profiles, environment)
+ if time.monotonic() >= request.deadline:
+ raise TimeoutError("Gateway shutdown preparation expired")
+ write_record(_request_path(environment), request.model_copy(update={"phase": "commit"}).model_dump())
+ break
+ if time.monotonic() >= request.deadline:
+ raise TimeoutError("Gateways did not prepare shutdown in time; no stop was committed")
+ await asyncio.sleep(_POLL_SECONDS)
+ finally:
+ # Atomic replacement may have succeeded even if its directory
+ # fsync failed. Never overwrite an observable commit with abort.
+ decision = _read_request(environment)
+ if decision is not None and decision.attempt == request.attempt and decision.phase == "prepare":
+ write_record(_request_path(environment), request.model_copy(update={"phase": "abort"}).model_dump())
+
+ # A receipt becomes inactive before its outer process/lease finishes.
+ # Require actual process exit too, and leave lock acquisition to the
+ # installer: neither an acknowledgement nor inventory grants that lock.
+ deadline = time.monotonic() + timeout
+ reviewed_runs = [item.receipt for item in plan.profiles]
+ while True:
+ try:
+ require_stopped_profiles(plan.profiles, environment)
+ runtime = GatewayRuntime()
+ if all(not runtime.process_is_running(item.pid) or (
+ item.process_identity is not None
+ and runtime.process_identity_match(item.process_identity, item.pid) == "mismatch"
+ ) for item in reviewed_runs):
+ completed = _read_request(environment)
+ if completed is not None and completed.plan_id == plan.id:
+ write_record(_request_path(environment), completed.model_copy(update={"phase": "stopped"}).model_dump())
+ return
+ except ValueError:
+ pass
+ if time.monotonic() >= deadline:
+ raise TimeoutError("Shutdown was committed but process exit is not confirmed; no package files were changed")
+ await asyncio.sleep(_POLL_SECONDS)
+
+
+def settle_uncommitted_handoff(directory: Path) -> JobStatus:
+ """Retire a prepared/failed handoff without undoing a committed shutdown.
+
+ The requesting gateway can remain running. No worker, orphan preflight or
+ stop coordinator may still own the old job. Keep its files and confirmation
+ for diagnosis; CANCELLED prevents a delayed launcher from using that consent.
+ """
+ spec = WorkerSpec.read(directory)
+ root = installation_state_dir(spec.baseline.environment)
+ with (file_access(root / "worker.lock", exclusive=True),
+ file_access(root / "handoff-child.lock", exclusive=True),
+ file_access(root / "stop.lock", exclusive=True),
+ installation_access(environment=spec.baseline.environment)):
+ status = JobStatus.read(directory)
+ if status.mutation_started or status.phase not in {Phase.READY, Phase.HANDOFF_FAILED, Phase.CANCELLED}:
+ raise ValueError("Only an unmodified, inactive handoff can be settled")
+ request = _read_request(spec.baseline.environment)
+ if request is not None and request.plan_id == spec.plan_id and request.phase in {"commit", "stopped"}:
+ raise ValueError("Shutdown was committed; recover the saved update before starting another")
+ if (directory / "approval.json").exists():
+ raise ValueError("Installation was admitted; recover the saved update before starting another")
+ if status.phase != Phase.CANCELLED:
+ status = JobStatus(spec.plan_id, Phase.CANCELLED, status.attempt, False,
+ "Previous handoff settled; review a new plan before updating", int(time.time()))
+ status.save(directory)
+ return status
diff --git a/nanobot/update_uv.py b/nanobot/update_uv.py
new file mode 100644
index 000000000..96f9ac31d
--- /dev/null
+++ b/nanobot/update_uv.py
@@ -0,0 +1,354 @@
+"""Private uv tool preparation; cache copies never change the owner's saved policy.
+
+Keep this module stdlib-only: its verification/copy operations also run from the
+frozen update worker after the installed application has stopped.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import os
+import re
+import shutil
+import stat
+import tempfile
+import tomllib
+from dataclasses import dataclass
+from pathlib import Path
+from typing import cast
+
+from nanobot.update_process import PreparationProcess
+
+# Cache/receipt and exec-lease behavior must be exercised before expanding this
+# internal native route to another manager release. Unsupported versions use
+# the installation owner's workflow; they are never downgraded automatically.
+UV_TRANSACTION_VERSION = "0.11.16"
+_TRANSPORT_SETTINGS = {"UV_HTTP_TIMEOUT", "UV_HTTP_RETRIES", "UV_SYSTEM_CERTS", "UV_NATIVE_TLS"}
+
+
+def _receipt_only_policy() -> None:
+ """Refuse external resolver policy that this receipt-bound plan has not frozen."""
+ locations = {"UV_TOOL_DIR", "UV_TOOL_BIN_DIR", "UV_CACHE_DIR", "UV_NO_CONFIG"}
+ for key in os.environ:
+ if (key.startswith("UV_") and key not in locations | _TRANSPORT_SETTINGS
+ and not (key.startswith("UV_INDEX_") and key.endswith(("_USERNAME", "_PASSWORD")))):
+ raise ValueError("External uv settings require the installation owner's update workflow")
+ if os.environ.get("UV_NO_CONFIG", "").lower() in {"1", "true"}:
+ return
+ roots = [Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config"), Path("/etc")]
+ roots.extend(Path(value) for value in os.environ.get("XDG_CONFIG_DIRS", "/etc/xdg").split(":") if value)
+ if any((root / "uv/uv.toml").exists() for root in roots):
+ raise ValueError("External uv configuration requires the installation owner's update workflow")
+
+
+def _record(value: object) -> dict[str, object]:
+ if not isinstance(value, dict):
+ raise ValueError("Invalid uv preparation record")
+ data = cast(dict[object, object], value)
+ if not all(isinstance(key, str) for key in data):
+ raise ValueError("Invalid uv preparation record")
+ return cast(dict[str, object], data)
+
+
+def _text(value: object) -> str:
+ if not isinstance(value, str) or not value or len(value) > 16_384:
+ raise ValueError("Invalid uv preparation value")
+ return value
+
+
+def _hash_file(path: Path) -> str:
+ with path.open("rb") as stream:
+ return hashlib.file_digest(stream, "sha256").hexdigest()
+
+
+def _toml(value: object) -> str:
+ """Re-encode parsed receipt settings, leaving their semantics to uv itself."""
+ if isinstance(value, (str, bool)) or type(value) is int:
+ return json.dumps(value, ensure_ascii=False)
+ if isinstance(value, list):
+ return "[" + ", ".join(_toml(item) for item in cast(list[object], value)) + "]"
+ if isinstance(value, dict):
+ items = _record(cast(dict[object, object], value))
+ return "{ " + ", ".join(f"{json.dumps(key)} = {_toml(item)}" for key, item in items.items()) + " }"
+ raise ValueError("Unsupported uv receipt setting; use the installation owner")
+
+
+def _requirement(value: object) -> str:
+ item = _record(value)
+ if item.keys() - {"name", "extras", "specifier", "url", "marker"}:
+ raise ValueError("This uv requirement needs its owner's update workflow")
+ name = _text(item.get("name"))
+ extras = item.get("extras", [])
+ if not isinstance(extras, list):
+ raise ValueError("Invalid uv requirement extras")
+ extra_values = cast(list[object], extras)
+ if (not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]*", name)
+ or not all(isinstance(extra, str) and re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]*", extra)
+ for extra in extra_values)):
+ raise ValueError("Invalid uv requirement identity")
+ suffix = "[" + ",".join(cast(list[str], extras)) + "]" if extras else ""
+ url = item.get("url")
+ if url is not None:
+ # Source/editable installs can run build children; they are not a wheel
+ # transaction and must not be quietly converted into one.
+ from urllib.parse import urlsplit
+
+ parsed = urlsplit(_text(url))
+ if parsed.scheme not in {"https", "http", "file"} or not parsed.path.endswith(".whl"):
+ raise ValueError("Source requirements need the uv owner's update workflow")
+ suffix += " @ " + _text(url)
+ elif item.get("specifier"):
+ suffix += _text(item["specifier"])
+ if item.get("marker"):
+ suffix += " ; " + _text(item["marker"])
+ return name + suffix
+
+
+def uv_environment(*, tools: Path, binaries: Path, cache: Path) -> dict[str, str]:
+ """Use frozen receipt policy, retaining credentials and transport settings only."""
+ env = {key: value for key, value in os.environ.items() if not key.upper().startswith(("UV_", "PIP_", "PIPX_"))
+ or key in _TRANSPORT_SETTINGS or (key.startswith("UV_INDEX_") and key.endswith(("_USERNAME", "_PASSWORD")))}
+ env.update(UV_TOOL_DIR=str(tools), UV_TOOL_BIN_DIR=str(binaries), UV_CACHE_DIR=str(cache),
+ UV_NO_PROGRESS="1", UV_PYTHON_DOWNLOADS="never", PYTHONDONTWRITEBYTECODE="1")
+ return env
+
+
+def _run(process: PreparationProcess, executable: str, arguments: list[str], *, env: dict[str, str], cwd: Path) -> str:
+ result = process.run(executable, arguments, kind="native", env=env, cwd=cwd)
+ if result.returncode:
+ # Index URLs, raw resolver messages and TOML parse diagnostics may carry
+ # credentials. The public job stores a stage, not these raw strings.
+ raise ValueError("Could not prepare the uv transaction; inspect the installation's manager settings")
+ return result.stdout.strip()
+
+
+def cache_digest(source: Path, *, copy_to: Path | None = None) -> str:
+ """Seal/copy a private cache without its absolute internal symlink locations.
+
+ uv writes its working cache during apply. A fresh verified copy keeps both the
+ original preparation and interrupted-update retries bound to the same inputs.
+ No shared uv cache is read, moved, rewritten or cleared by this operation.
+ """
+ root = source.resolve(strict=True)
+ if source.is_symlink() or not root.is_dir():
+ raise ValueError("Invalid private uv cache")
+ if copy_to is not None:
+ copy_to.mkdir(mode=0o700) # Never merge into an existing apply cache.
+ digest = hashlib.sha256()
+ count, size = 0, 0
+ for current, directories, files in os.walk(root, followlinks=False):
+ directories.sort()
+ files.sort()
+ for name in sorted(directories + files):
+ path = Path(current) / name
+ relative = path.relative_to(root)
+ mode = path.lstat().st_mode
+ output = copy_to / relative if copy_to is not None else None
+ count += 1
+ if count > 200_000:
+ raise ValueError("Private uv cache exceeds its entry limit")
+ if stat.S_ISLNK(mode):
+ target = path.resolve(strict=True)
+ if not target.is_relative_to(root):
+ raise ValueError("Private uv cache links outside its preparation")
+ target_name = target.relative_to(root).as_posix()
+ entry = [relative.as_posix(), "link", target_name]
+ if output is not None and copy_to is not None:
+ output.symlink_to(os.path.relpath(copy_to / target_name, output.parent),
+ target_is_directory=target.is_dir())
+ elif stat.S_ISDIR(mode):
+ entry = [relative.as_posix(), "directory"]
+ if output is not None:
+ output.mkdir(mode=0o700)
+ elif stat.S_ISREG(mode):
+ size += path.stat().st_size
+ if size > 4 * 1024**3:
+ raise ValueError("Private uv cache exceeds its size limit")
+ entry = [relative.as_posix(), "file", str(mode & 0o111), _hash_file(path)]
+ if output is not None:
+ shutil.copyfile(path, output)
+ output.chmod(0o600 | (mode & 0o111))
+ else:
+ raise ValueError("Private uv cache contains an unsupported file type")
+ digest.update((json.dumps(entry, separators=(",", ":")) + "\n").encode())
+ return digest.hexdigest()
+
+
+def _versions(process: PreparationProcess, python: str, *, prepared: bool = False) -> dict[str, str]:
+ result = process.run(python, ["-c",
+ "import json,re; from importlib.metadata import distributions; "
+ "print(json.dumps({re.sub(r'[-_.]+','-',d.metadata['Name']).lower():"
+ "[d.version,json.loads(d.read_text('direct_url.json') or '{}')] for d in distributions()}))"],
+ timeout=30)
+ if result.returncode:
+ raise ValueError("Could not inspect the prepared uv environment")
+ from urllib.parse import urlsplit
+
+ versions: dict[str, str] = {}
+ for name, value in _record(json.loads(result.stdout)).items():
+ if not isinstance(value, list):
+ raise ValueError("Invalid prepared distribution record")
+ fields = cast(list[object], value)
+ if len(fields) != 2:
+ raise ValueError("Invalid prepared distribution record")
+ versions[name] = _text(fields[0])
+ direct = _record(fields[1])
+ if prepared and direct and name != "nanobot-ai":
+ parsed = urlsplit(_text(direct.get("url")))
+ if parsed.scheme not in {"https", "http"} or not parsed.path.endswith(".whl"):
+ raise ValueError("Local or source dependencies need the uv owner's update workflow")
+ return versions
+
+
+def _remote_location(value: object) -> None:
+ from urllib.parse import urlsplit
+
+ if isinstance(value, list):
+ for item in cast(list[object], value):
+ _remote_location(item)
+ elif isinstance(value, dict):
+ _remote_location(_record(cast(dict[object, object], value)).get("url"))
+ elif urlsplit(_text(value)).scheme not in {"https", "http"}:
+ # --offline still reads local indexes/find-links. Such a directory can
+ # change the resolved target after preparation even with a sealed cache.
+ raise ValueError("Local package sources need their owner's update workflow")
+
+
+@dataclass(frozen=True)
+class UVPreparation:
+ executable: str
+ executable_sha256: str
+ manager_version: str
+ receipt_sha256: str
+ cache: str
+ cache_sha256: str
+ binaries: str
+ versions: dict[str, str]
+
+ @classmethod
+ def parse(cls, value: object) -> UVPreparation:
+ data = _record(value)
+ result = cls(_text(data["executable"]), _text(data["executable_sha256"]), _text(data["manager_version"]),
+ _text(data["receipt_sha256"]), _text(data["cache"]), _text(data["cache_sha256"]),
+ _text(data["binaries"]),
+ {name: _text(version) for name, version in _record(data["versions"]).items()})
+ if any(not re.fullmatch(r"[0-9a-f]{64}", item) for item in (
+ result.executable_sha256, result.receipt_sha256, result.cache_sha256,
+ )) or len(result.versions) > 500 or not all(
+ Path(path).is_absolute() for path in (result.executable, result.binaries)
+ ):
+ raise ValueError("Invalid uv preparation identity")
+ cache = Path(result.cache)
+ if (cache.is_absolute() or ".." in cache.parts or len(cache.parts) != 2
+ or not cache.parts[0].startswith(".uv-prepare-") or cache.parts[1] != "cache"):
+ raise ValueError("Invalid private uv cache location")
+ return result
+
+ def verify(self, environment: str, directory: Path) -> None:
+ _receipt_only_policy()
+ if _hash_file(Path(self.executable)) != self.executable_sha256:
+ raise ValueError("The uv executable changed since preparation")
+ receipt = Path(environment) / "uv-receipt.toml"
+ if receipt.is_symlink() or _hash_file(receipt) != self.receipt_sha256:
+ raise ValueError("The uv installation settings changed since preparation")
+ cache = directory / self.cache
+ if not cache.resolve().is_relative_to(directory.resolve()) or cache_digest(cache) != self.cache_sha256:
+ raise ValueError("The prepared uv cache changed")
+
+ def working_cache(self, directory: Path) -> Path:
+ attempt = Path(tempfile.mkdtemp(prefix=".uv-apply-", dir=directory)) / "cache"
+ if (cache_digest(directory / self.cache, copy_to=attempt) != self.cache_sha256
+ or cache_digest(attempt) != self.cache_sha256):
+ raise ValueError("The copied uv transaction does not match its preparation")
+ return attempt
+
+
+def prepare_uv(*, environment: str, python: str, receipt_sha256: str, app_wheel: Path,
+ version: str, extras: list[str], directory: Path, executable: str,
+ process: PreparationProcess) -> UVPreparation:
+ """Resolve in a separate tool home; never change the user's tool or receipt."""
+ _receipt_only_policy()
+ if Path(environment).resolve().name != "nanobot-ai":
+ raise ValueError("This tool layout needs the uv owner's update workflow")
+ executable = str(Path(executable).resolve(strict=True))
+ with Path(executable).open("rb") as stream:
+ magic = stream.read(4)
+ if (Path(executable).is_relative_to(Path(environment).resolve())
+ or magic not in {b"\x7fELF", b"\xcf\xfa\xed\xfe", b"\xfe\xed\xfa\xcf",
+ b"\xca\xfe\xba\xbe", b"\xbe\xba\xfe\xca",
+ b"\xca\xfe\xba\xbf", b"\xbf\xba\xfe\xca"}):
+ raise ValueError("The uv updater needs a native manager outside the environment being replaced")
+ manager_sha = _hash_file(Path(executable))
+ receipt_path = Path(environment) / "uv-receipt.toml"
+ with receipt_path.open("rb") as stream:
+ raw = stream.read(1024**2 + 1)
+ if receipt_path.is_symlink() or len(raw) > 1024**2 or hashlib.sha256(raw).hexdigest() != receipt_sha256:
+ raise ValueError("The uv receipt changed before preparation")
+ try:
+ receipt = _record(tomllib.loads(raw.decode()))
+ tool = _record(receipt["tool"])
+ if receipt.keys() != {"tool"} or tool.keys() - {"requirements", "python", "entrypoints", "options"}:
+ raise ValueError("Unsupported receipt fields")
+ requirements = tool["requirements"]
+ entries = tool["entrypoints"]
+ options = _record(tool.get("options", {}))
+ if not isinstance(requirements, list) or not isinstance(entries, list):
+ raise ValueError("Invalid receipt collections")
+ injected: list[str] = []
+ main = 0
+ for item in cast(list[object], requirements):
+ requirement = _record(item)
+ rendered = _requirement(item)
+ if re.sub(r"[-_.]+", "-", _text(requirement["name"])).lower() == "nanobot-ai":
+ main += 1
+ else:
+ injected.extend(["--with", rendered])
+ paths = [_text(_record(entry)["install-path"]) for entry in cast(list[object], entries)]
+ parents = {str(Path(path).parent) for path in paths}
+ if main != 1 or len(parents) != 1 or not all(Path(path).is_absolute() for path in paths):
+ raise ValueError("Ambiguous tool ownership")
+ if (options.get("compile-bytecode") or options.get("no-binary") or options.get("no-binary-package")
+ or options.get("link-mode") == "symlink" or options.get("keyring-provider") == "subprocess"):
+ raise ValueError("This policy requires a different native lifecycle")
+ for name in ("index", "index-url", "default-index", "extra-index-url", "find-links"):
+ if name in options:
+ _remote_location(options[name])
+ binaries = parents.pop()
+ encoded_options = "\n".join(f"{json.dumps(key)} = {_toml(value)}" for key, value in options.items())
+ except (ValueError, KeyError, TypeError):
+ raise ValueError("These uv settings need the installation owner's update workflow") from None
+ before = _versions(process, python)
+ # Unique attempts prevent an orphan preparing process from writing a cache
+ # reused by a subsequent request after its parent exits.
+ staging = Path(tempfile.mkdtemp(prefix=".uv-prepare-", dir=directory))
+ cache = staging / "cache"
+ config = staging / "uv.toml"
+ config.write_text(encoded_options, encoding="utf-8")
+ config.chmod(0o600)
+ env = uv_environment(tools=staging / "tools", binaries=staging / "bin", cache=cache)
+ manager_version = _run(process, executable, ["--version"], env=env, cwd=staging)
+ if manager_version.split()[:2] != ["uv", UV_TRANSACTION_VERSION]:
+ raise ValueError("This uv version needs the installation owner's update workflow")
+ target = "nanobot-ai" + (f"[{','.join(extras)}]" if extras else "") + " @ " + app_wheel.as_uri()
+ # --no-build is private to this disposable receipt. Supplying it to the real
+ # tool upgrade would permanently change the user's stored options.
+ _run(process, executable, ["tool", "install", "--config-file", str(config), "--python", python,
+ "--no-build", *injected, target], env=env, cwd=staging)
+ prepared_python = staging / "tools/nanobot-ai" / ("Scripts/python.exe" if os.name == "nt" else "bin/python")
+ versions = _versions(process, str(prepared_python), prepared=True)
+ if versions.get("nanobot-ai") != version:
+ raise ValueError("uv resolved a different application version")
+ if _versions(process, python) != before or receipt_path.read_bytes() != raw:
+ raise ValueError("The original uv installation changed during preparation")
+ for source_cache in cache.glob("sdists-*"):
+ if any(path.is_file() and path.stat().st_size for path in source_cache.rglob("*")):
+ raise ValueError("Source-built dependencies cannot enter the offline uv transaction")
+ for path in cache.rglob("*"):
+ if path.is_file() and not path.is_symlink():
+ with path.open("r+b") as stream:
+ os.fsync(stream.fileno())
+ result = UVPreparation(executable, manager_sha, manager_version, receipt_sha256,
+ cache.relative_to(directory).as_posix(), cache_digest(cache), binaries, versions)
+ result.verify(environment, directory)
+ return result
diff --git a/nanobot/update_worker.py b/nanobot/update_worker.py
new file mode 100644
index 000000000..8d687a6da
--- /dev/null
+++ b/nanobot/update_worker.py
@@ -0,0 +1,957 @@
+"""Standalone, offline installer worker for an already prepared update.
+
+This file and its stdlib-only helpers are copied to an immutable zipapp outside
+site-packages before mutation. The coordinator uses the base Python. Its installer and
+verification children own their runtime leases, so coordinator loss cannot release a
+lease while they are still using the installation. Only lease-protected child entrypoints
+import the installed nanobot runtime for shutdown, verification or restart.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import os
+import re
+import runpy
+import subprocess
+import sys
+import time
+from collections.abc import Generator
+from contextlib import contextmanager
+from dataclasses import asdict, dataclass
+from email.parser import BytesParser
+from enum import Enum
+from pathlib import Path
+from typing import cast
+from uuid import UUID, uuid4
+from zipfile import ZipFile
+
+from nanobot.data_access import DataLease, data_access
+from nanobot.installation_lock import (
+ FileLease,
+ InstallationBusyError,
+ file_access,
+ installation_access,
+ installation_state_dir,
+ pending_update_path,
+)
+from nanobot.update_backup import BackupSource, ensure_backup, verify_backup
+from nanobot.update_process import (
+ PreparationProcess,
+ child_leases,
+ initialize_runtime,
+ inspect_python_environment,
+ run_preparation_child,
+)
+from nanobot.update_uv import UVPreparation, uv_environment
+from nanobot.utils.atomic_file import atomic_write_lines, io_path, read_atomic_bytes
+
+_REQUEST_SCHEMA_VERSION = 4
+_MAX_REQUEST_BYTES = 16 * 1024 * 1024
+_HANDOFF_PROTOCOL = 1
+
+_PROBE = """
+import hashlib, json, re, sys
+from pathlib import Path
+from importlib.metadata import distributions, distribution, PackageNotFoundError
+root = Path(sys.prefix).resolve()
+cfg = root / 'pyvenv.cfg'
+if sys.prefix == sys.base_prefix or not cfg.is_file():
+ raise SystemExit('A dedicated virtual environment is required')
+owners = [name for name in ('uv-receipt.toml', 'pipx_metadata.json') if (root / name).exists()]
+if owners != (['uv-receipt.toml'] if manager == 'uv' else []):
+ raise SystemExit('This environment belongs to another package manager')
+if 'include-system-site-packages = true' in cfg.read_text().lower():
+ raise SystemExit('Shared system packages are not supported by this worker')
+items, versions = {}, {}
+for d in distributions():
+ name = re.sub(r'[-_.]+', '-', d.metadata['Name']).lower()
+ payload = '\\n'.join(d.read_text(f) or '' for f in ('METADATA', 'RECORD', 'direct_url.json'))
+ items[name] = hashlib.sha256(payload.encode()).hexdigest()
+ versions[name] = d.version
+try:
+ app = distribution('nanobot-ai')
+ app_version = app.version
+ app_records = {name: hashlib.sha256((app.read_text(name) or '').encode()).hexdigest()
+ for name in ('RECORD', 'direct_url.json')}
+except PackageNotFoundError:
+ app_version, app_records = '', {}
+snapshot = dict(environment=str(root), python=str(Path(sys.executable).absolute()),
+ base_python=str(Path(sys._base_executable).resolve()),
+ receipt_sha=hashlib.sha256(cfg.read_bytes()).hexdigest(), distributions=items, versions=versions,
+ app_version=app_version, app_records=app_records,
+ installer_receipt_sha=hashlib.sha256((root / 'nanobot-install.json').read_bytes()).hexdigest()
+ if (root / 'nanobot-install.json').is_file() else None,
+ manager_receipt_sha=hashlib.sha256((root / owners[0]).read_bytes()).hexdigest() if owners else None)
+"""
+
+
+def _object(value: object) -> dict[str, object]:
+ if not isinstance(value, dict):
+ raise ValueError("Expected a JSON object")
+ data = cast(dict[object, object], value)
+ if not all(isinstance(key, str) for key in data):
+ raise ValueError("Expected string record keys")
+ return cast(dict[str, object], data)
+
+
+def _text(value: object) -> str:
+ if not isinstance(value, str) or not value or len(value) > 4096:
+ raise ValueError("Expected a bounded nonempty string")
+ return value
+
+
+def _sha(value: object) -> str:
+ text = _text(value)
+ if not re.fullmatch(r"[0-9a-f]{64}", text):
+ raise ValueError("Invalid checksum")
+ return text
+
+
+def _integer(value: object) -> int:
+ if type(value) is not int or value < 0:
+ raise ValueError("Expected a nonnegative integer")
+ return value
+
+
+def read_record(path: Path, *, max_bytes: int = 1024 * 1024) -> dict[str, object]:
+ path = io_path(path)
+ if path.is_symlink():
+ raise ValueError("Invalid update record")
+ data = read_atomic_bytes(path, max_bytes=max_bytes + 1)
+ if len(data) > max_bytes:
+ raise ValueError("Update record exceeds its size limit")
+ return _object(json.loads(data))
+
+
+def write_record(path: Path, record: object, *, max_bytes: int = 1024 * 1024) -> None:
+ encoded = json.dumps(record, sort_keys=True, separators=(",", ":"))
+ if len(encoded.encode("utf-8")) + 1 > max_bytes:
+ raise ValueError("Update record exceeds its size limit")
+ atomic_write_lines(path, [encoded])
+ io_path(path).chmod(0o600)
+
+
+def verify_target_handoff(wheel: ZipFile) -> None:
+ """Read the target's declared restart contract without executing its code.
+
+ Protocol 1 covers request schema 4, protected -I -S gateway startup, scoped
+ data grants and exact-run activation. A matching package version or Python
+ filename does not establish that contract. See docs/releasing.md.
+ """
+ message = ("This release cannot use this updater's protected restart. "
+ "Use the installation owner's external update procedure instead.")
+ try:
+ wheel.getinfo("nanobot/update_restart.py")
+ entry = wheel.getinfo("nanobot/update_contract.json")
+ if entry.file_size > 4096:
+ raise ValueError(message)
+ record = _object(json.loads(wheel.read(entry)))
+ except (KeyError, ValueError, UnicodeError) as exc:
+ raise ValueError(message) from exc
+ protocols = record.get("handoff_protocols")
+ if (type(record.get("schema_version")) is not int or record["schema_version"] != 1
+ or not isinstance(protocols, list)):
+ raise ValueError(message)
+ values = cast(list[object], protocols)
+ if (not 1 <= len(values) <= 32 or not all(type(value) is int and value > 0 for value in values)
+ or _HANDOFF_PROTOCOL not in values):
+ raise ValueError(message)
+
+
+@dataclass(frozen=True)
+class EnvironmentSnapshot:
+ environment: str
+ python: str
+ base_python: str
+ receipt_sha: str
+ distributions: dict[str, str]
+ versions: dict[str, str]
+ app_version: str
+ app_records: dict[str, str]
+ manager_receipt_sha: str | None = None
+ installer_receipt_sha: str | None = None
+
+ @classmethod
+ def parse(cls, value: object) -> EnvironmentSnapshot:
+ data = _object(value)
+ version = data["app_version"]
+ if not isinstance(version, str):
+ raise ValueError("Invalid installed version")
+ return cls(_text(data["environment"]), _text(data["python"]), _text(data["base_python"]),
+ _sha(data["receipt_sha"]), {name: _sha(digest) for name, digest in
+ _object(data["distributions"]).items()},
+ {name: _text(value) for name, value in _object(data["versions"]).items()}, version,
+ {name: _sha(digest) for name, digest in _object(data["app_records"]).items()},
+ _sha(data["manager_receipt_sha"]) if data.get("manager_receipt_sha") is not None else None,
+ _sha(data["installer_receipt_sha"]) if data.get("installer_receipt_sha") is not None else None)
+
+
+def inspect_environment(python: str, *, uv: bool = False, process: PreparationProcess | None = None) -> EnvironmentSnapshot:
+ # Raw metadata diagnostics may inspect an interrupted installation, but
+ # never run concurrently with a package writer. Preparation is stricter.
+ probe = "manager = __import__('sys').argv[1]\n" + _PROBE + "\nprint(json.dumps(snapshot))\n"
+ arguments = ["-c", probe, "uv" if uv else "pip"]
+ result = (process.run(python, arguments, timeout=15) if process is not None else
+ inspect_python_environment(python, str(Path(python).parent.parent.resolve()), probe,
+ arguments=("uv" if uv else "pip",), allow_incomplete=True))
+ if result.returncode:
+ raise ValueError("Could not verify the selected package environment; use its installation owner")
+ return EnvironmentSnapshot.parse(json.loads(result.stdout))
+
+
+def current_environment(*, uv: bool = False) -> EnvironmentSnapshot:
+ """Inspect in an already initialized, lease-owning target child, without a grandchild."""
+ scope: dict[str, object] = {"manager": "uv" if uv else "pip"}
+ exec(compile(_PROBE, "<update environment probe>", "exec"), scope)
+ return EnvironmentSnapshot.parse(scope["snapshot"])
+
+
+@dataclass(frozen=True)
+class StagedWheel:
+ filename: str
+ name: str
+ version: str
+ size: int
+ sha256: str
+
+ @classmethod
+ def parse(cls, value: object) -> StagedWheel:
+ data = _object(value)
+ filename, name = _text(data["filename"]), _text(data["name"])
+ if not re.fullmatch(r"[A-Za-z0-9_.-]+\.whl", filename) or not re.fullmatch(r"[a-z0-9-]+", name):
+ raise ValueError("Invalid staged wheel name")
+ if name == "pip":
+ raise ValueError("An application update cannot replace its installer")
+ return cls(filename, name, _text(data["version"]), _integer(data["size"]), _sha(data["sha256"]))
+
+ def verify(self, directory: Path) -> Path:
+ path = directory / self.filename
+ if path.is_symlink() or path.stat().st_size != self.size:
+ raise ValueError("Staged wheel size or file type changed")
+ with path.open("rb") as stream:
+ if hashlib.file_digest(stream, "sha256").hexdigest() != self.sha256:
+ raise ValueError("Staged wheel checksum changed")
+ with ZipFile(path) as wheel:
+ names = wheel.namelist()
+ if len(names) != len(set(names)) or any(re.search(r"(^[A-Za-z]:|^/|\\|(?:^|/)\.\.(?:/|$))", name) for name in names):
+ raise ValueError("Invalid wheel paths")
+ metadata = [item for item in wheel.infolist() if item.filename.endswith(".dist-info/METADATA")]
+ if len(metadata) != 1 or metadata[0].file_size > 256 * 1024:
+ raise ValueError("Invalid wheel metadata")
+ parsed = BytesParser().parsebytes(wheel.read(metadata[0]))
+ name = re.sub(r"[-_.]+", "-", str(parsed["Name"])).lower()
+ if (name, parsed["Version"]) != (self.name, self.version):
+ raise ValueError("Staged wheel identity changed")
+ return path
+
+
+@dataclass(frozen=True)
+class WorkerSpec:
+ plan_id: str
+ plan_sha256: str
+ worker_sha256: str
+ baseline: EnvironmentSnapshot
+ version: str
+ wheels: tuple[StagedWheel, ...]
+ backup_sources: tuple[BackupSource, ...]
+ restart_profiles: tuple[str, ...] = ()
+ uv: UVPreparation | None = None
+ automatic_recovery: bool = False
+
+ @staticmethod
+ def recovery_selected(directory: Path) -> bool:
+ """Read the frozen selection for status, without probing damaged inputs."""
+ try:
+ data = read_record(directory / "request.json", max_bytes=_MAX_REQUEST_BYTES)
+ except FileNotFoundError:
+ return False # Preparation has not committed a worker request.
+ if data.get("plan_id") != directory.name:
+ raise ValueError("Update job identity mismatch")
+ return data.get("automatic_recovery") is True
+
+ @classmethod
+ def read(cls, directory: Path) -> WorkerSpec:
+ data = read_record(directory / "request.json", max_bytes=_MAX_REQUEST_BYTES)
+ if data.get("schema_version") != _REQUEST_SCHEMA_VERSION:
+ raise ValueError("Unsupported update worker request")
+ plan_id = _text(data["plan_id"])
+ if str(UUID(plan_id)) != plan_id or directory.name != plan_id:
+ raise ValueError("Update job identity mismatch")
+ raw_wheels = data["wheels"]
+ if not isinstance(raw_wheels, list):
+ raise ValueError("Invalid update wheel set")
+ wheel_values = cast(list[object], raw_wheels)
+ if not 1 <= len(wheel_values) <= 500:
+ raise ValueError("Invalid update wheel set")
+ wheels = tuple(StagedWheel.parse(value) for value in wheel_values)
+ raw_sources = data.get("backup_sources")
+ if not isinstance(raw_sources, list):
+ raise ValueError("Invalid backup scope")
+ source_values = cast(list[object], raw_sources)
+ if not 1 <= len(source_values) <= 40_000:
+ raise ValueError("Invalid backup scope")
+ sources = tuple(BackupSource.parse(value) for value in source_values)
+ participants = data.get("restart_profiles")
+ if not isinstance(participants, list):
+ raise ValueError("Invalid restart participants")
+ restart_profiles = tuple(_sha(value) for value in cast(list[object], participants))
+ if len(restart_profiles) > 1024 or len(set(restart_profiles)) != len(restart_profiles):
+ raise ValueError("Invalid restart participants")
+ automatic_recovery = data.get("automatic_recovery", False)
+ if type(automatic_recovery) is not bool:
+ raise ValueError("Invalid automatic recovery selection")
+ spec = cls(plan_id, _sha(data["plan_sha256"]), _sha(data["worker_sha256"]), EnvironmentSnapshot.parse(data["baseline"]),
+ _text(data["version"]), wheels, sources, restart_profiles,
+ UVPreparation.parse(data["uv"]) if data.get("uv") is not None else None,
+ automatic_recovery)
+ if (spec.uv is None) != (spec.baseline.manager_receipt_sha is None):
+ raise ValueError("Installer preparation does not match the environment owner")
+ if spec.uv is not None and (spec.uv.receipt_sha256 != spec.baseline.manager_receipt_sha
+ or spec.uv.versions.get("nanobot-ai") != spec.version):
+ raise ValueError("The uv preparation does not match the approved installation or target")
+ if directory.resolve() != (installation_state_dir(spec.baseline.environment) / "jobs" / plan_id).resolve():
+ raise ValueError("Update job is outside its installation state directory")
+ if len({wheel.name for wheel in wheels}) != len(wheels):
+ raise ValueError("Duplicate staged distributions")
+ if [(wheel.name, wheel.version) for wheel in wheels if wheel.name == "nanobot-ai"] != [("nanobot-ai", spec.version)]:
+ raise ValueError("Missing exact nanobot target")
+ if hashlib.sha256((directory / "plan.json").read_bytes()).hexdigest() != spec.plan_sha256:
+ raise ValueError("The approved plan changed")
+ if hashlib.sha256((directory / "worker.pyz").read_bytes()).hexdigest() != spec.worker_sha256:
+ raise ValueError("The staged update worker changed")
+ return spec
+
+ def save(self, directory: Path) -> None:
+ # Expanded profile stores may exceed the small journal/approval limit.
+ # Keep the writer and standalone reader on the same bounded contract.
+ write_record(directory / "request.json", {"schema_version": _REQUEST_SCHEMA_VERSION, **asdict(self)},
+ max_bytes=_MAX_REQUEST_BYTES)
+
+ def verify_inputs(self, directory: Path) -> None:
+ for wheel in self.wheels:
+ path = wheel.verify(directory / "wheels")
+ if self.restart_profiles and wheel.name == "nanobot-ai":
+ with ZipFile(path) as archive:
+ verify_target_handoff(archive)
+ if self.uv is not None:
+ self.uv.verify(self.baseline.environment, directory)
+
+ @contextmanager
+ def mutation_access(self) -> Generator[tuple[FileLease, DataLease]]:
+ """Hold this job's installation and data leases, in acquisition order."""
+ with (installation_access(updating=True, environment=self.baseline.environment) as installation,
+ data_access((source.path for source in self.backup_sources), updating=True, job_id=self.plan_id) as data):
+ yield installation, data
+
+
+class Phase(str, Enum):
+ PREPARATION_REQUESTED = "preparation_requested"
+ PREPARING = "preparing"
+ PREPARATION_FAILED = "preparation_failed"
+ READY = "ready"
+ CHECKING = "checking"
+ STOPPING = "stopping"
+ HANDOFF_FAILED = "handoff_failed"
+ BACKING_UP = "backing_up"
+ INSTALLING = "installing"
+ VERIFYING = "verifying"
+ INSTALLED = "installed"
+ RESTARTING = "restarting"
+ ACTIVATING = "activating"
+ FINALIZING = "finalizing"
+ RESTART_FAILED = "restart_failed"
+ SUCCEEDED = "succeeded"
+ FAILED = "failed"
+ CANCELLED = "cancelled"
+ RESTORED = "restored"
+
+
+@dataclass(frozen=True)
+class JobStatus:
+ plan_id: str
+ phase: Phase
+ attempt: int
+ mutation_started: bool
+ message: str
+ updated_at: int
+
+ @classmethod
+ def read(cls, directory: Path) -> JobStatus:
+ value = read_record(directory / "status.json")
+ mutated = value["mutation_started"]
+ if type(mutated) is not bool or value["plan_id"] != directory.name:
+ raise ValueError("Invalid update status")
+ return cls(directory.name, Phase(value["phase"]), _integer(value["attempt"]), mutated,
+ _text(value["message"]), _integer(value["updated_at"]))
+
+ def save(self, directory: Path) -> None:
+ write_record(directory / "status.json", asdict(self))
+
+ def advance(self, directory: Path, phase: Phase, message: str, *,
+ mutation_started: bool | None = None, attempt: int | None = None) -> JobStatus:
+ """Publish a phase without reconstructing the job's execution history."""
+ status = JobStatus(self.plan_id, phase, self.attempt if attempt is None else attempt,
+ self.mutation_started if mutation_started is None else mutation_started,
+ message, int(time.time()))
+ status.save(directory)
+ return status
+
+
+@dataclass(frozen=True)
+class ExecutionConfirmation:
+ """One durable user confirmation; not proof that a worker is currently alive."""
+
+ id: str
+ plan_id: str
+ request_sha256: str
+ created_at: int
+ expires_at: int
+
+ @classmethod
+ def read(cls, directory: Path) -> ExecutionConfirmation | None:
+ try:
+ value = read_record(directory / "confirmation.json", max_bytes=2048)
+ except FileNotFoundError:
+ return None
+ identifier, plan_id = _text(value["id"]), _text(value["plan_id"])
+ if UUID(identifier).hex != identifier or str(UUID(plan_id)) != plan_id or plan_id != directory.name:
+ raise ValueError("Invalid execution confirmation identity")
+ created, expires = _integer(value["created_at"]), _integer(value["expires_at"])
+ if not created < expires <= created + 900:
+ raise ValueError("Invalid execution confirmation lifetime")
+ return cls(identifier, plan_id, _sha(value["request_sha256"]), created, expires)
+
+ def save(self, directory: Path) -> None:
+ write_record(directory / "confirmation.json", asdict(self), max_bytes=2048)
+
+
+def check_approval(directory: Path, spec: WorkerSpec, *, handoff: bool = False,
+ confirmation_id: str | None = None, check_expiry: bool = True) -> dict[str, object]:
+ approval = read_record(directory / ("handoff-approval.json" if handoff else "approval.json"))
+ now = int(time.time())
+ created, expires = _integer(approval["created_at"]), _integer(approval["expires_at"])
+ if not created < expires <= created + 900 or (check_expiry and not created <= now < expires):
+ raise ValueError("Update approval expired; review this exact job again before retrying")
+ digest = hashlib.sha256((directory / "request.json").read_bytes()).hexdigest()
+ if approval.get("request_sha256") != digest or approval.get("plan_id") != spec.plan_id:
+ raise ValueError("Update approval does not match this job")
+ if confirmation_id is not None:
+ confirmation = ExecutionConfirmation.read(directory)
+ if (confirmation is None or confirmation.id != confirmation_id
+ or approval.get("confirmation_id") != confirmation_id
+ or confirmation.request_sha256 != digest or confirmation.plan_id != spec.plan_id
+ or (confirmation.created_at, confirmation.expires_at) != (created, expires)):
+ raise ValueError("Execution confirmation was replaced or revoked")
+ return approval
+
+
+def _prepare_handoff_child(directory: Path, confirmation_id: str | None = None) -> None:
+ spec = WorkerSpec.read(directory)
+ # The child imports the old application, but keeps a shared lease until it
+ # actually exits. Parent loss cannot allow another installer to replace its
+ # imports. The base-Python parent waits for this exit before changing files.
+ child_leases.enter_context(file_access(
+ installation_state_dir(spec.baseline.environment) / "handoff-child.lock", exclusive=True))
+ child_leases.enter_context(installation_access(environment=spec.baseline.environment))
+ check_approval(directory, spec, handoff=True, confirmation_id=confirmation_id)
+ initialize_runtime(spec.baseline.python, spec.baseline.environment)
+ from nanobot.update_handoff import prepare_handoff
+
+ prepare_handoff(directory)
+
+
+def _handoff(directory: Path, spec: WorkerSpec, confirmation_id: str | None = None) -> None:
+ status = JobStatus.read(directory)
+ check_approval(directory, spec, handoff=True, confirmation_id=confirmation_id)
+ status.advance(directory, Phase.CHECKING, "Rechecking the exact release and installation before shutdown", mutation_started=False)
+ subprocess.run([spec.baseline.python, "-I", "-S", str(directory / "worker.pyz"),
+ "--prepare-handoff", str(directory), *([confirmation_id] if confirmation_id else [])], check=True, timeout=300,
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+ approval = check_approval(directory, spec, handoff=True, confirmation_id=confirmation_id)
+ current = inspect_job_environment(directory, spec)
+ with spec.mutation_access():
+ check_environment(spec, repairing=False, current=current)
+ spec.verify_inputs(directory)
+ # Stopping a process did not grant installation authority. Only successful
+ # preflight, child exit and exclusive installation/data leases get here.
+ write_record(directory / "approval.json", approval)
+
+
+def check_environment(spec: WorkerSpec, *, repairing: bool, current: EnvironmentSnapshot) -> None:
+ if current.installer_receipt_sha != spec.baseline.installer_receipt_sha:
+ raise ValueError("Installer selection changed outside this update")
+ if (current.environment, current.python, current.base_python, current.receipt_sha, current.manager_receipt_sha) != (
+ spec.baseline.environment, spec.baseline.python, spec.baseline.base_python, spec.baseline.receipt_sha,
+ spec.baseline.manager_receipt_sha,
+ ):
+ raise ValueError("Installation ownership or interpreter changed")
+ changed: set[str] = {wheel.name for wheel in spec.wheels} if repairing else set()
+ targets = {wheel.name: wheel.version for wheel in spec.wheels}
+ if spec.uv is not None:
+ targets = spec.uv.versions
+ if repairing:
+ changed = set(spec.baseline.versions) | set(targets)
+ before = {name: digest for name, digest in spec.baseline.distributions.items() if name not in changed}
+ after = {name: digest for name, digest in current.distributions.items() if name not in changed}
+ if before != after:
+ raise ValueError("The package environment changed outside this update; review it before continuing")
+ if repairing:
+ for name in changed:
+ if current.versions.get(name) not in {None, spec.baseline.versions.get(name), targets.get(name)}:
+ raise ValueError("Another update changed a target package; repair cannot overwrite its version")
+
+
+def require_pending_owner(spec: WorkerSpec) -> None:
+ pending = pending_update_path(spec.baseline.environment)
+ if pending.exists() and read_record(pending).get("job_id") != spec.plan_id:
+ raise ValueError("Another incomplete update owns this installation")
+
+
+def inspect_job_environment(directory: Path, spec: WorkerSpec) -> EnvironmentSnapshot:
+ """Inspect a staged job without borrowing its caller's runtime/data leases.
+
+ Call with the worker lease held, but not exclusive runtime/data leases. The
+ child owns those while loading site and retains them through exit cleanup.
+ The caller still checks the snapshot under its final admission leases, and
+ the installer repeats that check in-process immediately before mutation.
+ """
+ result = subprocess.run([spec.baseline.python, "-I", "-S", str(directory / "worker.pyz"),
+ "--inspect", str(directory)], capture_output=True, text=True, timeout=15)
+ if result.returncode == 11:
+ raise InstallationBusyError("The update's installation or data is in use; wait for its current owner")
+ if result.returncode:
+ raise ValueError("Could not verify the selected package environment; use its installation owner")
+ return EnvironmentSnapshot.parse(json.loads(result.stdout))
+
+
+def _inspection_child(directory: Path) -> None:
+ spec = WorkerSpec.read(directory)
+ status = JobStatus.read(directory)
+ restarting = status.phase in {Phase.RESTARTING, Phase.ACTIVATING, Phase.FINALIZING, Phase.RESTART_FAILED}
+ child_leases.enter_context(installation_access(
+ updating=not restarting, allow_incomplete=restarting, environment=spec.baseline.environment))
+ # Finalization can already have released the data reservation while the
+ # verified gateway is serving requests. It only needs the runtime read lease.
+ if status.phase != Phase.FINALIZING:
+ child_leases.enter_context(data_access(
+ (source.path for source in spec.backup_sources), updating=not restarting, job_id=spec.plan_id))
+ require_pending_owner(spec)
+ initialize_runtime(spec.baseline.python, spec.baseline.environment)
+ print(json.dumps(asdict(current_environment(uv=spec.uv is not None))))
+
+
+def _installer_child(directory: Path, confirmation_id: str | None = None) -> None:
+ spec = WorkerSpec.read(directory)
+ installation, data = child_leases.enter_context(spec.mutation_access())
+ status = JobStatus.read(directory)
+ if status.phase in {Phase.INSTALLED, Phase.CANCELLED, Phase.RESTARTING,
+ Phase.ACTIVATING, Phase.FINALIZING, Phase.RESTART_FAILED, Phase.SUCCEEDED, Phase.RESTORED}:
+ raise ValueError("This update job is already finished")
+ check_approval(directory, spec, confirmation_id=confirmation_id)
+ require_pending_owner(spec)
+ initialize_runtime(spec.baseline.python, spec.baseline.environment)
+ check_environment(spec, repairing=status.mutation_started, current=current_environment(uv=spec.uv is not None))
+ spec.verify_inputs(directory)
+ wheels = [str(directory / "wheels" / wheel.filename) for wheel in spec.wheels]
+ uv_cache = None
+ if spec.uv is not None:
+ if os.name != "posix":
+ raise ValueError("Native uv lease handoff is not available on this platform")
+ uv_cache = spec.uv.working_cache(directory)
+ verify_backup(directory, spec.backup_sources, hashlib.sha256((directory / "request.json").read_bytes()).hexdigest(),
+ unchanged=not status.mutation_started)
+ pending = pending_update_path()
+ pending.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
+ data.reserve()
+ write_record(pending, {"schema_version": 2, "job_id": spec.plan_id, "version": spec.version})
+ status.advance(directory, Phase.INSTALLING, "Installing the verified package files",
+ mutation_started=True, attempt=status.attempt + 1)
+ if spec.uv is not None and uv_cache is not None:
+ # Exact-wheel override is one operation, not a rewrite of the saved
+ # requirement. Even --no-build would persist in the user's receipt.
+ plan = read_record(directory / "plan.json", max_bytes=_MAX_REQUEST_BYTES)
+ extras = plan.get("extras")
+ if not isinstance(extras, list):
+ raise ValueError("Invalid approved uv extras")
+ extra_values = cast(list[object], extras)
+ if not all(isinstance(extra, str) and re.fullmatch(r"[a-z0-9]+(?:-[a-z0-9]+)*", extra)
+ for extra in extra_values):
+ raise ValueError("Invalid approved uv extras")
+ suffix = "[" + ",".join(cast(list[str], extra_values)) + "]" if extras else ""
+ app = next(wheel for wheel in spec.wheels if wheel.name == "nanobot-ai")
+ target = "nanobot-ai" + suffix + " @ " + (directory / "wheels" / app.filename).as_uri()
+ env = uv_environment(tools=Path(spec.baseline.environment).parent,
+ binaries=Path(spec.uv.binaries), cache=uv_cache)
+ arguments = [spec.uv.executable, "tool", "upgrade", "--no-config", "--offline", "--reinstall", target]
+ with installation.inherit_for_exec(), data.inherit_for_exec():
+ os.execve(spec.uv.executable, arguments, env)
+ # Keep pip in this lease-owning process on every platform. Inherited Windows
+ # handles cannot transfer byte-range locks; a POSIX wrapper can also die
+ # before a spawned installer. Only verified local wheels are accepted, so
+ # no build child can outlive it. A separate protected child verifies afterwards.
+ arguments = ["--disable-pip-version-check", "--no-input", "install",
+ "--no-index", "--no-deps", "--only-binary=:all:", "--no-compile",
+ "--force-reinstall", *wheels]
+ # A dedicated CLI, ending in pip's SystemExit; no application or second pip
+ # call runs afterwards. Process-owned leases remain held during atexit.
+ sys.argv = ["pip", *arguments]
+ runpy.run_module("pip", run_name="__main__")
+
+
+def _verify(spec: WorkerSpec, directory: Path) -> None:
+ # The coordinator must not hold the runtime/data leases here: this child
+ # acquires its own before site/imports and keeps them through dependency
+ # checks and atexit, even if the coordinator disappears.
+ verification_id = uuid4().hex
+ env = {key: value for key, value in os.environ.items() if not key.upper().startswith("PIP_")}
+ env["PIP_CONFIG_FILE"] = os.devnull
+ result = subprocess.run([spec.baseline.python, "-I", "-S", str(directory / "worker.pyz"),
+ "--verify", str(directory), verification_id], timeout=90,
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=env)
+ if result.returncode == 10:
+ raise ValueError("The installed nanobot package does not import")
+ if result.returncode:
+ raise ValueError("Installed package or dependency verification failed")
+ try:
+ checkpoint = read_record(directory / "verification.json", max_bytes=2048)
+ except (OSError, ValueError) as exc:
+ raise ValueError("Installed package verification did not finish") from exc
+ if checkpoint.get("id") != verification_id:
+ raise ValueError("Installed package verification did not finish")
+
+
+def _verification_child(directory: Path, verification_id: str) -> None:
+ if UUID(verification_id).hex != verification_id:
+ raise ValueError("Invalid verification identity")
+ spec = WorkerSpec.read(directory)
+ installation, data = child_leases.enter_context(spec.mutation_access())
+ status = JobStatus.read(directory)
+ if not status.mutation_started or status.phase not in {Phase.VERIFYING, Phase.INSTALLED}:
+ raise ValueError("This job is not awaiting installed-package verification")
+ if read_record(pending_update_path(spec.baseline.environment)).get("job_id") != spec.plan_id:
+ raise ValueError("This job no longer owns installed-package verification")
+ spec.verify_inputs(directory)
+ initialize_runtime(spec.baseline.python, spec.baseline.environment)
+ try:
+ import nanobot
+ except Exception:
+ # A dedicated exit code preserves an actionable diagnosis without
+ # persisting arbitrary import exceptions, paths or package output.
+ raise SystemExit(10) from None
+ package = Path(nanobot.__file__).resolve()
+ if nanobot.__version__ != spec.version or not package.is_relative_to(spec.baseline.environment):
+ raise ValueError("Installed package version or location differs from the approved target")
+ app = next(wheel for wheel in spec.wheels if wheel.name == "nanobot-ai")
+ with ZipFile(directory / "wheels" / app.filename) as wheel:
+ for item in wheel.infolist():
+ if item.is_dir() or not item.filename.startswith("nanobot/"):
+ continue
+ installed = package.parent.parent / item.filename
+ if not installed.is_file() or installed.is_symlink():
+ raise ValueError("An installed application file is missing")
+ with installed.open("rb") as actual, wheel.open(item) as expected:
+ digest = hashlib.sha256()
+ while chunk := expected.read(1024 * 1024):
+ digest.update(chunk)
+ if hashlib.file_digest(actual, "sha256").digest() != digest.digest():
+ raise ValueError("Installed application files differ from the verified wheel")
+ if spec.uv is not None:
+ current = current_environment(uv=True)
+ if (current.environment, current.python, current.base_python, current.receipt_sha) != (
+ spec.baseline.environment, spec.baseline.python, spec.baseline.base_python, spec.baseline.receipt_sha,
+ ):
+ raise ValueError("uv changed the prepared interpreter or environment ownership")
+ if current.versions != spec.uv.versions:
+ raise ValueError("The installed uv dependencies differ from the prepared transaction")
+ if os.name != "posix":
+ raise ValueError("Native uv lease handoff is not available on this platform")
+ command = [spec.uv.executable, "pip", "check", "--no-config", "--no-cache", "--offline", "--python", spec.baseline.python]
+ env = uv_environment(tools=Path(spec.baseline.environment).parent,
+ binaries=Path(spec.uv.binaries), cache=directory / ".uv-check-cache")
+ # This checkpoint plus the native command's successful exit proves the
+ # verification path ran. Exit 0 from site/import hooks alone does not.
+ write_record(directory / "verification.json", {"id": verification_id}, max_bytes=2048)
+ with installation.inherit_for_exec(), data.inherit_for_exec():
+ os.execve(spec.uv.executable, command, env)
+ # Like installation, pip check runs in the same process that owns the
+ # leases, not in an unprotected subprocess of a protected wrapper.
+ sys.argv = ["pip", "check"]
+ try:
+ runpy.run_module("pip", run_name="__main__")
+ except SystemExit as exc:
+ if exc.code not in {None, 0}:
+ raise
+ write_record(directory / "verification.json", {"id": verification_id}, max_bytes=2048)
+
+
+def _approve_recovery(directory: Path, spec: WorkerSpec, status: JobStatus) -> None:
+ """Fresh local consent resumes only a previously admitted, immutable job.
+
+ Never repeats shutdown or resolves a release. Before mutation, the original
+ handoff must already have admitted this worker (approval.json). After mutation
+ the same installation/data reservation and backup remain authoritative.
+ """
+ if status.phase in {Phase.CANCELLED, Phase.PREPARATION_FAILED, Phase.PREPARING, Phase.PREPARATION_REQUESTED}:
+ raise ValueError("This job cannot be repaired; no installation was admitted")
+ check_approval(directory, spec, check_expiry=False)
+ spec.verify_inputs(directory)
+ current = inspect_job_environment(directory, spec)
+ check_environment(spec, repairing=status.mutation_started, current=current)
+ if status.mutation_started:
+ verify_backup(directory, spec.backup_sources,
+ hashlib.sha256((directory / "request.json").read_bytes()).hexdigest(), unchanged=False)
+ now = int(time.time())
+ write_record(directory / "approval.json", {
+ "plan_id": spec.plan_id,
+ "request_sha256": hashlib.sha256((directory / "request.json").read_bytes()).hexdigest(),
+ "created_at": now, "expires_at": now + 900,
+ })
+
+
+def run_job(directory: Path, *, handoff: bool = False, confirmation_id: str | None = None,
+ recover: bool = False) -> JobStatus:
+ """Execute one approved offline job. 'installed' does not mean restarted."""
+ spec = WorkerSpec.read(directory)
+ root = installation_state_dir(spec.baseline.environment)
+ with file_access(root / "worker.lock", exclusive=True):
+ if recover and (handoff or confirmation_id is not None):
+ raise ValueError("Repair cannot initiate a second shutdown handoff")
+ if confirmation_id is not None:
+ if not handoff:
+ raise ValueError("A confirmation only starts the reviewed shutdown handoff")
+ confirmation = ExecutionConfirmation.read(directory)
+ if confirmation is None or confirmation.id != confirmation_id:
+ raise ValueError("This execution confirmation is no longer current")
+ claimed = directory / "confirmation-claimed.json"
+ if claimed.exists():
+ if read_record(claimed, max_bytes=2048).get("id") != confirmation_id:
+ raise ValueError("Another execution confirmation owns this job")
+ # A duplicate or delayed launcher is history, not a retry, even
+ # if the first worker exited before updating its journal.
+ return JobStatus.read(directory)
+ check_approval(directory, spec, handoff=True, confirmation_id=confirmation_id)
+ write_record(claimed, {"id": confirmation_id}, max_bytes=2048)
+ if handoff:
+ # An orphan preflight child may still own the old runtime. Refuse a
+ # competing handoff without rewriting its durable progress.
+ with file_access(root / "handoff-child.lock", exclusive=True):
+ pass
+ status = JobStatus.read(directory)
+ if status.phase == Phase.RESTORED:
+ raise ValueError("This update was settled by service recovery; review a new update instead")
+ if status.phase == Phase.CANCELLED:
+ raise ValueError("This update job was cancelled")
+ if recover:
+ with file_access(root / "handoff-child.lock", exclusive=True):
+ if status.phase == Phase.SUCCEEDED:
+ return status
+ _approve_recovery(directory, spec, status)
+ if handoff and (status.mutation_started or status.phase not in {
+ Phase.READY, Phase.CHECKING, Phase.STOPPING, Phase.HANDOFF_FAILED,
+ }):
+ raise ValueError("Shutdown handoff requires an unmodified prepared job")
+ try:
+ if handoff:
+ spec.verify_inputs(directory)
+ _handoff(directory, spec, confirmation_id)
+ if status.phase in {Phase.RESTARTING, Phase.ACTIVATING, Phase.FINALIZING, Phase.RESTART_FAILED, Phase.SUCCEEDED}:
+ return restart_runtime(directory, spec, confirmation_id)
+ if status.phase == Phase.INSTALLED:
+ # Recover a crash after saving the result but before removing
+ # the startup fence. Verification owns independent leases.
+ with spec.mutation_access():
+ require_pending_owner(spec)
+ needs_verification = pending_update_path(spec.baseline.environment).exists()
+ if needs_verification:
+ _verify(spec, directory)
+ with spec.mutation_access() as (_, data):
+ require_pending_owner(spec)
+ pending_update_path(spec.baseline.environment).unlink(missing_ok=True)
+ data.release_reservation()
+ return status
+ check_approval(directory, spec, confirmation_id=confirmation_id)
+ current = inspect_job_environment(directory, spec)
+ with spec.mutation_access() as (_, data):
+ require_pending_owner(spec)
+ check_approval(directory, spec, confirmation_id=confirmation_id)
+ check_environment(spec, repairing=status.mutation_started, current=current)
+ spec.verify_inputs(directory)
+ if not status.mutation_started:
+ from nanobot.update_fallback import preserve_program
+
+ preserve_program(directory, spec)
+ status.advance(directory, Phase.BACKING_UP, "Preserving the original scoped data backup")
+ ensure_backup(directory, spec.backup_sources,
+ hashlib.sha256((directory / "request.json").read_bytes()).hexdigest(),
+ mutated=status.mutation_started)
+ # Block shared-data writers too, including a different Python
+ # installation, across handoff and interrupted-job recovery.
+ data.reserve()
+ pending = pending_update_path(spec.baseline.environment)
+ pending.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
+ write_record(pending, {"schema_version": 2, "job_id": spec.plan_id, "version": spec.version})
+ env = {key: value for key, value in os.environ.items() if not key.upper().startswith("PIP_")}
+ env["PIP_CONFIG_FILE"] = os.devnull
+ subprocess.run([spec.baseline.python, "-I", "-S", str(directory / "worker.pyz"),
+ "--install", str(directory), *([confirmation_id] if confirmation_id else [])], check=True, timeout=900,
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=env)
+ with spec.mutation_access():
+ status = JobStatus.read(directory)
+ status.advance(directory, Phase.VERIFYING, "Checking the installed package and dependencies", mutation_started=True)
+ _verify(spec, directory)
+ with spec.mutation_access() as (_, data):
+ require_pending_owner(spec)
+ status = status.advance(directory, Phase.RESTARTING if spec.restart_profiles else Phase.INSTALLED,
+ "Files installed and checked; running gateway not yet verified", mutation_started=True)
+ if not spec.restart_profiles:
+ pending_update_path(spec.baseline.environment).unlink()
+ data.release_reservation()
+ return status
+ return restart_runtime(directory, spec, confirmation_id)
+ except InstallationBusyError:
+ # An orphan pip child may still be alive. Do not turn its ongoing
+ # installation into a terminal failure or overwrite its journal.
+ current = JobStatus.read(directory)
+ if handoff and current.phase in {Phase.CHECKING, Phase.STOPPING} and not current.mutation_started:
+ current.advance(directory, Phase.HANDOFF_FAILED,
+ "Update handoff could not acquire exclusive access; no package files were changed", mutation_started=False)
+ raise
+ except Exception as exc:
+ status = JobStatus.read(directory)
+ if status.phase in {Phase.FINALIZING, Phase.SUCCEEDED}:
+ # Runtime success was durably verified. Retry only final cleanup,
+ # never demote it to a restart or package-repair transaction.
+ raise
+ # Do not persist arbitrary package-manager output, URLs or credentials.
+ message = str(exc) if isinstance(exc, (ValueError, InstallationBusyError)) else f"Update failed ({type(exc).__name__})"
+ handoff_failed = status.phase in {Phase.CHECKING, Phase.STOPPING, Phase.HANDOFF_FAILED}
+ if handoff_failed:
+ # The old runtime may already have exited. Never imply that a
+ # pre-install failure undoes a durable shutdown commitment.
+ message = (status.message if status.phase == Phase.HANDOFF_FAILED else
+ "Update handoff did not finish; review the saved shutdown state before retrying")
+ phase = Phase.HANDOFF_FAILED if handoff_failed else (
+ Phase.RESTART_FAILED if status.phase in {
+ Phase.RESTARTING, Phase.ACTIVATING, Phase.RESTART_FAILED,
+ } else Phase.FAILED
+ )
+ status.advance(directory, phase, message[:1000])
+ if not status.mutation_started and not handoff_failed:
+ with spec.mutation_access() as (_, data):
+ require_pending_owner(spec)
+ pending_update_path(spec.baseline.environment).unlink(missing_ok=True)
+ data.release_reservation()
+ raise
+
+
+def restart_runtime(directory: Path, spec: WorkerSpec, confirmation_id: str | None = None) -> JobStatus:
+ # Use the target Python, but enter through frozen stdlib code so its shared
+ # installation lease is held before importing the mutable target runtime.
+ subprocess.run([spec.baseline.python, "-I", "-S", str(directory / "worker.pyz"),
+ "--restart", str(directory), *([confirmation_id] if confirmation_id else [])], check=True, timeout=300,
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+ result = JobStatus.read(directory)
+ if result.phase not in {Phase.SUCCEEDED, Phase.RESTORED}:
+ raise ValueError("Runtime handoff did not verify the updated gateways")
+ return result
+
+
+def _runtime_child(directory: Path, participant: str | None = None, confirmation_id: str | None = None) -> None:
+ spec = WorkerSpec.read(directory)
+ if not spec.restart_profiles or (participant is not None and participant not in spec.restart_profiles):
+ raise ValueError("This gateway is not a reviewed restart participant")
+ child_leases.enter_context(installation_access(allow_incomplete=True, environment=spec.baseline.environment))
+ require_pending_owner(spec)
+ if confirmation_id is not None:
+ # Completion can take longer than consent's launch window. Bind the
+ # identity, without treating elapsed time as a reason to reinstall.
+ check_approval(directory, spec, confirmation_id=confirmation_id, check_expiry=False)
+ initialize_runtime(spec.baseline.python, spec.baseline.environment)
+ # Deliberately import the installed application, not a frozen stub.
+ if (directory / "restoration.json").exists():
+ # Recovery uses the original frozen restart implementation. An older
+ # installed package need not understand the newer recovery journal.
+ from .update_restart import run_gateway, run_restarts
+ else:
+ import importlib
+
+ restart = importlib.import_module("nanobot.update_restart")
+ run_gateway, run_restarts = restart.run_gateway, restart.run_restarts
+
+ if participant is None:
+ run_restarts(directory)
+ else:
+ run_gateway(directory, participant)
+
+
+def cancel_job(directory: Path) -> JobStatus:
+ """Cancel only a stopped, unmodified job; never terminate an installer."""
+ spec = WorkerSpec.read(directory)
+ with file_access(installation_state_dir(spec.baseline.environment) / "worker.lock", exclusive=True):
+ with spec.mutation_access() as (_, data):
+ status = JobStatus.read(directory)
+ if status.mutation_started:
+ raise ValueError("Installation has begun; this job needs verification or repair, not cancellation")
+ require_pending_owner(spec)
+ pending_update_path(spec.baseline.environment).unlink(missing_ok=True)
+ data.release_reservation()
+ status = status.advance(directory, Phase.CANCELLED, "Cancelled; installed files were not changed", mutation_started=False)
+ (directory / "approval.json").unlink(missing_ok=True)
+ return status
+
+
+def main() -> None:
+ if len(sys.argv) >= 4 and sys.argv[1] == "--supervise":
+ from nanobot.update_fallback import supervise
+
+ supervise(Path(sys.argv[2]).resolve(), sys.argv[3:])
+ return
+ if len(sys.argv) == 3 and sys.argv[1] == "--inspect":
+ try:
+ _inspection_child(Path(sys.argv[2]).resolve())
+ except InstallationBusyError:
+ raise SystemExit(11) from None
+ return
+ if len(sys.argv) == 3 and sys.argv[1] == "--prepare-native":
+ run_preparation_child(Path(sys.argv[2]).resolve())
+ return
+ if len(sys.argv) in {3, 4} and sys.argv[1] == "--prepare-handoff":
+ _prepare_handoff_child(Path(sys.argv[2]).resolve(), sys.argv[3] if len(sys.argv) == 4 else None)
+ return
+ if len(sys.argv) in {3, 4} and sys.argv[1] == "--restart":
+ _runtime_child(Path(sys.argv[2]).resolve(), confirmation_id=sys.argv[3] if len(sys.argv) == 4 else None)
+ return
+ if len(sys.argv) == 4 and sys.argv[1] == "--gateway":
+ _runtime_child(Path(sys.argv[2]).resolve(), sys.argv[3])
+ return
+ if len(sys.argv) in {3, 4} and sys.argv[1] == "--install":
+ _installer_child(Path(sys.argv[2]).resolve(), sys.argv[3] if len(sys.argv) == 4 else None)
+ return
+ if len(sys.argv) == 4 and sys.argv[1] == "--verify":
+ _verification_child(Path(sys.argv[2]).resolve(), sys.argv[3])
+ return
+ if len(sys.argv) == 3 and sys.argv[1] in {"--status", "--cancel"}:
+ directory = Path(sys.argv[2]).resolve()
+ WorkerSpec.read(directory)
+ status = cancel_job(directory) if sys.argv[1] == "--cancel" else JobStatus.read(directory)
+ print(json.dumps(asdict(status)))
+ return
+ recover = len(sys.argv) == 3 and sys.argv[1] == "--recover"
+ handoff = len(sys.argv) == 3 and sys.argv[1] == "--handoff"
+ confirmed = len(sys.argv) == 4 and sys.argv[1] == "--confirmed-handoff"
+ if len(sys.argv) != 2 and not handoff and not confirmed and not recover:
+ raise SystemExit("Use this worker with its exact saved job directory")
+ directory = Path(sys.argv[2] if handoff or confirmed or recover else sys.argv[1]).resolve()
+ try:
+ result = run_job(directory, handoff=handoff or confirmed, confirmation_id=sys.argv[3] if confirmed else None,
+ recover=recover)
+ except (OSError, ValueError, RuntimeError, subprocess.SubprocessError) as exc:
+ print(f"Update did not finish: {type(exc).__name__}. Consult the saved job status.", file=sys.stderr)
+ raise SystemExit(1) from exc
+ print(json.dumps(asdict(result)))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/nanobot/utils/atomic_file.py b/nanobot/utils/atomic_file.py
new file mode 100644
index 000000000..3bc20cb55
--- /dev/null
+++ b/nanobot/utils/atomic_file.py
@@ -0,0 +1,173 @@
+"""Standard-library atomic record replacement, also used by the update worker."""
+
+from __future__ import annotations
+
+import errno
+import os
+import uuid
+from collections.abc import Iterable
+from contextlib import suppress
+from pathlib import Path
+from typing import BinaryIO
+
+
+def io_path(path: Path) -> Path:
+ """Use Windows' extended namespace for I/O, without changing stored identities."""
+ if os.name != "nt":
+ return path
+ name = str(path)
+ if name.startswith(("\\\\?\\", "\\\\.\\")):
+ return path
+ # Extended paths bypass Win32 normalization and must be absolute. Normalize
+ # ordinary relative paths, separators and dot segments before adding a prefix.
+ name = os.path.abspath(name)
+ if name.startswith("\\\\"):
+ return Path("\\\\?\\UNC\\" + name[2:])
+ return Path("\\\\?\\" + name)
+
+
+def _open_snapshot(path: Path) -> BinaryIO:
+ """Read one inode without preventing its atomic replacement on Windows."""
+ if os.name != "nt":
+ return path.open("rb")
+ import ctypes
+ import msvcrt
+ from ctypes import wintypes
+
+ kernel = ctypes.WinDLL("kernel32", use_last_error=True)
+ create = kernel.CreateFileW
+ create.argtypes = [wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD,
+ wintypes.LPVOID, wintypes.DWORD, wintypes.DWORD, wintypes.HANDLE]
+ create.restype = wintypes.HANDLE
+ close = kernel.CloseHandle
+ close.argtypes = [wintypes.HANDLE]
+ close.restype = wintypes.BOOL
+ # GENERIC_READ; FILE_SHARE_READ | WRITE | DELETE; OPEN_EXISTING.
+ # Python's normal open omits SHARE_DELETE. Pair this handle with the POSIX
+ # rename below so a short status poll cannot block journal commits.
+ handle = create(str(io_path(path)), 0x80000000, 1 | 2 | 4, None, 3, 0x80, None)
+ if handle == wintypes.HANDLE(-1).value:
+ raise ctypes.WinError(ctypes.get_last_error())
+ try:
+ descriptor = msvcrt.open_osfhandle(handle, os.O_RDONLY | os.O_BINARY)
+ except BaseException:
+ close(handle)
+ raise
+ # open_osfhandle transfers handle ownership to the file descriptor.
+ return os.fdopen(descriptor, "rb")
+
+
+def replace_atomic(source: Path, destination: Path) -> None:
+ """Publish a new inode while existing snapshot readers retain the old one."""
+ if os.name != "nt":
+ os.replace(source, destination)
+ return
+ source, destination = io_path(source), io_path(destination)
+ import ctypes
+ from ctypes import wintypes
+
+ class RenameInfo(ctypes.Structure):
+ _fields_ = [("Flags", wintypes.DWORD), ("RootDirectory", wintypes.HANDLE),
+ ("FileNameLength", wintypes.DWORD), ("FileName", wintypes.WCHAR * 1)]
+
+ # MoveFileExW (Python's os.replace) rejects an open destination even when
+ # readers share DELETE. FileRenameInfoEx provides atomic POSIX replacement
+ # on modern Windows: old readers keep their snapshot, new readers see this
+ # commit. Do not unlink first or fall back to copying a partially written file.
+ kernel = ctypes.WinDLL("kernel32", use_last_error=True)
+ create = kernel.CreateFileW
+ create.argtypes = [wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD,
+ wintypes.LPVOID, wintypes.DWORD, wintypes.DWORD, wintypes.HANDLE]
+ create.restype = wintypes.HANDLE
+ rename = kernel.SetFileInformationByHandle
+ rename.argtypes = [wintypes.HANDLE, ctypes.c_int, wintypes.LPVOID, wintypes.DWORD]
+ rename.restype = wintypes.BOOL
+ close = kernel.CloseHandle
+ close.argtypes = [wintypes.HANDLE]
+ close.restype = wintypes.BOOL
+ # DELETE | SYNCHRONIZE; share READ | WRITE | DELETE; OPEN_EXISTING.
+ handle = create(str(source), 0x10000 | 0x100000, 1 | 2 | 4, None, 3, 0x80, None)
+ if handle == wintypes.HANDLE(-1).value:
+ raise ctypes.WinError(ctypes.get_last_error())
+ unsupported = False
+ try:
+ name = str(destination).encode("utf-16-le")
+ buffer = ctypes.create_string_buffer(ctypes.sizeof(RenameInfo) + len(name))
+ info = RenameInfo.from_buffer(buffer)
+ info.Flags = 1 | 2 # REPLACE_IF_EXISTS | POSIX_SEMANTICS (not IGNORE_READONLY).
+ info.FileNameLength = len(name)
+ ctypes.memmove(ctypes.addressof(buffer) + RenameInfo.FileName.offset, name, len(name))
+ if not rename(handle, 22, buffer, len(buffer)): # FileRenameInfoEx
+ error = ctypes.get_last_error()
+ # Older Windows/filesystems can lack this information class. Keep
+ # their existing atomic rename behavior, never a delete/copy gap.
+ # Sharing/permission errors are not treated as missing capability.
+ if error not in (1, 50, 87): # INVALID_FUNCTION, NOT_SUPPORTED, INVALID_PARAMETER
+ raise ctypes.WinError(error)
+ unsupported = True
+ finally:
+ close(handle)
+ if unsupported:
+ os.replace(source, destination)
+
+
+def read_atomic_bytes(path: Path, *, max_bytes: int = -1) -> bytes:
+ """Read a snapshot while permitting writers to atomically publish the next."""
+ with _open_snapshot(path) as stream:
+ return stream.read(max_bytes)
+
+
+def _fsync_directory_after_replace(directory: Path) -> None:
+ """Fsync a directory, ignoring only unsupported platforms/filesystems."""
+ with suppress(PermissionError):
+ fd = os.open(str(directory), os.O_RDONLY)
+ try:
+ try:
+ os.fsync(fd)
+ except OSError as exc:
+ if exc.errno != errno.EINVAL:
+ raise
+ finally:
+ os.close(fd)
+
+
+def atomic_write_text(path: Path, content: str) -> None:
+ """Create parent directories and durably replace exact UTF-8 text."""
+ path = io_path(path)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ tmp = path.with_name(f".{path.name}.{uuid.uuid4().hex}.tmp")
+ try:
+ with open(tmp, "x", encoding="utf-8") as handle:
+ handle.write(content)
+ handle.flush()
+ os.fsync(handle.fileno())
+ replace_atomic(tmp, path)
+ _fsync_directory_after_replace(path.parent)
+ finally:
+ tmp.unlink(missing_ok=True)
+
+
+def atomic_write_lines(path: Path, lines: Iterable[str], *, fsync: bool = True) -> None:
+ """Replace serialized records, optionally syncing both file and directory.
+
+ A unique sibling is flushed before replacement and cleaned on every failure.
+ Directory fsync tolerates Windows permission errors and unsupported filesystems,
+ but propagates other I/O failures. Existing callers retain their durability choice.
+ """
+ path = io_path(path)
+ tmp = path.with_name(f".{path.name}.{uuid.uuid4().hex}.tmp")
+ try:
+ # Stable bytes across platforms: callers hash records and bound their
+ # encoded size, so Windows newline translation would break the contract.
+ with open(tmp, "x", encoding="utf-8", newline="\n") as handle:
+ for line in lines:
+ handle.write(line if line.endswith("\n") else f"{line}\n")
+ if fsync:
+ handle.flush()
+ os.fsync(handle.fileno())
+ replace_atomic(tmp, path)
+ if fsync:
+ _fsync_directory_after_replace(path.parent)
+ finally:
+ if tmp.exists():
+ tmp.unlink(missing_ok=True)
diff --git a/nanobot/utils/helpers.py b/nanobot/utils/helpers.py
index 1573f7d6a..3cd078212 100644
--- a/nanobot/utils/helpers.py
+++ b/nanobot/utils/helpers.py
@@ -3,14 +3,10 @@
from __future__ import annotations
import base64
-import errno
import json
-import os
import re
import shutil
import time
-import uuid
-from collections.abc import Iterable
from contextlib import suppress
from datetime import datetime
from pathlib import Path
@@ -19,6 +15,8 @@ from typing import TYPE_CHECKING, Any, TypeVar, cast, overload
from loguru import logger
+from nanobot.utils.atomic_file import atomic_write_lines as atomic_write_lines
+from nanobot.utils.atomic_file import atomic_write_text as atomic_write_text
from nanobot.utils.file_io import ensure_dir as ensure_dir
from nanobot.utils.file_io import write_text_atomic as _write_text_atomic
from nanobot.utils.token_encoding import get_token_encoding as _get_token_encoding
@@ -554,67 +552,6 @@ def _cleanup_tool_result_buckets(root: Path, current_bucket: Path) -> None:
shutil.rmtree(path, ignore_errors=True)
-def atomic_write_text(path: Path, content: str) -> None:
- """Create parent directories and durably replace *path* with UTF-8 text."""
- path.parent.mkdir(parents=True, exist_ok=True)
- tmp_path = path.with_name(f".{path.name}.{uuid.uuid4().hex}.tmp")
- try:
- with open(tmp_path, "w", encoding="utf-8") as handle:
- handle.write(content)
- handle.flush()
- os.fsync(handle.fileno())
- os.replace(tmp_path, path)
- _fsync_directory_after_replace(path.parent)
- except BaseException:
- tmp_path.unlink(missing_ok=True)
- raise
-
-
-def atomic_write_lines(path: Path, lines: Iterable[str], *, fsync: bool = True) -> None:
- """Atomically replace *path* with already-serialized record lines.
-
- Each item is one record. A trailing newline is added when the item does
- not already end with one. The bytes are written to a uniquely named temp
- file in the same directory, then published with ``os.replace``.
-
- ``fsync=True`` (the default) flushes and fsyncs the file before the
- replace, then fsyncs the parent directory. ``fsync=False`` skips both,
- which session saves use when the caller does not ask for durability.
- Directory fsync suppresses ``PermissionError`` (Windows cannot open a
- directory this way) and ``EINVAL`` (filesystems that reject directory
- fsync). Any other directory fsync error propagates. The temp file is
- removed on every ``BaseException``.
- """
- tmp = path.with_name(f".{path.name}.{uuid.uuid4().hex}.tmp")
- try:
- with open(tmp, "x", encoding="utf-8") as handle:
- for line in lines:
- handle.write(line if line.endswith("\n") else f"{line}\n")
- if fsync:
- handle.flush()
- os.fsync(handle.fileno())
- os.replace(tmp, path)
- if fsync:
- _fsync_directory_after_replace(path.parent)
- finally:
- if tmp.exists():
- tmp.unlink(missing_ok=True)
-
-
-def _fsync_directory_after_replace(directory: Path) -> None:
- """Fsync *directory* after a replace, ignoring unsupported platforms."""
- with suppress(PermissionError):
- fd = os.open(str(directory), os.O_RDONLY)
- try:
- try:
- os.fsync(fd)
- except OSError as exc:
- if exc.errno != errno.EINVAL:
- raise
- finally:
- os.close(fd)
-
-
def maybe_persist_tool_result(
workspace: Path | None,
session_key: str | None,
diff --git a/nanobot/webui/build.py b/nanobot/webui/build.py
index 6129aa425..07f36d1b0 100644
--- a/nanobot/webui/build.py
+++ b/nanobot/webui/build.py
@@ -6,11 +6,13 @@ import os
import shutil
import subprocess
from collections.abc import Callable, Mapping
-from contextlib import suppress
+from contextlib import nullcontext, suppress
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Literal
+from nanobot.bun import BunUnavailableError, bun_environment, ensure_bun
+
BuildMode = Literal["auto", "prompt", "warn", "skip"]
_SOURCE_TOP_LEVEL_FILES = (
@@ -194,21 +196,20 @@ def build_webui_bundle(
) -> WebUIBundleStatus:
"""Install frontend dependencies and build the WebUI bundle."""
resolved_source = source_dir or default_webui_source_dir()
- command_runner = runner or pick_webui_build_runner()
- if command_runner is None:
- raise WebUIBuildError(
- "neither `bun` nor `npm` is available on PATH; install one or run "
- "`cd webui && bun run build` manually"
- )
+ try:
+ command_runner = runner or pick_webui_build_runner() or ensure_bun(output=output or print)
+ except BunUnavailableError as exc:
+ raise WebUIBuildError(str(exc)) from exc
+ using_bun = Path(command_runner).stem.lower() == "bun"
_emit(output, f"Building bundled WebUI with `{command_runner}`...")
_run_frontend_command(
- [command_runner, "install"],
+ [command_runner, "install", *(["--frozen-lockfile"] if using_bun else [])],
cwd=resolved_source,
subprocess_run=subprocess_run,
)
_run_frontend_command(
- [command_runner, "run", "build"],
+ [command_runner, *(["--bun"] if using_bun else []), "run", "build"],
cwd=resolved_source,
subprocess_run=subprocess_run,
)
@@ -281,13 +282,20 @@ def _run_frontend_command(
subprocess_run: Callable[..., subprocess.CompletedProcess[Any]],
) -> None:
try:
- subprocess_run(command, cwd=cwd, check=True)
+ environment = (
+ bun_environment(command[0])
+ if Path(command[0]).stem.lower() == "bun" else nullcontext(os.environ.copy())
+ )
+ with environment as env:
+ subprocess_run(command, cwd=cwd, check=True, env=env, timeout=900)
except subprocess.CalledProcessError as exc:
raise WebUIBuildError(
f"command failed ({exc.returncode}): {' '.join(command)}"
) from exc
except OSError as exc:
raise WebUIBuildError(f"command failed: {' '.join(command)} ({exc})") from exc
+ except subprocess.TimeoutExpired as exc:
+ raise WebUIBuildError(f"command timed out: {' '.join(command)}") from exc
def _display_source_path(status: WebUIBundleStatus) -> str:
diff --git a/nanobot/webui/client_contract.py b/nanobot/webui/client_contract.py
index e985285cf..913afb247 100644
--- a/nanobot/webui/client_contract.py
+++ b/nanobot/webui/client_contract.py
@@ -18,6 +18,14 @@ SUBAGENT_EVENTS_CAPABILITY = "webui.subagents.events.v1"
SUBAGENT_HISTORY_CAPABILITY = "webui.subagents.history.v1"
AUTOMATION_CHAT_CAPABILITY = "webui.automation-chat.v1"
BINARY_ATTACHMENTS_CAPABILITY = "webui.attachments.binary.v1"
+UPDATE_PLAN_CAPABILITY = "webui.update-plans.v1"
+UPDATE_JOB_CAPABILITY = "webui.update-jobs.read.v1"
+UPDATE_PREPARATION_CAPABILITY = "webui.update-jobs.prepare.v1"
+UPDATE_EXECUTION_CAPABILITY = "webui.update-jobs.execute.v1"
+UPDATE_RETRY_CAPABILITY = "webui.update-jobs.retry-handoff.v1"
+UPDATE_SETTLE_HANDOFF_CAPABILITY = "webui.update-jobs.settle-handoff.v1"
+UPDATE_FLOW_CAPABILITY = "webui.update-flow.v1"
+UPDATE_CHANNEL_CAPABILITY = "webui.update-channels.v1"
PROMPT_NAVIGATION_CAPABILITY = "webui.prompt-navigation.v1"
@@ -35,7 +43,10 @@ def webui_contract() -> dict[str, object]:
"capabilities": [
CORE_CAPABILITY, SUBAGENT_CAPABILITY, SUBAGENT_EVENTS_CAPABILITY,
SUBAGENT_HISTORY_CAPABILITY, AUTOMATION_CHAT_CAPABILITY,
- BINARY_ATTACHMENTS_CAPABILITY, PROMPT_NAVIGATION_CAPABILITY,
+ BINARY_ATTACHMENTS_CAPABILITY, UPDATE_PLAN_CAPABILITY,
+ UPDATE_JOB_CAPABILITY, UPDATE_PREPARATION_CAPABILITY, UPDATE_EXECUTION_CAPABILITY,
+ UPDATE_RETRY_CAPABILITY, UPDATE_SETTLE_HANDOFF_CAPABILITY, UPDATE_FLOW_CAPABILITY, UPDATE_CHANNEL_CAPABILITY,
+ PROMPT_NAVIGATION_CAPABILITY,
],
}
diff --git a/nanobot/webui/gateway_endpoint.py b/nanobot/webui/gateway_endpoint.py
index 49b5d870c..3aebddb74 100644
--- a/nanobot/webui/gateway_endpoint.py
+++ b/nanobot/webui/gateway_endpoint.py
@@ -4,11 +4,13 @@ from __future__ import annotations
import hmac
from collections.abc import Callable
+from http import HTTPStatus
from typing import TYPE_CHECKING, Any
from websockets.asyncio.server import ServerConnection
from websockets.http11 import Request as WsRequest
+from nanobot.runtime_admission import RuntimeMaintenanceError
from nanobot.webui.gateway_tokens import GatewayTokenStore
from nanobot.webui.http_utils import (
is_trusted_proxy_authenticated_request,
@@ -57,6 +59,10 @@ class WebUIGatewayEndpoint:
is_allowed: Callable[[str], bool],
) -> Any:
"""Route one listener request to a WS handshake or the HTTP application."""
+ try:
+ self._http.bus.admission.check()
+ except RuntimeMaintenanceError:
+ return connection.respond(HTTPStatus.SERVICE_UNAVAILABLE, "Gateway update is being verified. Retry shortly.\n")
got, query = parse_request_path(request.path)
expected_ws = normalize_config_path(self._config.path)
if got == expected_ws and is_websocket_upgrade(request):
diff --git a/nanobot/webui/mcp_oauth_api.py b/nanobot/webui/mcp_oauth_api.py
index 49a43bb4d..a4c54b759 100644
--- a/nanobot/webui/mcp_oauth_api.py
+++ b/nanobot/webui/mcp_oauth_api.py
@@ -16,6 +16,7 @@ from nanobot.agent.tools.mcp import MCPConnection, connect_mcp_servers
from nanobot.agent.tools.mcp_oauth import MCP_OAUTH_CALLBACK_PATH, MCPOAuthHandlers
from nanobot.agent.tools.registry import ToolRegistry
from nanobot.config.schema import MCPServerConfig
+from nanobot.runtime_admission import RuntimeAdmission
from nanobot.security.network import validate_url_target
from nanobot.webui.http_utils import is_loopback_host
@@ -100,9 +101,36 @@ def prepare_mcp_oauth_redirect_uri(redirect_uri: str) -> tuple[str, bool]:
class McpOAuthManager:
"""Own short-lived browser flows while the gateway process is running."""
- def __init__(self) -> None:
+ def __init__(self, admission: RuntimeAdmission) -> None:
+ self._admission = admission
self._flows: dict[str, _McpOAuthFlow] = {}
self._states: dict[str, str] = {}
+ self._tasks: set[asyncio.Task[bool]] = set()
+ self._cleanup_tasks: set[asyncio.Task[None]] = set()
+ self._remove_pending_work: Callable[[], None] | None = None
+
+ async def close(self) -> None:
+ """Join authorization work after the owner has stopped request intake."""
+ tasks = tuple(self._tasks)
+ for task in tasks:
+ if not task.done() and not task.cancelling():
+ task.cancel()
+ if tasks:
+ await asyncio.gather(*tasks, return_exceptions=True)
+ if self._cleanup_tasks:
+ await asyncio.shield(asyncio.gather(*tuple(self._cleanup_tasks)))
+ self._flows.clear()
+ self._states.clear()
+ if self._remove_pending_work is not None:
+ self._remove_pending_work()
+ self._remove_pending_work = None
+
+ def _flow_finished(self, task: asyncio.Task[bool]) -> None:
+ self._tasks.discard(task)
+ # An expired flow no longer has a status consumer, but still owns its
+ # task until connection cleanup finishes. Observe any terminal error.
+ if not task.cancelled():
+ task.exception()
async def start(
self,
@@ -113,9 +141,15 @@ class McpOAuthManager:
reload_mcp: McpReload,
reset_credentials: bool = False,
) -> dict[str, Any]:
+ self._admission.check()
self._prune()
redirect_uri, manual_callback = prepare_mcp_oauth_redirect_uri(redirect_uri)
await self._cancel_name(name)
+ self._admission.check()
+ if self._remove_pending_work is None:
+ self._remove_pending_work = self._admission.register_pending_work(
+ lambda: bool(self._tasks or self._cleanup_tasks),
+ )
loop = asyncio.get_running_loop()
now = time.monotonic()
@@ -139,6 +173,8 @@ class McpOAuthManager:
self._connect_and_reload(flow, handlers, reload_mcp),
name=f"mcp-oauth:{name}",
)
+ self._tasks.add(flow.task)
+ flow.task.add_done_callback(self._flow_finished)
ready_waiter = asyncio.create_task(flow.authorization_ready.wait())
try:
@@ -287,11 +323,21 @@ class McpOAuthManager:
flow.error = "MCP authorization timed out."
raise _OAuthCallbackError(flow.error) from exc
- @staticmethod
- async def _close_connections(connections: dict[str, MCPConnection]) -> None:
- for connection in connections.values():
- with suppress(Exception):
- await connection.aclose()
+ async def _close_connections(self, connections: dict[str, MCPConnection]) -> None:
+ if not connections:
+ return
+
+ async def close_all() -> None:
+ for connection in connections.values():
+ with suppress(Exception):
+ await connection.aclose()
+
+ # Cancelling/expiring the browser flow must not interrupt a transport
+ # close already in progress. Keep ownership until it actually finishes.
+ cleanup = asyncio.create_task(close_all(), name="mcp-oauth-cleanup")
+ self._cleanup_tasks.add(cleanup)
+ cleanup.add_done_callback(self._cleanup_tasks.discard)
+ await asyncio.shield(cleanup)
async def _connect(
self, flow: _McpOAuthFlow, handlers: MCPOAuthHandlers
@@ -406,7 +452,8 @@ class McpOAuthManager:
self._states.pop(flow.state, None)
task = flow.task
if task is not None and not task.done():
- task.cancel()
+ if not task.cancelling():
+ task.cancel()
with suppress(BaseException):
await task
@@ -417,7 +464,7 @@ class McpOAuthManager:
continue
if flow.state:
self._states.pop(flow.state, None)
- if flow.task is not None and not flow.task.done():
+ if flow.task is not None and not flow.task.done() and not flow.task.cancelling():
flow.task.cancel()
callback_result = flow.callback_result
if callback_result is not None and not callback_result.done():
diff --git a/nanobot/webui/settings_models.py b/nanobot/webui/settings_models.py
index 10757e62a..1f1252ab8 100644
--- a/nanobot/webui/settings_models.py
+++ b/nanobot/webui/settings_models.py
@@ -49,6 +49,7 @@ from nanobot.providers.registry import (
)
from nanobot.providers.request_overrides import isolate_request_overrides
from nanobot.providers.routing import resolve_automatic_model_api, resolve_model_api
+from nanobot.runtime_admission import RuntimeAdmission
from nanobot.webui import request_settings
from nanobot.webui.settings_contracts import (
QueryParams,
@@ -1724,7 +1725,7 @@ def login_oauth_provider(
if spec.name == "openai_codex":
try:
- from nanobot.providers.openai_codex_oauth import start_openai_codex_oauth_login
+ from nanobot.providers.openai_codex_oauth import OpenAICodexOAuthLoginFlow
except ImportError:
raise WebUISettingsError(OAUTH_CLI_KIT_MISSING_MESSAGE, status=500) from None
@@ -1741,19 +1742,21 @@ def login_oauth_provider(
if remote_browser_value is not None
else False
)
+ flow = OpenAICodexOAuthLoginFlow(
+ proxy=proxy,
+ timeout_s=_WEBUI_OAUTH_TIMEOUT_S,
+ open_browser=not remote_browser,
+ )
+ flow_id = secrets.token_urlsafe(24)
try:
- flow = start_openai_codex_oauth_login(
- proxy=proxy,
- timeout_s=_WEBUI_OAUTH_TIMEOUT_S,
- open_browser=not remote_browser,
- )
+ oauth_flows.register(spec.name, flow_id, flow)
+ flow.start()
except Exception as exc:
+ oauth_flows.remove(spec.name, flow_id, flow)
raise WebUISettingsError(
f"OpenAI Codex OAuth login failed: {exc}",
status=502,
) from exc
- flow_id = secrets.token_urlsafe(24)
- oauth_flows.register(spec.name, flow_id, flow)
return {
"status": "authorization_required",
"provider": spec.name,
@@ -1776,8 +1779,8 @@ def login_oauth_provider(
flow_id = secrets.token_urlsafe(24)
# Own the flow before network I/O, so logout/replacement also cancels a
# login that is still waiting for GitHub to return its device prompt.
- oauth_flows.register(spec.name, flow_id, copilot_flow)
try:
+ oauth_flows.register(spec.name, flow_id, copilot_flow)
copilot_flow.start()
except Exception:
oauth_flows.remove(spec.name, flow_id, copilot_flow)
@@ -1793,7 +1796,7 @@ def login_oauth_provider(
}
if spec.name == "xai_grok":
- from nanobot.providers.xai_oauth import start_xai_oauth_login
+ from nanobot.providers.xai_oauth import create_xai_oauth_login
try:
proxy = resolve_config_env_vars(
@@ -1803,14 +1806,19 @@ def login_oauth_provider(
except ValueError as exc:
raise WebUISettingsError(str(exc), status=400) from exc
try:
- flow = start_xai_oauth_login(
+ flow = create_xai_oauth_login(
proxy=proxy,
timeout_s=_WEBUI_OAUTH_TIMEOUT_S,
)
except Exception as exc:
raise WebUISettingsError(f"xAI OAuth login failed: {exc}", status=502) from exc
flow_id = secrets.token_urlsafe(24)
- oauth_flows.register(spec.name, flow_id, flow)
+ try:
+ oauth_flows.register(spec.name, flow_id, flow)
+ flow.start()
+ except Exception as exc:
+ oauth_flows.remove(spec.name, flow_id, flow)
+ raise WebUISettingsError(f"xAI OAuth login failed: {exc}", status=502) from exc
return {
"status": "authorization_required",
"provider": spec.name,
@@ -1850,25 +1858,14 @@ def complete_oauth_provider(
try:
if spec.name == "openai_codex":
- from nanobot.providers.openai_codex_oauth import (
- OpenAICodexOAuthInputError,
- complete_openai_codex_oauth_login,
- )
+ from nanobot.providers.openai_codex_oauth import OpenAICodexOAuthInputError
try:
- token = complete_openai_codex_oauth_login(flow, authorization_response)
+ token = flow.complete(authorization_response)
except OpenAICodexOAuthInputError as exc:
raise WebUISettingsError(str(exc), status=400) from exc
- elif spec.name == "github_copilot":
- from nanobot.providers.github_copilot_oauth import GitHubCopilotOAuthFlow
-
- if not isinstance(flow, GitHubCopilotOAuthFlow):
- raise WebUISettingsError("Invalid GitHub sign-in session. Start again.")
- token = flow.complete()
else:
- from nanobot.providers.xai_oauth import complete_xai_oauth_login
-
- token = complete_xai_oauth_login(flow, authorization_response)
+ token = flow.complete(authorization_response)
except WebUISettingsError:
raise
except Exception as exc:
@@ -1941,9 +1938,26 @@ def logout_oauth_provider(
class ModelSettingsHandler:
"""Handle model/provider commands after transport authentication and decoding."""
- def __init__(self, settings: WebUISettingsServices, logger: Any) -> None:
+ def __init__(
+ self, settings: WebUISettingsServices, logger: Any, admission: RuntimeAdmission,
+ ) -> None:
self.settings = settings
self.logger = logger
+ self._admission = admission
+ self._remove_pending_work: Callable[[], None] | None = None
+ self._close_task: asyncio.Task[None] | None = None
+
+ async def close(self) -> None:
+ """Keep the registry owned even if its shutdown awaiter is cancelled."""
+ if self._close_task is None or self._close_task.done():
+ self._close_task = asyncio.create_task(asyncio.to_thread(self.settings.oauth_flows.close))
+ self._close_task.add_done_callback(
+ lambda task: task.exception() if not task.cancelled() else None,
+ )
+ await asyncio.shield(self._close_task)
+ if self._remove_pending_work is not None:
+ self._remove_pending_work()
+ self._remove_pending_work = None
def _refresh_runtime_config(self) -> None:
"""Make a successful model-settings mutation visible to live clients now."""
@@ -1956,6 +1970,12 @@ class ModelSettingsHandler:
request: SettingsRequest,
operations: ModelSettingsOperations,
) -> SettingsRouteResult:
+ if action in {"oauth-login", "oauth-complete", "oauth-logout"}:
+ self._admission.check()
+ if self._remove_pending_work is None:
+ self._remove_pending_work = self._admission.register_pending_work(
+ lambda: self.settings.oauth_flows.has_pending_work,
+ )
try:
if action == "agent-update":
payload = await asyncio.to_thread(
diff --git a/nanobot/webui/settings_routes.py b/nanobot/webui/settings_routes.py
index 8b850ae5e..b2796704f 100644
--- a/nanobot/webui/settings_routes.py
+++ b/nanobot/webui/settings_routes.py
@@ -146,6 +146,14 @@ _SYSTEM_ROUTES = {
"/api/settings/pairing/deny": "pairing-deny",
"/api/settings/mcp-presets": "mcp-list",
"/api/settings/version-check": "version-check",
+ "/api/settings/nanobot-update/channel": "update-channel",
+ "/api/settings/nanobot-update/plan": "update-plan-read",
+ "/api/settings/nanobot-update/plan/create": "update-plan-create",
+ "/api/settings/nanobot-update/job": "update-job-read",
+ "/api/settings/nanobot-update/job/prepare": "update-job-prepare",
+ "/api/settings/nanobot-update/job/settle": "update-job-settle",
+ "/api/settings/nanobot-update/job/execute": "update-job-execute",
+ "/api/settings/nanobot-update/job/retry": "update-job-retry",
**{
path: f"mcp-{action}"
for path, action in _MCP_PRESET_ACTIONS_BY_PATH.items()
@@ -153,6 +161,12 @@ _SYSTEM_ROUTES = {
}
_SETTINGS_MUTATION_PATHS = frozenset({
+ "/api/settings/nanobot-update/channel",
+ "/api/settings/nanobot-update/plan/create",
+ "/api/settings/nanobot-update/job/prepare",
+ "/api/settings/nanobot-update/job/settle",
+ "/api/settings/nanobot-update/job/execute",
+ "/api/settings/nanobot-update/job/retry",
"/api/settings/runtime-config/update",
"/api/settings/update",
"/api/settings/model-configurations/create",
@@ -251,19 +265,21 @@ class WebUISettingsRouter:
self._mcp_reload = mcp_reload
self._image_generation_reload = image_generation_reload
self._mcp_oauth_redirect_uri = mcp_oauth_redirect_uri
- self._mcp_oauth = McpOAuthManager()
+ self._mcp_oauth = McpOAuthManager(bus.admission)
self._restart_sections: set[str] = set()
self._restart_baselines: dict[str, dict[str, Any]] = {}
self._restart_changes: dict[str, str] = {}
- self._models = model_domain.ModelSettingsHandler(settings, logger)
+ self._models = model_domain.ModelSettingsHandler(settings, logger, bus.admission)
self._capabilities = capability_domain.CapabilitySettingsHandler(
settings,
logger,
)
- self._system = system_domain.SystemSettingsHandler(settings, logger)
+ self._system = system_domain.SystemSettingsHandler(settings, logger, bus.admission)
async def close(self) -> None:
"""Release state owned by settings domains."""
+ await self._mcp_oauth.close()
+ await self._models.close()
await self._system.close()
async def dispatch(
@@ -303,6 +319,8 @@ class WebUISettingsRouter:
return await asyncio.to_thread(self._handle_settings_usage)
domain, action = route
+ if action.startswith("update-") and self._runtime_surface == "native":
+ return self._error_response(409, "Update this installation through Nanobot Desktop.")
restart_before = (
await asyncio.to_thread(self._restart_values, action)
if action in {"runtime-config-update", "image-update", "web-search-update"}
@@ -318,6 +336,14 @@ class WebUISettingsRouter:
"features-enable",
"channel-configure",
"channel-connect",
+ "update-channel",
+ "version-check",
+ "update-plan-create",
+ "update-plan-read",
+ "update-job-prepare",
+ "update-job-settle",
+ "update-job-execute",
+ "update-job-retry",
}
),
)
@@ -362,7 +388,12 @@ class WebUISettingsRouter:
self._restart_changes[action] = result.restart_section
# Reversible changes are tracked separately from installation and reload failures.
result.payload["requires_restart"] = False
- return self._render_result(result)
+ response = self._render_result(result)
+ if action.startswith("update-") or action == "version-check":
+ # A saved review is immutable, but its local validity and permission
+ # are not. Never reuse a cached success after an installation changes.
+ response.headers["Cache-Control"] = "no-store"
+ return response
def _restart_values(self, action: str) -> dict[str, Any]:
config = self.settings.config.load()
diff --git a/nanobot/webui/settings_services.py b/nanobot/webui/settings_services.py
index 5f635b1d4..b4700e6e4 100644
--- a/nanobot/webui/settings_services.py
+++ b/nanobot/webui/settings_services.py
@@ -6,7 +6,7 @@ import threading
from collections.abc import Callable
from dataclasses import dataclass
from pathlib import Path
-from typing import Any, TypeVar
+from typing import Any, Protocol, TypeVar
from filelock import FileLock
@@ -46,30 +46,90 @@ class WebUISettingsConfig:
return operation(self.path)
+class WebUIOAuthToken(Protocol):
+ @property
+ def access(self) -> str: ...
+
+
+class WebUIOAuthFlow(Protocol):
+ """Provider flow whose cancellation and actual worker exit are separate."""
+
+ @property
+ def expired(self) -> bool: ...
+
+ @property
+ def has_pending_work(self) -> bool:
+ """A nonblocking observation of live workers, including cleanup."""
+ ...
+
+ def complete(self, response: str | None = None, /) -> WebUIOAuthToken | None: ...
+ def cancel(self) -> None: ...
+ def wait_closed(self) -> None:
+ """Return only after the cancelled flow's workers have actually exited."""
+ ...
+
+
class WebUIOAuthFlowRegistry:
- """Bounded, thread-safe OAuth flows owned by one gateway instance."""
+ """Bounded, thread-safe OAuth ownership, including removed flows still stopping."""
def __init__(self, *, max_flows: int = _WEBUI_OAUTH_MAX_FLOWS) -> None:
if max_flows < 1:
raise ValueError("max_flows must be at least one")
self._max_flows = max_flows
- self._flows: dict[str, tuple[str, Any]] = {}
+ self._flows: dict[str, tuple[str, WebUIOAuthFlow]] = {}
+ self._retiring: dict[int, tuple[str, WebUIOAuthFlow]] = {}
+ self._cancelling: set[int] = set()
self._lock = threading.Lock()
+ self._closed = False
+ self._closing = False
- def register(self, provider_name: str, flow_id: str, flow: Any) -> None:
- discarded: list[Any] = []
+ @property
+ def has_pending_work(self) -> bool:
+ with self._lock:
+ return self._closing or bool(self._cancelling) or any(
+ flow.has_pending_work
+ for _provider, flow in (*self._flows.values(), *self._retiring.values())
+ )
+
+ def _retire_locked(self, flow_id: str, *, cancel: bool = True) -> WebUIOAuthFlow:
+ registered = self._flows.pop(flow_id)
+ self._retiring[id(registered[1])] = registered
+ if cancel:
+ self._cancelling.add(id(registered[1]))
+ return registered[1]
+
+ def _cancel(self, flow: WebUIOAuthFlow) -> None:
+ flow.cancel()
with self._lock:
+ self._cancelling.discard(id(flow))
+
+ def register(self, provider_name: str, flow_id: str, flow: WebUIOAuthFlow) -> None:
+ """Register before start; reject capacity rather than losing a live worker."""
+ discarded: list[WebUIOAuthFlow] = []
+ with self._lock:
+ if self._closed:
+ raise RuntimeError("OAuth sign-in is closing. Reconnect before starting again.")
for existing_id, (_provider_name, existing) in list(self._flows.items()):
- if existing.expired:
- discarded.append(self._flows.pop(existing_id)[1])
- while len(self._flows) >= self._max_flows:
+ if existing.expired or existing_id == flow_id:
+ discarded.append(self._retire_locked(existing_id))
+ if len(self._flows) >= self._max_flows:
oldest_id = next(iter(self._flows))
- discarded.append(self._flows.pop(oldest_id)[1])
- self._flows[flow_id] = (provider_name, flow)
+ discarded.append(self._retire_locked(oldest_id))
+ # Never hold the registry lock while a provider waits for its commit lock.
for existing in discarded:
- existing.cancel()
+ self._cancel(existing)
+ with self._lock:
+ self._retiring = {
+ key: value for key, value in self._retiring.items()
+ if key in self._cancelling or value[1].has_pending_work
+ }
+ if self._closed:
+ raise RuntimeError("OAuth sign-in is closing. Reconnect before starting again.")
+ if len(self._flows) + len(self._retiring) >= self._max_flows:
+ raise RuntimeError("Previous sign-ins are still stopping. Try again shortly.")
+ self._flows[flow_id] = (provider_name, flow)
- def get(self, provider_name: str, flow_id: str) -> Any | None:
+ def get(self, provider_name: str, flow_id: str) -> WebUIOAuthFlow | None:
with self._lock:
registered = self._flows.get(flow_id)
if registered is None or registered[0] != provider_name:
@@ -77,15 +137,15 @@ class WebUIOAuthFlowRegistry:
flow = registered[1]
if not flow.expired:
return flow
- self._flows.pop(flow_id, None)
- flow.cancel()
+ self._retire_locked(flow_id)
+ self._cancel(flow)
return None
def remove(
self,
provider_name: str,
flow_id: str,
- flow: Any,
+ flow: WebUIOAuthFlow,
*,
cancel: bool = True,
) -> None:
@@ -96,9 +156,9 @@ class WebUIOAuthFlowRegistry:
and registered[0] == provider_name
and registered[1] is flow
):
- self._flows.pop(flow_id)
+ self._retire_locked(flow_id, cancel=cancel)
if cancel:
- flow.cancel()
+ self._cancel(flow)
def clear(self, provider_name: str) -> None:
with self._lock:
@@ -107,9 +167,29 @@ class WebUIOAuthFlowRegistry:
for flow_id, (registered_provider, _flow) in self._flows.items()
if registered_provider == provider_name
]
- flows = [self._flows.pop(flow_id)[1] for flow_id in flow_ids]
+ for flow_id in flow_ids:
+ self._retire_locked(flow_id)
+ flows = [
+ flow for provider, flow in self._retiring.values() if provider == provider_name
+ ]
+ for flow in flows:
+ self._cancel(flow)
+
+ def close(self) -> None:
+ """Cancel and join all owned workers; failure retains ownership for retry."""
+ with self._lock:
+ self._closed = True
+ self._closing = True
+ for flow_id in tuple(self._flows):
+ self._retire_locked(flow_id)
+ flows = [flow for _provider, flow in self._retiring.values()]
+ for flow in flows:
+ self._cancel(flow)
for flow in flows:
- flow.cancel()
+ flow.wait_closed()
+ with self._lock:
+ self._retiring.clear()
+ self._closing = False
@dataclass(frozen=True)
diff --git a/nanobot/webui/settings_system.py b/nanobot/webui/settings_system.py
index 824308c8e..09ed5c760 100644
--- a/nanobot/webui/settings_system.py
+++ b/nanobot/webui/settings_system.py
@@ -7,6 +7,7 @@ import inspect
import json
import platform
import re
+import subprocess
import time
from collections.abc import Callable, Iterable, Mapping
from dataclasses import dataclass
@@ -14,11 +15,13 @@ from pathlib import Path
from typing import TYPE_CHECKING, Any, TypedDict, cast
from zoneinfo import ZoneInfo
+import httpx
+from pydantic import ValidationError
from pydantic.alias_generators import to_snake
from nanobot.build_info import COMMIT
from nanobot.channels._setup import channel_setup_spec
-from nanobot.channels.connect import ChannelConnectError
+from nanobot.channels.connect import ChannelConnectError, ChannelConnector, ManagedChannelConnector
from nanobot.channels.contracts import (
RouteFieldType,
channel_instance_config,
@@ -27,7 +30,26 @@ from nanobot.channels.contracts import (
from nanobot.config.schema import Config
from nanobot.llm_usage import llm_usage_payload
from nanobot.optional_features import OptionalFeatureError, with_channel_runtime_status
+from nanobot.runtime_admission import RuntimeAdmission
from nanobot.security.workspace_access import workspace_sandbox_status
+from nanobot.update_channel import UpdateChannelRequest
+from nanobot.update_guidance import installation_method
+from nanobot.update_jobs import UpdateJobNotFoundError, read_update_job
+from nanobot.update_plan import (
+ UpdatePlan,
+ UpdatePlanNotFoundError,
+ UpdatePlanRequest,
+ inspect_update_installation,
+ preview_release_update,
+ read_release_plan,
+ review_plan,
+)
+from nanobot.update_service import (
+ UpdateExecutionRequest,
+ UpdateJobRequest,
+ UpdateJobService,
+ UpdateRetryRequest,
+)
from nanobot.webui.settings_capabilities import network_safety_payload
from nanobot.webui.settings_contracts import (
QueryParams,
@@ -40,9 +62,10 @@ from nanobot.webui.settings_contracts import (
from nanobot.webui.settings_runtime import runtime_config_payload
if TYPE_CHECKING:
+ from nanobot.channels.plugin import ChannelPlugin
from nanobot.webui.settings_services import WebUISettingsServices
-LoadChannelPlugin = Callable[[str], Any]
+LoadChannelPlugin = Callable[[str], "ChannelPlugin"]
ListPendingPairings = Callable[[], Iterable[dict[str, Any]]]
SettingsOperation = Callable[..., Any]
@@ -424,28 +447,53 @@ def pairing_payload(
class SystemSettingsHandler:
"""Handle channel and system commands behind a transport-neutral request DTO."""
- def __init__(self, settings: WebUISettingsServices, logger: Any) -> None:
+ def __init__(
+ self, settings: WebUISettingsServices, logger: Any, admission: RuntimeAdmission,
+ ) -> None:
self.settings = settings
self.logger = logger
- self._channel_connectors: dict[str, Any] = {}
+ self._admission = admission
+ self._channel_connectors: dict[str, ChannelConnector] = {}
+ self._remove_pending_work: Callable[[], None] | None = None
+ self._closing_connectors = False
+ self._update_jobs = UpdateJobService()
+ self._remove_update_work: Callable[[], None] | None = None
+
+ def _has_pending_connectors(self) -> bool:
+ return self._closing_connectors or any(
+ not isinstance(connector, ManagedChannelConnector) or connector.has_pending_work
+ for connector in self._channel_connectors.values()
+ )
async def close(self) -> None:
"""Release channel-owned setup sessions during gateway shutdown."""
+ await self._update_jobs.close()
+ if self._remove_update_work is not None:
+ self._remove_update_work()
+ self._remove_update_work = None
connectors = tuple(self._channel_connectors.items())
- self._channel_connectors.clear()
- for channel_name, connector in connectors:
- close = getattr(connector, "close", None)
- if not callable(close):
- continue
- try:
- result = close()
- if inspect.isawaitable(result):
- await result
- except Exception:
- self.logger.exception(
- "failed to close {} WebUI connector",
- channel_name,
- )
+ self._closing_connectors = True
+ try:
+ for channel_name, connector in connectors:
+ close = getattr(connector, "close", None)
+ if not callable(close):
+ continue
+ try:
+ result = close()
+ if inspect.isawaitable(result):
+ await result
+ if isinstance(connector, ManagedChannelConnector) and not connector.has_pending_work:
+ del self._channel_connectors[channel_name]
+ except Exception:
+ self.logger.exception(
+ "failed to close {} WebUI connector",
+ channel_name,
+ )
+ if not self._channel_connectors and self._remove_pending_work is not None:
+ self._remove_pending_work()
+ self._remove_pending_work = None
+ finally:
+ self._closing_connectors = False
async def handle(
self,
@@ -516,9 +564,122 @@ class SystemSettingsHandler:
operations,
)
if action == "version-check":
- return await self._version_check(operations)
+ return await self._version_check(request, operations)
+ if action == "update-channel":
+ if not self.allow_feature_package_install(request):
+ return SettingsRouteResult.failure(403, "Changing update channels requires package-install permission.")
+ try:
+ options = UpdateChannelRequest.model_validate(request.payload or {})
+ except (ValidationError, ValueError):
+ return SettingsRouteResult.failure(400, "Invalid update channel request")
+ try:
+ self._admission.check()
+ selection = self._update_jobs.change_channel(options)
+ except (RuntimeError, ValueError, OSError, KeyError) as exc:
+ self.logger.warning("could not change update channel ({})", type(exc).__name__)
+ return SettingsRouteResult.failure(409, "Could not change channels. Finish or recover any pending update, then check again.")
+ return SettingsRouteResult.success({"channel": selection.channel, "revision": selection.revision})
+ if action in {"update-plan-create", "update-plan-read"}:
+ return await self._update_plan(request, create=action == "update-plan-create")
+ if action == "update-job-read":
+ return await self._update_job(request)
+ if action in {"update-job-prepare", "update-job-settle"}:
+ return self._update_job_action(request, prepare=action == "update-job-prepare")
+ if action in {"update-job-execute", "update-job-retry"}:
+ return await self._execute_update_job(request, retry=action == "update-job-retry")
return SettingsRouteResult.failure(404, "unknown settings action")
+ async def _execute_update_job(self, request: SettingsRequest, *, retry: bool) -> SettingsRouteResult:
+ if not self.allow_feature_package_install(request):
+ return SettingsRouteResult.failure(
+ 403, "Updating from a remote WebUI is disabled. Use localhost or enable remote package installation.",
+ )
+ try:
+ options = (UpdateRetryRequest if retry else UpdateExecutionRequest).model_validate(request.payload or {})
+ except (ValidationError, ValueError):
+ return SettingsRouteResult.failure(400, "Confirm the saved update plan and its gateway restart.")
+ try:
+ self._admission.check()
+ job = await self._update_jobs.execute(
+ options.id, previous_confirmation_id=options.previous_confirmation_id if isinstance(options, UpdateRetryRequest) else None,
+ )
+ except UpdateJobNotFoundError:
+ return SettingsRouteResult.failure(404, "No saved update job is available. Review and prepare the update first.")
+ except (RuntimeError, ValueError, OSError, KeyError) as exc:
+ self.logger.warning("could not confirm an update handoff ({})", type(exc).__name__)
+ return SettingsRouteResult.failure(409, "Could not confirm this update. Read its saved state before starting a new review.")
+ return SettingsRouteResult.success({"job": job.model_dump(mode="json")})
+
+ def _update_job_action(self, request: SettingsRequest, *, prepare: bool) -> SettingsRouteResult:
+ if not self.allow_feature_package_install(request):
+ return SettingsRouteResult.failure(
+ 403, "Preparing updates from a remote WebUI is disabled. Use localhost or enable remote package installation.",
+ )
+ try:
+ options = UpdateJobRequest.model_validate(request.payload or {})
+ except (ValidationError, ValueError):
+ return SettingsRouteResult.failure(400, "Invalid update job request")
+ try:
+ self._admission.check()
+ if prepare:
+ if self._remove_update_work is None:
+ self._remove_update_work = self._admission.register_pending_work(self._update_jobs.has_pending_work)
+ job = self._update_jobs.prepare(options.id)
+ else:
+ job = self._update_jobs.settle(options.id)
+ except (UpdatePlanNotFoundError, UpdateJobNotFoundError):
+ return SettingsRouteResult.failure(404, "This saved update is no longer available. Check again.")
+ except (RuntimeError, ValueError, OSError, KeyError) as exc:
+ self.logger.warning("could not accept an update preparation action ({})", type(exc).__name__)
+ return SettingsRouteResult.failure(409, "Could not accept this preparation action. Read the saved update state before trying again.")
+ return SettingsRouteResult.success({"job": job.model_dump(mode="json")})
+
+ async def _update_job(self, request: SettingsRequest) -> SettingsRouteResult:
+ plan_id = query_first(request.query, "id") or ""
+ try:
+ UpdatePlan.canonical_id(plan_id)
+ except ValueError:
+ return SettingsRouteResult.failure(400, "Invalid update job identifier")
+ try:
+ job = await asyncio.to_thread(read_update_job, plan_id)
+ except UpdateJobNotFoundError:
+ return SettingsRouteResult.failure(404, "No saved update job is available for this installation.")
+ except (ValueError, OSError, KeyError) as exc:
+ self.logger.warning("could not read the gateway's update job ({})", type(exc).__name__)
+ return SettingsRouteResult.failure(409, "Could not read this update's saved state. No recovery action was started.")
+ return SettingsRouteResult.success({"job": job.model_dump(mode="json")})
+
+ async def _update_plan(self, request: SettingsRequest, *, create: bool) -> SettingsRouteResult:
+ plan_id = query_first(request.query, "id") or ""
+ try:
+ options = UpdatePlanRequest.model_validate(request.payload or {}) if create else None
+ if options is None:
+ UpdatePlan.canonical_id(plan_id)
+ except (ValidationError, ValueError):
+ return SettingsRouteResult.failure(400, "Invalid update plan request")
+ try:
+ if options is not None:
+ plan = await preview_release_update(
+ options.channel, restart_running=options.restart_running, extras=options.extras,
+ )
+ review = review_plan(plan, plan.installation)
+ else:
+ review = await read_release_plan(plan_id)
+ except UpdatePlanNotFoundError:
+ return SettingsRouteResult.failure(404, "The update plan is no longer available. Check again.")
+ except (RuntimeError, ValueError, OSError, subprocess.SubprocessError, httpx.HTTPError) as exc:
+ # A parser/subprocess error may contain local configuration or source
+ # credentials. Neither belongs in a remote response.
+ self.logger.warning("could not inspect the gateway's update plan ({})", type(exc).__name__)
+ return SettingsRouteResult.failure(409, "Could not verify an update plan for this installation. No update was started.")
+ return SettingsRouteResult.success({
+ "plan": review.model_dump(mode="json"),
+ "installation_allowed": self.allow_feature_package_install(request),
+ # This exact review is consumed by the durable preparation/handoff
+ # routes, never by the legacy unbound latest-release mutation.
+ "execution_available": review.execution_blocked_reason is None,
+ })
+
async def _cli_apps(
self,
request: SettingsRequest,
@@ -883,10 +1044,15 @@ class SystemSettingsHandler:
action: str,
operations: SystemSettingsOperations,
) -> SettingsRouteResult:
+ self._admission.check()
try:
connector = self._channel_connectors.get(channel_name)
if connector is None:
plugin = operations.load_channel_plugin(channel_name)
+ if self._remove_pending_work is None:
+ self._remove_pending_work = self._admission.register_pending_work(
+ self._has_pending_connectors,
+ )
connector = plugin.load_connector()
self._channel_connectors[channel_name] = connector
except ImportError:
@@ -1055,11 +1221,25 @@ class SystemSettingsHandler:
async def _version_check(
self,
+ request: SettingsRequest,
operations: SystemSettingsOperations,
) -> SettingsRouteResult:
try:
update_info = await asyncio.to_thread(operations.check_for_update)
- except Exception:
- self.logger.exception("version check failed")
+ except Exception as exc:
+ self.logger.warning("version check failed ({})", type(exc).__name__)
return SettingsRouteResult.failure(500, "version check failed")
- return SettingsRouteResult.success({"updateAvailable": update_info})
+ if query_first(request.query, "channel_status") == "1":
+ try:
+ method = installation_method(await asyncio.to_thread(inspect_update_installation))
+ except (RuntimeError, ValueError, OSError, subprocess.SubprocessError):
+ method = None # Unknown owner must not imply one-click eligibility.
+ return SettingsRouteResult.success({
+ **update_info, "can_change_channel": self.allow_feature_package_install(request),
+ "installation_method": method,
+ })
+ # An older client cannot interpret waiting/withdrawn/unavailable states.
+ # Report a failure rather than converting them to its green "up to date".
+ if update_info["releaseStatus"]["state"] not in {"available", "current", "ahead"}:
+ return SettingsRouteResult.failure(409, "No verified update result is available. Open this gateway's current WebUI to check its release channel.")
+ return SettingsRouteResult.success({"updateAvailable": update_info["updateAvailable"]})
diff --git a/nanobot/webui/version_check.py b/nanobot/webui/version_check.py
index f1a00535c..b33e4b41c 100644
--- a/nanobot/webui/version_check.py
+++ b/nanobot/webui/version_check.py
@@ -1,58 +1,57 @@
-"""On-demand version checker for nanobot-ai releases.
-
-Checks PyPI for newer versions when explicitly requested (no background polling).
-"""
+"""Channel-aware discovery using the same verified feed as update planning."""
from __future__ import annotations
-import logging
-import time
+import asyncio
from typing import Any
import httpx
-from packaging.version import InvalidVersion, Version
-
-from nanobot import __version__
-
-logger = logging.getLogger(__name__)
-
-_PYPI_URL = "https://pypi.org/pypi/nanobot-ai/json"
-_CACHE_TTL_S = 300 # 5 minutes cache to avoid hammering PyPI
-
-_cache: tuple[float, str | None] = (0.0, None)
+from packaging.version import Version
+import nanobot
+from nanobot.installation_lock import installation_state_dir
+from nanobot.release_feed import ReleaseFeed, ReleaseFeedError
+from nanobot.update_channel import read_update_channel
-def check_for_update() -> dict[str, Any] | None:
- """Check PyPI for a newer version. Returns update info dict or None if up-to-date.
- Uses a short cache to avoid repeated requests within the TTL window.
- This is a blocking call — invoke from a thread or background task.
- """
- global _cache
- now = time.monotonic()
- cached_at, cached_val = _cache
- if now - cached_at < _CACHE_TTL_S and cached_val is not None:
- latest = cached_val
- else:
- try:
- resp = httpx.get(_PYPI_URL, timeout=5.0, follow_redirects=True)
- resp.raise_for_status()
- latest = resp.json().get("info", {}).get("version")
- except Exception:
- logger.debug("PyPI version check failed", exc_info=True)
- return None
- _cache = (now, latest)
-
- if not isinstance(latest, str) or not latest:
- return None
- try:
- if Version(latest) <= Version(__version__):
- return None
- except InvalidVersion:
- logger.debug("PyPI returned an invalid nanobot version: %r", latest)
- return None
- return {
- "currentVersion": __version__,
- "latestVersion": latest,
- "pypiUrl": "https://pypi.org/project/nanobot-ai/",
+async def _check() -> dict[str, Any]:
+ selection = read_update_channel()
+ current = nanobot.__version__
+ status: dict[str, Any] = {
+ "channel": selection.channel, "revision": selection.revision,
+ "currentVersion": current, "state": "unavailable",
}
+ result: dict[str, Any] = {"updateAvailable": None, "releaseStatus": status}
+ try:
+ async with ReleaseFeed(installation_state_dir() / "releases") as feed:
+ target, withdrawn = await feed.discover(selection.channel, current)
+ if target is not None and Version(target.version) > Version(current):
+ result["updateAvailable"] = {
+ "currentVersion": current, "latestVersion": target.version,
+ "releaseUrl": f"https://github.com/HKUDS/nanobot/releases/tag/v{target.version}",
+ }
+ status["state"] = "available"
+ elif target is not None:
+ status["state"] = (
+ "waiting_stable" if selection.channel == "stable" and Version(current).is_prerelease
+ else "ahead" if Version(current) > Version(target.version) else "current"
+ )
+ if withdrawn:
+ status["state"] = "withdrawn"
+ except ReleaseFeedError as exc:
+ # This concerns the candidate, not necessarily the installed version.
+ status["state"] = "unavailable" if exc.code == "withdrawn" else exc.code
+ except (httpx.HTTPError, ValueError, OSError):
+ status["state"] = "unavailable"
+ if read_update_channel() != selection:
+ raise ValueError("Update channel changed while checking; check again")
+ return result
+
+
+def check_for_update() -> dict[str, Any]:
+ """Blocking settings adapter. Every check is fresh and never installs.
+
+ The feed's ETag cache guards generations, not availability. Older clients
+ still read updateAvailable; channel status is additive.
+ """
+ return asyncio.run(_check())
diff --git a/nanobot/webui/ws_http.py b/nanobot/webui/ws_http.py
index 475a55830..7ebd11e62 100644
--- a/nanobot/webui/ws_http.py
+++ b/nanobot/webui/ws_http.py
@@ -32,6 +32,7 @@ from nanobot.command.builtin import builtin_command_palette
from nanobot.cron.binding import CronBindingError, binding_revision
from nanobot.cron.session_turns import is_bound_cron_job
from nanobot.cron.types import CronJob, CronSchedule
+from nanobot.runtime_admission import RuntimeMaintenanceError
from nanobot.security.workspace_access import WorkspaceScope, WorkspaceScopeError
from nanobot.session.display_history import HistoryReader
from nanobot.session.manager import SessionManager
@@ -222,6 +223,12 @@ _WEBUI_MUTATION_PATHS = {
"settings.cli_app.test": "/api/settings/cli-apps/test",
"settings.feature.enable": "/api/settings/nanobot-features/enable",
"settings.feature.disable": "/api/settings/nanobot-features/disable",
+ "settings.nanobot.update.channel": "/api/settings/nanobot-update/channel",
+ "settings.nanobot.update.plan": "/api/settings/nanobot-update/plan/create",
+ "settings.nanobot.update.prepare": "/api/settings/nanobot-update/job/prepare",
+ "settings.nanobot.update.settle": "/api/settings/nanobot-update/job/settle",
+ "settings.nanobot.update.execute": "/api/settings/nanobot-update/job/execute",
+ "settings.nanobot.update.retry": "/api/settings/nanobot-update/job/retry",
"settings.channel.validate": "/api/settings/channels/validate",
"settings.channel.configure": "/api/settings/channels/configure",
"settings.pairing.approve": "/api/settings/pairing/approve",
@@ -479,8 +486,11 @@ class GatewayHTTPHandler:
405,
"WebUI mutations require an authenticated WebSocket",
)
- response = await self._dispatch_resolved(connection, request, got)
+ with self.bus.admission.activity():
+ response = await self._dispatch_resolved(connection, request, got)
return response
+ except RuntimeMaintenanceError:
+ return _http_error(503, "Gateway update is being verified. Retry shortly.")
finally:
self._log_slow_http(got, response, started)
@@ -511,7 +521,13 @@ class GatewayHTTPHandler:
setattr(request, "_nanobot_trusted_proxy_authenticated", True)
setattr(request, _WEBUI_MUTATION_REQUEST_ATTR, True)
setattr(request, _WEBUI_MUTATION_PAYLOAD_ATTR, dict(payload))
- response = await self._dispatch_resolved(connection, request, path)
+ try:
+ # WebUI mutation tasks already survive a disconnected browser. Keep
+ # their async/threaded writes busy until that operation really ends.
+ with self.bus.admission.activity():
+ response = await self._dispatch_resolved(connection, request, path)
+ except RuntimeMaintenanceError:
+ return _http_error(503, "Gateway update is being verified. Retry shortly.")
if isinstance(response, Response):
return response
return _http_error(404, "WebUI mutation action not found")
diff --git a/pyproject.toml b/pyproject.toml
index a0f059341..1a61e67e7 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -33,6 +33,7 @@ dependencies = [
"aiohttp>=3.14.3,<4.0.0",
"yarl>=1.17.0,<2.0.0",
"cryptography>=46.0.0",
+ "sigstore==4.5.0",
"ddgs>=9.5.5,<10.0.0",
"oauth-cli-kit>=0.1.6,<1.0.0",
"loguru>=0.7.3,<1.0.0",
@@ -123,7 +124,7 @@ nanobot-desktop-tui = "nanobot.cli.desktop_tui:main"
# my_plugin = "my_package.plugins:MyTool"
[build-system]
-requires = ["hatchling"]
+requires = ["hatchling", "filelock>=3.25.2"]
build-backend = "hatchling.build"
[tool.hatch.metadata]
@@ -135,6 +136,8 @@ allow-direct-references = true
[tool.hatch.build]
include = [
"nanobot/**/*.py",
+ "nanobot/cli/assets/*.png",
+ "nanobot/update_contract.json",
"nanobot/webui/mcp_presets.json",
"nanobot/templates/**/*.md",
"nanobot/skills/**/*.md",
@@ -193,6 +196,9 @@ omit = ["tests/*", "**/tests/*"]
[tool.coverage.report]
fail_under = 75
+# Discovery of unexecuted source files also includes colocated channel tests.
+# Match run.omit so the application gate never counts test bodies as product code.
+omit = ["tests/*", "**/tests/*"]
exclude_lines = [
"pragma: no cover",
"def __repr__",
diff --git a/scripts/build_tui_wheels.py b/scripts/build_tui_wheels.py
index a8e1da0f4..7dcb97a66 100644
--- a/scripts/build_tui_wheels.py
+++ b/scripts/build_tui_wheels.py
@@ -21,27 +21,22 @@ import zipfile
from email.parser import BytesParser
from pathlib import Path, PurePosixPath
-from nanobot.cli.tui_launcher import _verified_release_archive
+# Packaging must use the same archive checks as the installed launcher.
+from nanobot.cli.tui_launcher import (
+ _verified_release_archive, # pyright: ignore[reportPrivateUsage]
+)
+from nanobot.releases import PLATFORMS
ROOT = Path(__file__).resolve().parents[1]
-# Minimums verified against BOTH the Bun executable and its embedded OpenTUI library.
-# Linux binaries use glibc, not musl; macOS binaries require macOS 13.
-PLATFORMS = {
- "darwin-arm64": "macosx_13_0_arm64",
- "darwin-x64": "macosx_13_0_x86_64",
- "linux-arm64": "manylinux_2_17_aarch64",
- "linux-x64": "manylinux_2_17_x86_64",
- "win32-x64": "win_amd64",
-}
def _digest(data: bytes) -> str:
return "sha256=" + base64.urlsafe_b64encode(hashlib.sha256(data).digest()).rstrip(b"=").decode()
-def _source_files(raw: bytes) -> dict[str, bytes]:
+def source_files(raw: bytes) -> dict[str, bytes]:
"""Compare archive contents without extracting any untrusted path to disk."""
- files = {}
+ files: dict[str, bytes] = {}
with tarfile.open(fileobj=io.BytesIO(raw), mode="r:gz") as archive:
for member in archive:
if member.isdir():
@@ -73,10 +68,12 @@ def _verify_architecture(binary: bytes, target: str) -> None:
raise ValueError(f"TUI executable architecture does not match {target}")
-def _base_files(wheel: Path, version: str) -> tuple[dict[str, bytes], dict[str, int], str]:
+def wheel_files(wheel: Path, version: str, *, platform: str = "any") -> tuple[dict[str, bytes], dict[str, int], str]:
+ """Verify identity and every RECORD entry for an intermediate or final wheel."""
prefix = f"nanobot_ai-{version}"
- if wheel.name != f"{prefix}-py3-none-any.whl":
- raise ValueError(f"Expected the candidate's universal wheel ({version})")
+ if wheel.name != f"{prefix}-py3-none-{platform}.whl":
+ kind = "universal wheel" if platform == "any" else "platform wheel"
+ raise ValueError(f"Expected the candidate's {kind} ({version})")
info_dir = f"{prefix}.dist-info"
with zipfile.ZipFile(wheel) as archive:
names = archive.namelist()
@@ -85,7 +82,7 @@ def _base_files(wheel: Path, version: str) -> tuple[dict[str, bytes], dict[str,
for name in names:
path = PurePosixPath(name)
if (path.is_absolute() or ".." in path.parts or "\\" in name
- or name.startswith("nanobot/tui/bin/")
+ or (platform == "any" and name.startswith("nanobot/tui/bin/"))
or name.endswith(("/RECORD.jws", "/RECORD.p7s"))):
raise ValueError(f"Unexpected base wheel entry: {name}")
files = {name: archive.read(name) for name in names if not name.endswith("/")}
@@ -93,8 +90,8 @@ def _base_files(wheel: Path, version: str) -> tuple[dict[str, bytes], dict[str,
metadata = BytesParser().parsebytes(files[f"{info_dir}/METADATA"])
wheel_metadata = BytesParser().parsebytes(files[f"{info_dir}/WHEEL"])
if (metadata["Name"] != "nanobot-ai" or metadata["Version"] != version
- or wheel_metadata["Root-Is-Purelib"] != "true"
- or wheel_metadata.get_all("Tag") != ["py3-none-any"]):
+ or wheel_metadata["Root-Is-Purelib"] != ("true" if platform == "any" else "false")
+ or wheel_metadata.get_all("Tag") != [f"py3-none-{platform}"]):
raise ValueError("Base wheel metadata does not match the candidate")
record = f"{info_dir}/RECORD"
rows = list(csv.reader(io.StringIO(files[record].decode())))
@@ -107,15 +104,8 @@ def _base_files(wheel: Path, version: str) -> tuple[dict[str, bytes], dict[str,
return files, modes, info_dir
-def build_wheel(wheel: Path, tui_dir: Path, out_dir: Path, target: str, *,
- root: Path = ROOT) -> Path:
- """Fail closed on stale sources, damaged archives, or existing output files."""
- version = tomllib.loads((root / "pyproject.toml").read_text())["project"]["version"]
- tag = f"py3-none-{PLATFORMS[target]}"
- output = out_dir / f"nanobot_ai-{version}-{tag}.whl"
- if output.exists():
- raise FileExistsError(output)
- files, modes, info_dir = _base_files(wheel, version)
+def release_bundle(tui_dir: Path, target: str, *, root: Path = ROOT) -> dict[str, bytes]:
+ """Validate the archive, architecture and corresponding source once at its owner."""
asset = f"nanobot-tui-{target}" + (".exe" if target.startswith("win32-") else "")
archive = tui_dir / f"{asset}.zip"
raw = archive.read_bytes()
@@ -130,8 +120,22 @@ def build_wheel(wheel: Path, tui_dir: Path, out_dir: Path, target: str, *,
source_packager = runpy.run_path(str(root / "tui/scripts/package-release.py"))
source_packager["_validate_opentui_version"](root / "tui", notices)
expected_source = source_packager["_source_archive"](root / "tui")
- if _source_files(bundle["nanobot-tui-source.tar.gz"]) != _source_files(expected_source):
+ if source_files(bundle["nanobot-tui-source.tar.gz"]) != source_files(expected_source):
raise ValueError("TUI archive source does not match this release checkout; rebuild it")
+ return bundle
+
+
+def build_wheel(wheel: Path, tui_dir: Path, out_dir: Path, target: str, *,
+ root: Path = ROOT) -> Path:
+ """Fail closed on stale sources, damaged archives, or existing output files."""
+ version = tomllib.loads((root / "pyproject.toml").read_text())["project"]["version"]
+ tag = f"py3-none-{PLATFORMS[target]}"
+ output = out_dir / f"nanobot_ai-{version}-{tag}.whl"
+ if output.exists():
+ raise FileExistsError(output)
+ files, modes, info_dir = wheel_files(wheel, version)
+ asset = f"nanobot-tui-{target}" + (".exe" if target.startswith("win32-") else "")
+ bundle = release_bundle(tui_dir, target, root=root)
for name, content in bundle.items():
path = f"nanobot/tui/bin/{name}"
files[path] = content
diff --git a/scripts/check_import_boundaries.py b/scripts/check_import_boundaries.py
index ae50a4b32..bd2e88e05 100644
--- a/scripts/check_import_boundaries.py
+++ b/scripts/check_import_boundaries.py
@@ -51,6 +51,32 @@ _TOOL_CONFIG_MODULES = (
)
IMPORT_RULES = (
+ ImportRule(
+ "update-policy-direction",
+ ("nanobot.agent", "nanobot.session", "nanobot.runtime_admission",
+ "nanobot.data_access", "nanobot.installation_lock"),
+ ("nanobot.update_service", "nanobot.update_plan", "nanobot.update_jobs",
+ "nanobot.update_worker", "nanobot.update_stop", "nanobot.update_restart"),
+ ),
+ ImportRule(
+ "update-domain",
+ ("nanobot.update_service", "nanobot.update_plan", "nanobot.update_jobs",
+ "nanobot.update_worker", "nanobot.update_stop",
+ "nanobot.update_profiles", "nanobot.update_handoff", "nanobot.update_guidance"),
+ ("nanobot.agent", "nanobot.session", "nanobot.api", "nanobot.cli",
+ "nanobot.channels", "nanobot.webui"),
+ ),
+ ImportRule(
+ "update-restart-adapter",
+ ("nanobot.update_restart",),
+ (*_ADAPTERS, "nanobot.agent", "nanobot.session"),
+ # This protected-startup entry composes the existing CLI, not a second
+ # agent runtime. Keep its frozen worker entry and launch semantics stable.
+ allowed_targets=("nanobot.gateway.runtime", "nanobot.cli.gateway_runtime._run_gateway",
+ "nanobot.cli.entry.configure_windows_console",
+ "nanobot.cli.process_identity.set_cli_process_identity",
+ "nanobot.cli.runtime_config._load_runtime_config"),
+ ),
ImportRule(
"core-execution",
("nanobot.agent.loop", "nanobot.agent.runner", "nanobot.agent.turn_delivery"),
diff --git a/scripts/install.ps1 b/scripts/install.ps1
index 7428ee616..ecf2bc6b4 100644
--- a/scripts/install.ps1
+++ b/scripts/install.ps1
@@ -1,6 +1,10 @@
param(
[switch]$Dev,
[switch]$DryRun,
+ [string]$Wheel,
+ [string]$Sha256,
+ [string]$Release,
+ [string]$ManifestSha256,
[Parameter(ValueFromRemainingArguments = $true)]
[string[]]$RemainingArgs
)
@@ -10,9 +14,8 @@ $ErrorActionPreference = "Stop"
$Package = "nanobot-ai"
$InstallTarget = $Package
$InstallSource = "PyPI"
-$script:NanobotRunner = $null
$script:NanobotPython = $null
-$script:LastInstallSucceeded = $false
+$ExpectedVersion = ""
function Write-Info {
param([string]$Message)
@@ -26,6 +29,9 @@ function Fail {
function Show-InstallFailureHint {
[Console]::Error.WriteLine("Error: could not install nanobot from $InstallSource.")
+ if ($ExpectedVersion) {
+ Fail "Inspect the original manager error and retry this exact handoff. No setup or other installation was attempted."
+ }
[Console]::Error.WriteLine("If pip mentioned externally-managed-environment, use uv, pipx, or a virtual environment instead of system pip.")
[Console]::Error.WriteLine("You can also run manually:")
[Console]::Error.WriteLine(" uv tool install --force --upgrade $InstallTarget")
@@ -37,10 +43,14 @@ function Show-InstallFailureHint {
}
function Show-Usage {
- Write-Host "Usage: install.ps1 [-DryRun|--dry-run]"
+ Write-Host "Usage: install.ps1 [-DryRun|--dry-run] [-Wheel PATH -Sha256 HASH]"
+ Write-Host " install.ps1 [-DryRun|--dry-run] -Release VERSION -ManifestSha256 HASH"
Write-Host ""
Write-Host "By default this installs or upgrades nanobot-ai from PyPI."
Write-Host "Use --dry-run to print what would happen without installing or starting setup."
+ Write-Host "Use -Wheel and -Sha256 together for a verified release handoff; retain the downloaded wheel."
+ Write-Host "Stop affected gateways and back up their data before updating an existing install."
+ Write-Host "-Release downloads the matching official wheel; it is one version, not a Preview subscription."
Write-Host ""
Write-Host "For current main, clone the repository and run 'python -m pip install -e .'."
}
@@ -87,6 +97,39 @@ function Test-VirtualEnv {
}
}
+function Get-InstallMethod {
+ if (Test-VirtualEnv $Python) {
+ $ActivePrefix = & $Python -I -c "import json, sys; print(json.dumps(sys.prefix))" | ConvertFrom-Json
+ if ((Test-Path -LiteralPath (Join-Path $ActivePrefix "uv-receipt.toml")) -or
+ (Test-Path -LiteralPath (Join-Path $ActivePrefix "pipx_metadata.json"))) {
+ Fail "The active Python belongs to uv or pipx. Deactivate it and rerun this installer so its manager owns the update."
+ }
+ return "python"
+ }
+
+ $Existing = @()
+ if (Get-Command uv -ErrorAction SilentlyContinue) {
+ $ToolDir = & uv tool dir
+ if ($LASTEXITCODE -ne 0 -or -not $ToolDir) { Fail "Could not inspect the uv tools directory." }
+ if (Test-Path -LiteralPath (Join-Path $ToolDir $Package)) { $Existing += "uv" }
+ }
+ if (Get-Command pipx -ErrorAction SilentlyContinue) {
+ $ToolDir = & pipx environment --value PIPX_LOCAL_VENVS
+ if ($LASTEXITCODE -ne 0 -or -not $ToolDir) { Fail "Could not inspect the pipx environments directory." }
+ if (Test-Path -LiteralPath (Join-Path $ToolDir $Package)) { $Existing += "pipx" }
+ }
+ $ProfileDir = if ($env:HOME) { $env:HOME } else { $env:USERPROFILE }
+ if ($env:NANOBOT_VENV -or $ProfileDir) {
+ $Environment = if ($env:NANOBOT_VENV) { $env:NANOBOT_VENV } else { Join-Path $ProfileDir ".nanobot\venv" }
+ if (Test-Path -LiteralPath (Join-Path $Environment "pyvenv.cfg")) { $Existing += "managed" }
+ }
+ if ($Existing.Count -gt 1) {
+ Fail "Multiple nanobot installations were found. Use the intended environment's package manager; this installer changed none of them."
+ }
+ if ($Existing.Count -eq 1) { return $Existing[0] }
+ return "managed"
+}
+
function Ensure-Pip {
param([string]$Command)
@@ -105,35 +148,45 @@ function Ensure-Pip {
}
}
+function Select-InstalledPython {
+ param([string]$Command, [string]$ExpectedEnvironment = "")
+
+ $Probe = @'
+import json
+import sys
+from importlib.metadata import distribution
+from pathlib import Path
+
+import nanobot
+
+prefix = Path(sys.prefix).resolve()
+package = Path(nanobot.__file__).resolve()
+expected = sys.argv[1] if len(sys.argv) > 1 else ""
+if sys.prefix == sys.base_prefix or (expected not in ("", "-") and prefix != Path(expected).resolve()):
+ raise SystemExit("The installed interpreter does not belong to the expected virtual environment")
+if not package.is_relative_to(prefix) or package != Path(distribution("nanobot-ai").locate_file("nanobot/__init__.py")).resolve():
+ raise SystemExit("nanobot imports from outside the installed package")
+if len(sys.argv) > 2 and sys.argv[2] and distribution("nanobot-ai").version != sys.argv[2]:
+ raise SystemExit("The requested version was not installed. Check manager pins or locks; no setup was started.")
+print(json.dumps(str(Path(sys.executable).absolute())))
+'@
+ # Do not resolve the interpreter symlink or launch a new pipx/uv run environment.
+ # Send code on stdin so Windows PowerShell preserves its embedded quotes.
+ $ExpectedRoot = if ($ExpectedEnvironment) { $ExpectedEnvironment } else { "-" }
+ $Result = $Probe | & $Command -I - $ExpectedRoot $ExpectedVersion
+ if ($LASTEXITCODE -ne 0 -or -not $Result) {
+ Fail "The installed nanobot environment could not be verified. No setup or other installation was attempted."
+ }
+ $script:NanobotPython = [string]($Result | ConvertFrom-Json)
+}
+
function Invoke-Nanobot {
param([string[]]$NanobotArgs)
-
- switch ($script:NanobotRunner) {
- "uv" {
- & uv tool run --from $InstallTarget nanobot @NanobotArgs
- }
- "pipx" {
- & pipx run --spec $InstallTarget nanobot @NanobotArgs
- }
- "python" {
- & $script:NanobotPython -m nanobot @NanobotArgs
- }
- default {
- Fail "nanobot was installed, but no runner was configured."
- }
- }
+ & $script:NanobotPython -I -m nanobot @NanobotArgs
}
function Get-NanobotCommand {
- switch ($script:NanobotRunner) {
- "uv" { return "uv tool run --from $InstallTarget nanobot" }
- "pipx" { return "pipx run --spec $InstallTarget nanobot" }
- "python" {
- $QuotedPython = "'" + $script:NanobotPython.Replace("'", "''") + "'"
- return "& $QuotedPython -m nanobot"
- }
- default { return "nanobot" }
- }
+ return "& '" + $script:NanobotPython.Replace("'", "''") + "' -I -m nanobot"
}
function Test-FreshNanobotInstall {
@@ -163,30 +216,77 @@ function Install-WithActivePython {
if ($LASTEXITCODE -ne 0) {
Show-InstallFailureHint
}
- $script:NanobotRunner = "python"
- $script:NanobotPython = $Python
+ Select-InstalledPython $Python
}
function Install-WithUv {
- $script:LastInstallSucceeded = $false
Write-Info "Installing or upgrading nanobot from $InstallSource with uv tool..."
- & uv tool install --python $Python --force --upgrade $InstallTarget
+ $ToolDir = & uv tool dir
+ if ($LASTEXITCODE -ne 0 -or -not $ToolDir) {
+ Fail "Could not locate the uv tools directory."
+ }
+ $Environment = Join-Path $ToolDir $Package
+ if (Test-Path -LiteralPath (Join-Path $Environment "uv-receipt.toml")) {
+ & uv tool upgrade $InstallTarget
+ } elseif (Test-Path -LiteralPath $Environment) {
+ Fail "The uv environment exists without its installation record. Repair it with uv before rerunning this installer."
+ } else {
+ & uv tool install --python $Python $InstallTarget
+ }
if ($LASTEXITCODE -ne 0) {
- return
+ Fail "uv could not install or upgrade nanobot. Resolve the error above and retry; no other installation was attempted."
}
- $script:NanobotRunner = "uv"
- $script:LastInstallSucceeded = $true
+ Select-InstalledPython (Join-Path $Environment "Scripts\python.exe") $Environment
}
function Install-WithPipx {
- $script:LastInstallSucceeded = $false
Write-Info "Installing or upgrading nanobot from $InstallSource with pipx..."
- & pipx install --python $Python --force $InstallTarget
+ $ToolDir = & pipx environment --value PIPX_LOCAL_VENVS
+ if ($LASTEXITCODE -ne 0 -or -not $ToolDir) {
+ Fail "Could not locate the pipx environments directory."
+ }
+ $Environment = Join-Path $ToolDir $Package
+ if (Test-Path -LiteralPath (Join-Path $Environment "pipx_metadata.json")) {
+ # Keep this stdlib bootstrap check in sync with install.sh.
+ $Inspect = @'
+import json
+import re
+import sys
+from pathlib import Path
+
+try:
+ path = Path(sys.argv[1])
+ if path.is_symlink() or path.stat().st_size > 1024 * 1024:
+ raise ValueError
+ record = json.loads(path.read_text(encoding="utf-8"))
+ main = record["main_package"]
+ name = r"(?i)nanobot[-_.]ai(?:\[[a-z0-9_., -]+\])?"
+ spec = main["package_or_url"]
+ # An explicit wheel may replace an earlier wheel source, but not discard
+ # registry constraints, lock workflows or recorded installer options.
+ allowed = re.fullmatch(name, spec) or (sys.argv[2] != "-" and re.fullmatch(name + r"\s*@\s*\S+\.whl", spec))
+ if record["pipx_metadata_version"] not in {"0.5", "0.12"} or not allowed or main.get("pip_args") or main.get("lock_file"):
+ raise ValueError
+except (OSError, ValueError, KeyError, TypeError):
+ raise SystemExit("Cannot safely reuse pipx installation settings; inspect the original requirement and options.") from None
+'@
+ $Exact = if ($ExpectedVersion) { $ExpectedVersion } else { "-" }
+ $Inspect | & $Python -I - (Join-Path $Environment "pipx_metadata.json") $Exact
+ if ($LASTEXITCODE -ne 0) { Fail "Review the original pipx installation settings; no installation was attempted." }
+ if ($ExpectedVersion) {
+ & pipx install --skip-maintenance --upgrade $InstallTarget
+ } else {
+ & pipx upgrade $Package
+ }
+ } elseif (Test-Path -LiteralPath $Environment) {
+ Fail "The pipx environment exists without its installation record. Repair it with pipx before rerunning this installer."
+ } else {
+ & pipx install --python $Python $InstallTarget
+ }
if ($LASTEXITCODE -ne 0) {
- return
+ Fail "pipx could not install or upgrade nanobot. Resolve the error above and retry; no other installation was attempted."
}
- $script:NanobotRunner = "pipx"
- $script:LastInstallSucceeded = $true
+ Select-InstalledPython (Join-Path $Environment "Scripts\python.exe") $Environment
}
function Install-WithManagedVenv {
@@ -197,13 +297,38 @@ function Install-WithManagedVenv {
$VenvDir = if ($env:NANOBOT_VENV) { $env:NANOBOT_VENV } else { Join-Path $HomeDir ".nanobot\venv" }
$VenvPython = Join-Path $VenvDir "Scripts\python.exe"
-
if (-not (Test-Path $VenvPython)) {
Write-Info "Creating a dedicated virtual environment at $VenvDir..."
$Parent = Split-Path -Parent $VenvDir
if ($Parent) {
New-Item -ItemType Directory -Force -Path $Parent *> $null
}
+ # Selection survives a failed first venv/pip operation. It is not an
+ # installed/readiness claim, nor adoption of an existing environment.
+ $RecordSelection = @'
+import json, os, sys
+from pathlib import Path
+prefix = Path(sys.argv[1]).resolve()
+if any((prefix / name).exists() for name in ('uv-receipt.toml', 'pipx_metadata.json')):
+ raise SystemExit('This environment belongs to another package manager.')
+prefix.mkdir(parents=True, exist_ok=True)
+path = prefix / 'nanobot-install.json'
+record = {'schema_version': 1, 'owner': 'nanobot-installer', 'environment': str(prefix), 'extras': []}
+if path.is_symlink():
+ raise SystemExit('The installation selection is invalid; no receipt was replaced.')
+if path.exists():
+ if path.stat().st_size > 4096 or json.loads(path.read_bytes()) != record:
+ raise SystemExit('The installation selection changed; no receipt was replaced.')
+else:
+ with path.open('x', encoding='utf-8') as stream:
+ json.dump(record, stream, sort_keys=True)
+ stream.write('\n')
+ stream.flush()
+ os.fsync(stream.fileno())
+ path.chmod(0o600)
+'@
+ & $Python -I -c $RecordSelection $VenvDir
+ if ($LASTEXITCODE -ne 0) { Fail "Could not record the new installation's update settings." }
& $Python -m venv $VenvDir
if ($LASTEXITCODE -ne 0) {
Show-InstallFailureHint
@@ -221,10 +346,14 @@ function Install-WithManagedVenv {
Show-InstallFailureHint
}
- $script:NanobotRunner = "python"
- $script:NanobotPython = $VenvPython
+ Select-InstalledPython $VenvPython $VenvDir
}
+$PreviousOutputEncoding = [Console]::OutputEncoding
+try {
+# uv/pipx emit UTF-8 paths; Windows PowerShell otherwise uses the console code page.
+[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false)
+
foreach ($Arg in $RemainingArgs) {
switch ($Arg) {
"--dev" {
@@ -254,24 +383,251 @@ if ($Dev) {
$Python = Find-Python
$Version = & $Python --version
Write-Info "Using Python: $Version"
+$InstallMethod = Get-InstallMethod
+
+if ($PSBoundParameters.ContainsKey("Wheel") -or $PSBoundParameters.ContainsKey("Sha256") -or
+ $PSBoundParameters.ContainsKey("Release") -or $PSBoundParameters.ContainsKey("ManifestSha256")) {
+ if ($PSBoundParameters.ContainsKey("Release") -or $PSBoundParameters.ContainsKey("ManifestSha256")) {
+ if (-not $Release -or -not $ManifestSha256) { Fail "-Release and -ManifestSha256 must be supplied together." }
+ if ($PSBoundParameters.ContainsKey("Wheel") -or $PSBoundParameters.ContainsKey("Sha256")) { Fail "Choose -Release or -Wheel, not both." }
+ } elseif (-not $Wheel -or -not $Sha256) { Fail "-Wheel and -Sha256 must be supplied together." }
+ $TargetPython = $Python
+ $ToolEnvironment = ""
+ if ($InstallMethod -eq "uv") {
+ $ToolDir = & uv tool dir
+ if ($LASTEXITCODE -ne 0 -or -not $ToolDir) { Fail "Could not inspect the uv tools directory." }
+ $ToolEnvironment = Join-Path $ToolDir $Package
+ } elseif ($InstallMethod -eq "pipx") {
+ $ToolDir = & pipx environment --value PIPX_LOCAL_VENVS
+ if ($LASTEXITCODE -ne 0 -or -not $ToolDir) { Fail "Could not inspect the pipx environments directory." }
+ $ToolEnvironment = Join-Path $ToolDir $Package
+ } elseif ($InstallMethod -eq "managed") {
+ $ProfileDir = if ($env:HOME) { $env:HOME } else { $env:USERPROFILE }
+ if (-not $ProfileDir) { Fail "A home directory is required to retain the downloaded release." }
+ $ToolEnvironment = if ($env:NANOBOT_VENV) { $env:NANOBOT_VENV } else { Join-Path $ProfileDir ".nanobot\venv" }
+ }
+ if ($ToolEnvironment) {
+ $CandidatePython = Join-Path $ToolEnvironment "Scripts\python.exe"
+ if (Test-Path -LiteralPath $CandidatePython) { $TargetPython = $CandidatePython }
+ }
+ $ProfileDir = if ($env:HOME) { $env:HOME } else { $env:USERPROFILE }
+ $ReleaseCache = if ($env:NANOBOT_RELEASE_CACHE) { $env:NANOBOT_RELEASE_CACHE } elseif ($ProfileDir) { Join-Path $ProfileDir ".nanobot\downloads\releases" } else { "-" }
+ if ($Release -and $ReleaseCache -eq "-") { Fail "A home directory is required to retain the downloaded release." }
+ $OwnerRecord = "-"
+ if ($InstallMethod -eq "pipx") {
+ $PipxDir = & pipx environment --value PIPX_LOCAL_VENVS
+ if ($LASTEXITCODE -ne 0 -or -not $PipxDir) { Fail "Could not inspect the pipx environments directory." }
+ $OwnerRecord = Join-Path (Join-Path $PipxDir $Package) "pipx_metadata.json"
+ }
+ $Verify = @'
+import hashlib
+import json
+import re
+import sys
+from email.parser import BytesParser
+from pathlib import Path
+from zipfile import ZipFile
+
+import os
+import platform
+import struct
+import sysconfig
+import tempfile
+from urllib.parse import urlsplit
+from urllib.request import HTTPRedirectHandler, Request, build_opener
+
+# Bootstrap has no installed nanobot/packaging dependency. This closed platform
+# set matches the five published wheel tags; the owner still checks compatibility.
+def native_platform():
+ if struct.calcsize("P") != 8:
+ raise SystemExit("No native release wheel is available for 32-bit Python")
+ machine = platform.machine().lower()
+ if sys.platform == "darwin":
+ if int(platform.mac_ver()[0].split(".")[0]) < 13:
+ raise SystemExit("The native release requires macOS 13 or newer")
+ if machine in ("arm64", "x86_64"):
+ return "macosx_13_0_" + machine
+ elif sys.platform == "linux":
+ try:
+ libc = os.confstr("CS_GNU_LIBC_VERSION") or ""
+ except (ValueError, OSError):
+ libc = ""
+ if not re.fullmatch(r"glibc \d+\.\d+", libc) or tuple(map(int, libc.split()[1].split("."))) < (2, 17):
+ raise SystemExit("The native release requires glibc 2.17+; no musl wheel is published")
+ if machine in ("aarch64", "x86_64"):
+ return "manylinux_2_17_" + machine
+ elif sys.platform == "win32" and sysconfig.get_platform() == "win-amd64":
+ return "win_amd64"
+ raise SystemExit("No native release wheel is published for this Python platform")
+
+def checked_url(url):
+ parsed = urlsplit(url)
+ if (parsed.scheme != "https" or parsed.hostname not in
+ {"github.com", "release-assets.githubusercontent.com", "objects.githubusercontent.com"}
+ or parsed.username is not None or parsed.password is not None
+ or parsed.port not in (None, 443) or parsed.fragment):
+ raise SystemExit("Release download redirected outside the approved HTTPS hosts")
+ return url
+
+class ReleaseRedirect(HTTPRedirectHandler):
+ max_redirections = 4
+ max_repeats = 1
+
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
+ checked_url(newurl)
+ return super().redirect_request(req, fp, code, msg, headers, newurl)
+
+def fetch_release(version, manifest_hash, cache, dry_run):
+ number = r"(?:0|[1-9]\d*)"
+ if not re.fullmatch(rf"{number}\.{number}\.{number}(?:\.dev{number}|\.post{number})?", version):
+ raise SystemExit("Expected a canonical release version, not a branch or URL")
+ if not re.fullmatch(r"[0-9a-f]{64}", manifest_hash):
+ raise SystemExit("A trusted published manifest SHA-256 is required")
+ selected_platform = native_platform()
+ base = "https://github.com/HKUDS/nanobot/releases/download/v" + version + "/"
+ opener = build_opener(ReleaseRedirect())
+ with opener.open(Request(checked_url(base + "release-manifest.json"),
+ headers={"Accept-Encoding": "identity"}), timeout=20) as response:
+ payload = response.read(64 * 1024 + 1)
+ if len(payload) > 64 * 1024 or hashlib.sha256(payload).hexdigest() != manifest_hash:
+ raise SystemExit("Release manifest size or SHA-256 mismatch")
+ manifest = json.loads(payload)
+ if (not isinstance(manifest, dict) or type(manifest.get("schema_version")) is not int
+ or manifest["schema_version"] != 1 or manifest.get("version") != version
+ or set(manifest) != {"schema_version", "version", "source_commit", "candidate_commit",
+ "requires_python", "artifacts"}):
+ raise SystemExit("Unsupported or mismatched release manifest")
+ for key in ("source_commit", "candidate_commit"):
+ if not isinstance(manifest[key], str) or not re.fullmatch(r"[0-9a-f]{40}", manifest[key]):
+ raise SystemExit("Invalid release commit identity")
+ if not isinstance(manifest["requires_python"], str) or not 0 < len(manifest["requires_python"]) <= 200:
+ raise SystemExit("Invalid Python requirement in release manifest")
+ targets = {"darwin-arm64": "macosx_13_0_arm64", "darwin-x64": "macosx_13_0_x86_64",
+ "linux-arm64": "manylinux_2_17_aarch64", "linux-x64": "manylinux_2_17_x86_64",
+ "win32-x64": "win_amd64"}
+ expected = {f"nanobot_ai-{version}-py3-none-{tag}.whl" for tag in targets.values()}
+ expected.add(f"nanobot_ai-{version}.tar.gz")
+ for target in targets:
+ name = "nanobot-tui-" + target + (".exe" if target == "win32-x64" else "") + ".zip"
+ expected.update((name, name + ".sha256"))
+ artifacts = manifest["artifacts"]
+ if (not isinstance(artifacts, list) or len(artifacts) != 16
+ or any(not isinstance(item, dict) or set(item) != {"filename", "size", "sha256"}
+ or not isinstance(item["filename"], str) or type(item["size"]) is not int
+ or not 0 < item["size"] <= 2 * 1024**3
+ or not isinstance(item["sha256"], str) or not re.fullmatch(r"[0-9a-f]{64}", item["sha256"])
+ for item in artifacts)
+ or {item["filename"] for item in artifacts} != expected):
+ raise SystemExit("Release manifest does not contain the complete matching artifact set")
+ filename = f"nanobot_ai-{version}-py3-none-{selected_platform}.whl"
+ artifact = next(item for item in artifacts if item["filename"] == filename)
+ if dry_run:
+ print("nanobot-ai @ " + base + filename + "#sha256=" + artifact["sha256"] + "|" + version)
+ raise SystemExit(0)
+ directory = Path(cache).expanduser().absolute() / version / artifact["sha256"]
+ directory.mkdir(parents=True, exist_ok=True, mode=0o700)
+ destination = directory / filename
+ if destination.exists() or destination.is_symlink():
+ if destination.is_symlink() or not destination.is_file() or destination.stat().st_size != artifact["size"]:
+ raise SystemExit("Invalid cached release file; inspect the release download directory")
+ return destination, artifact["sha256"]
+ descriptor, name = tempfile.mkstemp(prefix=".download-", suffix=".part", dir=directory)
+ temporary = Path(name)
+ try:
+ size = 0
+ digest = hashlib.sha256()
+ with os.fdopen(descriptor, "wb") as output:
+ with opener.open(Request(checked_url(base + filename),
+ headers={"Accept-Encoding": "identity"}), timeout=20) as response:
+ while chunk := response.read(64 * 1024):
+ size += len(chunk)
+ if size > artifact["size"]:
+ raise SystemExit("Release wheel exceeds its verified size")
+ digest.update(chunk)
+ output.write(chunk)
+ if size != artifact["size"] or digest.hexdigest() != artifact["sha256"]:
+ raise SystemExit("Release wheel size or SHA-256 mismatch")
+ try:
+ os.link(temporary, destination)
+ except FileExistsError:
+ if destination.is_symlink() or not destination.is_file() or destination.stat().st_size != size:
+ raise SystemExit("The cached release destination changed during download")
+ return destination, artifact["sha256"]
+ finally:
+ temporary.unlink(missing_ok=True)
+
+expected_hash = sys.argv[2]
+if sys.argv[4] not in ("", "-"):
+ path, expected_hash = fetch_release(sys.argv[4], sys.argv[5], sys.argv[6], sys.argv[7] == "1")
+else:
+ path = Path(sys.argv[1]).absolute()
+match = re.fullmatch(r"nanobot_ai-(\d+\.\d+\.\d+(?:\.dev\d+|\.post\d+)?)-py3-none-(macosx_13_0_(?:arm64|x86_64)|manylinux_2_17_(?:aarch64|x86_64)|win_amd64)\.whl", path.name)
+if not match or path.is_symlink() or not path.is_file() or not re.fullmatch(r"[0-9a-f]{64}", expected_hash):
+ raise SystemExit("Expected a saved native nanobot wheel and its published SHA-256")
+with path.open("rb") as stream:
+ if hashlib.file_digest(stream, "sha256").hexdigest() != expected_hash:
+ raise SystemExit("Wheel SHA-256 mismatch; no package manager was started")
+version = match[1]
+with ZipFile(path) as wheel:
+ metadata_path = f"nanobot_ai-{version}.dist-info/METADATA"
+ if wheel.getinfo(metadata_path).file_size > 256 * 1024:
+ raise SystemExit("Wheel metadata exceeds its size limit")
+ metadata = BytesParser().parsebytes(wheel.read(metadata_path))
+ if metadata["Name"] != "nanobot-ai" or metadata["Version"] != version:
+ raise SystemExit("Wheel identity does not match its filename")
+extras = []
+record = Path(sys.argv[3])
+if sys.argv[3] != "-" and record.is_file():
+ if record.stat().st_size > 1024 * 1024:
+ raise SystemExit("pipx installation record is too large; inspect it before updating")
+ spec = json.loads(record.read_text(encoding="utf-8"))["main_package"]["package_or_url"]
+ extra_match = re.match(r"(?i)^nanobot[-_.]ai\[([a-z0-9_., -]+)\]", spec)
+ if extra_match:
+ extras = sorted({re.sub(r"[-_.]+", "-", extra.strip().lower()) for extra in extra_match[1].split(",")})
+ if any(not re.fullmatch(r"[a-z0-9]+(?:-[a-z0-9]+)*", extra) for extra in extras):
+ raise SystemExit("Cannot preserve pipx extras; review the installation manually")
+ elif "[" in spec:
+ raise SystemExit("Cannot preserve pipx extras; review the installation manually")
+ provided = {re.sub(r"[-_.]+", "-", extra.lower()) for extra in metadata.get_all("Provides-Extra", [])}
+ if not set(extras) <= provided:
+ raise SystemExit("The target wheel does not provide all existing pipx extras")
+requirement = "nanobot-ai" + ("[" + ",".join(extras) + "]" if extras else "")
+print(requirement + " @ " + path.as_uri() + "|" + version)
+'@
+ # Nonempty sentinels keep positional arguments intact on Windows PowerShell 5.1.
+ $WheelArg = if ($Wheel) { $Wheel } else { "-" }
+ $HashArg = if ($Sha256) { $Sha256 } else { "-" }
+ $ReleaseArg = if ($Release) { $Release } else { "-" }
+ $ManifestHashArg = if ($ManifestSha256) { $ManifestSha256 } else { "-" }
+ $DryRunArg = if ($DryRun) { "1" } else { "0" }
+ $WheelIdentity = $Verify | & $TargetPython -I - $WheelArg $HashArg $OwnerRecord $ReleaseArg $ManifestHashArg $ReleaseCache $DryRunArg
+ if ($LASTEXITCODE -ne 0 -or -not $WheelIdentity) { Fail "Release verification failed; no installation was attempted." }
+ $InstallTarget, $ExpectedVersion = $WheelIdentity -split '\|', 2
+ $InstallSource = "verified wheel $ExpectedVersion"
+ if ($Release -and $DryRun) {
+ Write-Info "Selected nanobot $ExpectedVersion from verified release metadata; its wheel was not downloaded."
+ } else {
+ Write-Info "Verified nanobot $ExpectedVersion. Keep the downloaded wheel at its current path."
+ }
+}
if ($DryRun) {
Write-Info "Dry run: would install or upgrade nanobot from $InstallSource."
- if (Test-VirtualEnv $Python) {
+ if ($InstallMethod -eq "python") {
Write-Info "Dry run: active virtual environment detected; would run: $Python -m pip install --upgrade $InstallTarget"
- Write-Info "Dry run: would run nanobot as: $Python -m nanobot"
- } elseif (Get-Command uv -ErrorAction SilentlyContinue) {
- Write-Info "Dry run: would run: uv tool install --python $Python --force --upgrade $InstallTarget"
- Write-Info "Dry run: would run nanobot as: uv tool run --from $InstallTarget nanobot"
- } elseif (Get-Command pipx -ErrorAction SilentlyContinue) {
- Write-Info "Dry run: would run: pipx install --python $Python --force $InstallTarget"
- Write-Info "Dry run: would run nanobot as: pipx run --spec $InstallTarget nanobot"
+ Write-Info "Dry run: would start nanobot with this environment's Python in isolated mode."
+ } elseif ($InstallMethod -eq "uv") {
+ Write-Info "Dry run: would install with uv tool install, or use uv tool upgrade for an existing installation."
+ Write-Info "Dry run: would start nanobot from its persistent uv tool environment."
+ } elseif ($InstallMethod -eq "pipx") {
+ Write-Info "Dry run: would review pipx installation settings before upgrading an existing environment."
+ Write-Info "Dry run: would start nanobot from its persistent pipx environment."
} else {
$HomeDir = if ($env:HOME) { $env:HOME } elseif ($env:USERPROFILE) { $env:USERPROFILE } else { "~" }
$VenvDir = if ($env:NANOBOT_VENV) { $env:NANOBOT_VENV } else { Join-Path $HomeDir ".nanobot\venv" }
Write-Info "Dry run: would create or reuse a dedicated virtual environment: $VenvDir"
Write-Info "Dry run: would run: $VenvDir\Scripts\python.exe -m pip install --upgrade $InstallTarget"
- Write-Info "Dry run: would run nanobot as: $VenvDir\Scripts\python.exe -m nanobot"
+ Write-Info "Dry run: would start nanobot with $VenvDir\Scripts\python.exe in isolated mode."
}
if ($env:NANOBOT_SKIP_WIZARD -eq "1") {
Write-Info "Dry run: would skip automatic setup because NANOBOT_SKIP_WIZARD=1."
@@ -285,31 +641,15 @@ if ($DryRun) {
return
}
-if (Test-VirtualEnv $Python) {
+if ($InstallMethod -eq "python") {
Install-WithActivePython
+} elseif ($InstallMethod -eq "uv") {
+ Install-WithUv
+} elseif ($InstallMethod -eq "pipx") {
+ Install-WithPipx
} else {
- $Installed = $false
-
- if (Get-Command uv -ErrorAction SilentlyContinue) {
- Install-WithUv
- $Installed = $script:LastInstallSucceeded
- if (-not $Installed) {
- Write-Info "uv tool install failed. Trying the next isolated install method..."
- }
- }
-
- if (-not $Installed -and (Get-Command pipx -ErrorAction SilentlyContinue)) {
- Install-WithPipx
- $Installed = $script:LastInstallSucceeded
- if (-not $Installed) {
- Write-Info "pipx install failed. Trying the managed virtual environment..."
- }
- }
-
- if (-not $Installed) {
- Write-Info "Using a dedicated virtual environment to avoid system pip."
- Install-WithManagedVenv
- }
+ Write-Info "Using a dedicated virtual environment to avoid system pip."
+ Install-WithManagedVenv
}
Write-Info "Installed nanobot:"
@@ -347,3 +687,6 @@ if ($LASTEXITCODE -ne 0) {
}
Write-Info "Done. Try: $(Get-NanobotCommand) agent -m `"Hello!`""
+} finally {
+ [Console]::OutputEncoding = $PreviousOutputEncoding
+}
diff --git a/scripts/install.sh b/scripts/install.sh
index 030051be7..41bfd3dfb 100755
--- a/scripts/install.sh
+++ b/scripts/install.sh
@@ -5,8 +5,13 @@ package="nanobot-ai"
install_target="$package"
install_source="PyPI"
dry_run="0"
-nanobot_runner=""
nanobot_python=""
+release_wheel=""
+release_sha256=""
+release_kind=""
+expected_version=""
+release_version=""
+manifest_sha256=""
info() {
printf '%s\n' "$*"
@@ -19,6 +24,10 @@ fail() {
install_failure_hint() {
printf '%s\n' "Error: could not install nanobot from $install_source." >&2
+ if [ -n "$expected_version" ]; then
+ printf '%s\n' "Inspect the original manager error and retry this exact handoff. No setup or other installation was attempted." >&2
+ exit 1
+ fi
printf '%s\n' "If pip mentioned externally-managed-environment, use uv, pipx, or a virtual environment instead of system pip." >&2
printf '%s\n' "You can also run manually:" >&2
printf ' %s\n' "uv tool install --force --upgrade $install_target" >&2
@@ -31,10 +40,16 @@ install_failure_hint() {
usage() {
cat <<'EOF'
-Usage: install.sh [--dry-run]
+Usage: install.sh [--dry-run] [--wheel PATH --sha256 HASH]
+ install.sh [--dry-run] --release VERSION --manifest-sha256 HASH
By default this installs or upgrades nanobot-ai from PyPI.
Use --dry-run to print what would happen without installing or starting setup.
+For a verified release handoff, use --wheel and --sha256 together. Keep that
+downloaded wheel in place; your manager may record it as the installation source.
+Stop affected gateways and back up their data before updating an existing install.
+--release downloads the matching platform wheel from the official release using
+its published manifest hash. This selects one version, not a Preview subscription.
For current main, clone the repository and run `python -m pip install -e .`.
EOF
@@ -63,6 +78,44 @@ raise SystemExit(0 if sys.prefix != sys.base_prefix else 1)
PY
}
+select_install_method() {
+ if python_is_virtual_env; then
+ active_prefix="$("$python_bin" -I -c 'import sys; print(sys.prefix)')"
+ if [ -f "$active_prefix/uv-receipt.toml" ] || [ -f "$active_prefix/pipx_metadata.json" ]; then
+ fail "The active Python belongs to uv or pipx. Deactivate it and rerun this installer so its manager owns the update."
+ fi
+ install_method="python"
+ return
+ fi
+
+ install_method=""
+ existing_count=0
+ if command -v uv >/dev/null 2>&1; then
+ uv_dir="$(uv tool dir)" || fail "Could not inspect the uv tools directory"
+ [ -n "$uv_dir" ] || fail "uv returned an empty tools directory"
+ if [ -e "$uv_dir/$package" ]; then
+ install_method="uv"
+ existing_count=$((existing_count + 1))
+ fi
+ fi
+ if command -v pipx >/dev/null 2>&1; then
+ pipx_dir="$(pipx environment --value PIPX_LOCAL_VENVS)" || fail "Could not inspect the pipx environments directory"
+ [ -n "$pipx_dir" ] || fail "pipx returned an empty environments directory"
+ if [ -e "$pipx_dir/$package" ]; then
+ install_method="pipx"
+ existing_count=$((existing_count + 1))
+ fi
+ fi
+ if [ -n "${NANOBOT_VENV:-}${HOME:-}" ] && [ -f "${NANOBOT_VENV:-${HOME:-}/.nanobot/venv}/pyvenv.cfg" ]; then
+ install_method="managed"
+ existing_count=$((existing_count + 1))
+ fi
+ [ "$existing_count" -le 1 ] || fail "Multiple nanobot installations were found. Use the intended environment's package manager; this installer changed none of them."
+ if [ -z "$install_method" ]; then
+ install_method="managed"
+ fi
+}
+
ensure_pip() {
target_python="$1"
if "$target_python" -m pip --version >/dev/null 2>&1; then
@@ -73,35 +126,36 @@ ensure_pip() {
"$target_python" -m ensurepip --upgrade >/dev/null 2>&1
}
+select_installed_python() {
+ # Keep the venv interpreter path (resolving its symlink would select base Python).
+ # Isolated mode also prevents a checkout/PYTHONPATH from shadowing the new package.
+ nanobot_python="$("$1" -I - "$2" "$expected_version" <<'PY'
+import sys
+from importlib.metadata import distribution
+from pathlib import Path
+
+import nanobot
+
+prefix = Path(sys.prefix).resolve()
+package = Path(nanobot.__file__).resolve()
+expected = sys.argv[1]
+if sys.prefix == sys.base_prefix or (expected and prefix != Path(expected).resolve()):
+ raise SystemExit("The installed interpreter does not belong to the expected virtual environment")
+if not package.is_relative_to(prefix) or package != Path(distribution("nanobot-ai").locate_file("nanobot/__init__.py")).resolve():
+ raise SystemExit("nanobot imports from outside the installed package")
+if sys.argv[2] and distribution("nanobot-ai").version != sys.argv[2]:
+ raise SystemExit("The requested version was not installed. Check manager pins or locks; no setup was started.")
+print(Path(sys.executable).absolute())
+PY
+ )" || fail "The installed nanobot environment could not be verified. No setup or other installation was attempted."
+}
+
run_nanobot() {
- case "$nanobot_runner" in
- uv)
- uv tool run --from "$install_target" nanobot "$@"
- ;;
- pipx)
- pipx run --spec "$install_target" nanobot "$@"
- ;;
- python)
- "$nanobot_python" -m nanobot "$@"
- ;;
- *)
- fail "nanobot was installed, but no runner was configured"
- ;;
- esac
+ "$nanobot_python" -I -m nanobot "$@"
}
nanobot_try_command() {
- case "$nanobot_runner" in
- uv)
- printf '%s\n' "uv tool run --from $install_target nanobot"
- ;;
- pipx)
- printf '%s\n' "pipx run --spec $install_target nanobot"
- ;;
- python)
- printf '%s\n' "$nanobot_python -m nanobot"
- ;;
- esac
+ "$python_bin" -I -c 'import shlex, sys; print(shlex.quote(sys.argv[1]) + " -I -m nanobot")' "$nanobot_python"
}
is_fresh_nanobot_install() {
@@ -132,20 +186,64 @@ install_with_active_python() {
info "Detected an active virtual environment. Installing into it..."
ensure_pip "$python_bin" || return 1
"$python_bin" -m pip install --upgrade "$install_target" || return 1
- nanobot_runner="python"
- nanobot_python="$python_bin"
+ select_installed_python "$python_bin" ""
}
install_with_uv() {
info "Installing or upgrading nanobot from $install_source with uv tool..."
- uv tool install --python "$python_bin" --force --upgrade "$install_target" || return 1
- nanobot_runner="uv"
+ tool_dir="$(uv tool dir)" || fail "Could not locate the uv tools directory"
+ [ -n "$tool_dir" ] || fail "uv returned an empty tools directory"
+ if [ -f "$tool_dir/$package/uv-receipt.toml" ]; then
+ uv tool upgrade "$install_target" || fail "uv could not upgrade nanobot. Resolve the error above and retry; no other installation was attempted."
+ elif [ -e "$tool_dir/$package" ]; then
+ fail "The uv environment exists without its installation record. Repair it with uv before rerunning this installer."
+ else
+ uv tool install --python "$python_bin" "$install_target" ||
+ fail "uv could not install nanobot. Resolve the error above and retry; no other installation was attempted."
+ fi
+ select_installed_python "$tool_dir/$package/bin/python" "$tool_dir/$package"
}
install_with_pipx() {
info "Installing or upgrading nanobot from $install_source with pipx..."
- pipx install --python "$python_bin" --force "$install_target" || return 1
- nanobot_runner="pipx"
+ tool_dir="$(pipx environment --value PIPX_LOCAL_VENVS)" || fail "Could not locate the pipx environments directory"
+ [ -n "$tool_dir" ] || fail "pipx returned an empty environments directory"
+ if [ -f "$tool_dir/$package/pipx_metadata.json" ]; then
+ # Bootstrap must not import the installed application or expose private options.
+ "$python_bin" -I - "$tool_dir/$package/pipx_metadata.json" "$expected_version" <<'PY' || fail "Review the original pipx installation settings; no installation was attempted."
+import json
+import re
+import sys
+from pathlib import Path
+
+try:
+ path = Path(sys.argv[1])
+ if path.is_symlink() or path.stat().st_size > 1024 * 1024:
+ raise ValueError
+ record = json.loads(path.read_text(encoding="utf-8"))
+ main = record["main_package"]
+ name = r"(?i)nanobot[-_.]ai(?:\[[a-z0-9_., -]+\])?"
+ spec = main["package_or_url"]
+ # An explicit wheel may replace an earlier wheel source, but not discard
+ # registry constraints, lock workflows or recorded installer options.
+ allowed = re.fullmatch(name, spec) or (sys.argv[2] and re.fullmatch(name + r"\s*@\s*\S+\.whl", spec))
+ if record["pipx_metadata_version"] not in {"0.5", "0.12"} or not allowed or main.get("pip_args") or main.get("lock_file"):
+ raise ValueError
+except (OSError, ValueError, KeyError, TypeError):
+ raise SystemExit("Cannot safely reuse pipx installation settings; inspect the original requirement and options.") from None
+PY
+ if [ -n "$expected_version" ]; then
+ pipx install --skip-maintenance --upgrade "$install_target" || fail "pipx could not upgrade nanobot. Resolve the error above and retry; no other installation was attempted."
+ else
+ pipx upgrade "$package" || fail "pipx could not upgrade nanobot. Resolve the error above and retry; no other installation was attempted."
+ fi
+ elif [ -e "$tool_dir/$package" ]; then
+ fail "The pipx environment exists without its installation record. Repair it with pipx before rerunning this installer."
+ else
+ pipx install --python "$python_bin" "$install_target" ||
+ fail "pipx could not install nanobot. Resolve the error above and retry; no other installation was attempted."
+ fi
+ select_installed_python "$tool_dir/$package/bin/python" "$tool_dir/$package"
}
write_managed_wrapper() {
@@ -158,10 +256,11 @@ write_managed_wrapper() {
return 0
fi
+ nanobot_command="$(nanobot_try_command)"
cat > "$wrapper" <<EOF
#!/bin/sh
# Generated by nanobot installer.
-exec "$nanobot_python" -m nanobot "\$@"
+exec $nanobot_command "\$@"
EOF
chmod +x "$wrapper" || return 0
@@ -176,10 +275,33 @@ install_with_managed_venv() {
venv_dir="${NANOBOT_VENV:-$HOME/.nanobot/venv}"
venv_python="$venv_dir/bin/python"
-
if [ ! -x "$venv_python" ]; then
info "Creating a dedicated virtual environment at $venv_dir..."
mkdir -p "$(dirname "$venv_dir")"
+ # Persist selection before venv/pip work, so a failed first install can
+ # resume as the same managed environment. This is not an installed claim.
+ "$python_bin" -I - "$venv_dir" <<'PY' || return 1
+import json, os, sys
+from pathlib import Path
+prefix = Path(sys.argv[1]).resolve()
+if any((prefix / name).exists() for name in ('uv-receipt.toml', 'pipx_metadata.json')):
+ raise SystemExit('This environment belongs to another package manager.')
+prefix.mkdir(parents=True, exist_ok=True)
+path = prefix / 'nanobot-install.json'
+record = {'schema_version': 1, 'owner': 'nanobot-installer', 'environment': str(prefix), 'extras': []}
+if path.is_symlink():
+ raise SystemExit('The installation selection is invalid; no receipt was replaced.')
+if path.exists():
+ if path.stat().st_size > 4096 or json.loads(path.read_bytes()) != record:
+ raise SystemExit('The installation selection changed; no receipt was replaced.')
+else:
+ with path.open('x', encoding='utf-8') as stream:
+ json.dump(record, stream, sort_keys=True)
+ stream.write('\n')
+ stream.flush()
+ os.fsync(stream.fileno())
+ path.chmod(0o600)
+PY
"$python_bin" -m venv "$venv_dir" || return 1
fi
@@ -192,13 +314,25 @@ PY
ensure_pip "$venv_python" || return 1
"$venv_python" -m pip install --upgrade "$install_target" || return 1
- nanobot_runner="python"
- nanobot_python="$venv_python"
+ select_installed_python "$venv_python" "$venv_dir"
write_managed_wrapper
}
while [ "$#" -gt 0 ]; do
case "$1" in
+ --wheel|--sha256|--release|--manifest-sha256)
+ [ "$#" -ge 2 ] || fail "$1 requires a value"
+ case "$1" in --wheel|--sha256) wanted_kind="wheel" ;; *) wanted_kind="release" ;; esac
+ [ -z "$release_kind" ] || [ "$release_kind" = "$wanted_kind" ] || fail "Choose --release or --wheel, not both"
+ release_kind="$wanted_kind"
+ case "$1" in
+ --wheel) release_wheel="$2" ;;
+ --sha256) release_sha256="$2" ;;
+ --release) release_version="$2" ;;
+ --manifest-sha256) manifest_sha256="$2" ;;
+ esac
+ shift
+ ;;
--dev)
fail "--dev installed an untracked main snapshot and is no longer supported; clone the repository and run 'python -m pip install -e .' instead"
;;
@@ -229,23 +363,229 @@ else
fi
info "Using Python: $("$python_bin" --version 2>&1)"
+select_install_method
+
+if [ -n "$release_kind" ]; then
+ if [ "$release_kind" = "release" ]; then
+ [ -n "$release_version" ] && [ -n "$manifest_sha256" ] || fail "--release and --manifest-sha256 must be supplied together"
+ [ -z "$release_wheel$release_sha256" ] || fail "Choose --release or --wheel, not both"
+ [ -n "${HOME:-}" ] || fail "HOME is required to retain the downloaded release"
+ else
+ [ -n "$release_wheel" ] && [ -n "$release_sha256" ] || fail "--wheel and --sha256 must be supplied together"
+ fi
+ target_python="$python_bin"
+ case "$install_method" in
+ uv) [ ! -x "$uv_dir/$package/bin/python" ] || target_python="$uv_dir/$package/bin/python" ;;
+ pipx) [ ! -x "$pipx_dir/$package/bin/python" ] || target_python="$pipx_dir/$package/bin/python" ;;
+ managed)
+ candidate_python="${NANOBOT_VENV:-${HOME:-}/.nanobot/venv}/bin/python"
+ [ ! -x "$candidate_python" ] || target_python="$candidate_python"
+ ;;
+ esac
+ owner_record="-"
+ if [ "$install_method" = "pipx" ]; then owner_record="$pipx_dir/$package/pipx_metadata.json"; fi
+ wheel_identity="$("$target_python" -I - "$release_wheel" "$release_sha256" "$owner_record" "$release_version" "$manifest_sha256" "${NANOBOT_RELEASE_CACHE:-${HOME:-}/.nanobot/downloads/releases}" "$dry_run" <<'PY'
+import hashlib
+import json
+import re
+import sys
+from email.parser import BytesParser
+from pathlib import Path
+from zipfile import ZipFile
+
+import os
+import platform
+import struct
+import sysconfig
+import tempfile
+from urllib.parse import urlsplit
+from urllib.request import HTTPRedirectHandler, Request, build_opener
+
+# Bootstrap has no installed nanobot/packaging dependency. This closed platform
+# set matches the five published wheel tags; the owner still checks compatibility.
+def native_platform():
+ if struct.calcsize("P") != 8:
+ raise SystemExit("No native release wheel is available for 32-bit Python")
+ machine = platform.machine().lower()
+ if sys.platform == "darwin":
+ if int(platform.mac_ver()[0].split(".")[0]) < 13:
+ raise SystemExit("The native release requires macOS 13 or newer")
+ if machine in ("arm64", "x86_64"):
+ return "macosx_13_0_" + machine
+ elif sys.platform == "linux":
+ try:
+ libc = os.confstr("CS_GNU_LIBC_VERSION") or ""
+ except (ValueError, OSError):
+ libc = ""
+ if not re.fullmatch(r"glibc \d+\.\d+", libc) or tuple(map(int, libc.split()[1].split("."))) < (2, 17):
+ raise SystemExit("The native release requires glibc 2.17+; no musl wheel is published")
+ if machine in ("aarch64", "x86_64"):
+ return "manylinux_2_17_" + machine
+ elif sys.platform == "win32" and sysconfig.get_platform() == "win-amd64":
+ return "win_amd64"
+ raise SystemExit("No native release wheel is published for this Python platform")
+
+def checked_url(url):
+ parsed = urlsplit(url)
+ if (parsed.scheme != "https" or parsed.hostname not in
+ {"github.com", "release-assets.githubusercontent.com", "objects.githubusercontent.com"}
+ or parsed.username is not None or parsed.password is not None
+ or parsed.port not in (None, 443) or parsed.fragment):
+ raise SystemExit("Release download redirected outside the approved HTTPS hosts")
+ return url
+
+class ReleaseRedirect(HTTPRedirectHandler):
+ max_redirections = 4
+ max_repeats = 1
+
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
+ checked_url(newurl)
+ return super().redirect_request(req, fp, code, msg, headers, newurl)
+
+def fetch_release(version, manifest_hash, cache, dry_run):
+ number = r"(?:0|[1-9]\d*)"
+ if not re.fullmatch(rf"{number}\.{number}\.{number}(?:\.dev{number}|\.post{number})?", version):
+ raise SystemExit("Expected a canonical release version, not a branch or URL")
+ if not re.fullmatch(r"[0-9a-f]{64}", manifest_hash):
+ raise SystemExit("A trusted published manifest SHA-256 is required")
+ selected_platform = native_platform()
+ base = "https://github.com/HKUDS/nanobot/releases/download/v" + version + "/"
+ opener = build_opener(ReleaseRedirect())
+ with opener.open(Request(checked_url(base + "release-manifest.json"),
+ headers={"Accept-Encoding": "identity"}), timeout=20) as response:
+ payload = response.read(64 * 1024 + 1)
+ if len(payload) > 64 * 1024 or hashlib.sha256(payload).hexdigest() != manifest_hash:
+ raise SystemExit("Release manifest size or SHA-256 mismatch")
+ manifest = json.loads(payload)
+ if (not isinstance(manifest, dict) or type(manifest.get("schema_version")) is not int
+ or manifest["schema_version"] != 1 or manifest.get("version") != version
+ or set(manifest) != {"schema_version", "version", "source_commit", "candidate_commit",
+ "requires_python", "artifacts"}):
+ raise SystemExit("Unsupported or mismatched release manifest")
+ for key in ("source_commit", "candidate_commit"):
+ if not isinstance(manifest[key], str) or not re.fullmatch(r"[0-9a-f]{40}", manifest[key]):
+ raise SystemExit("Invalid release commit identity")
+ if not isinstance(manifest["requires_python"], str) or not 0 < len(manifest["requires_python"]) <= 200:
+ raise SystemExit("Invalid Python requirement in release manifest")
+ targets = {"darwin-arm64": "macosx_13_0_arm64", "darwin-x64": "macosx_13_0_x86_64",
+ "linux-arm64": "manylinux_2_17_aarch64", "linux-x64": "manylinux_2_17_x86_64",
+ "win32-x64": "win_amd64"}
+ expected = {f"nanobot_ai-{version}-py3-none-{tag}.whl" for tag in targets.values()}
+ expected.add(f"nanobot_ai-{version}.tar.gz")
+ for target in targets:
+ name = "nanobot-tui-" + target + (".exe" if target == "win32-x64" else "") + ".zip"
+ expected.update((name, name + ".sha256"))
+ artifacts = manifest["artifacts"]
+ if (not isinstance(artifacts, list) or len(artifacts) != 16
+ or any(not isinstance(item, dict) or set(item) != {"filename", "size", "sha256"}
+ or not isinstance(item["filename"], str) or type(item["size"]) is not int
+ or not 0 < item["size"] <= 2 * 1024**3
+ or not isinstance(item["sha256"], str) or not re.fullmatch(r"[0-9a-f]{64}", item["sha256"])
+ for item in artifacts)
+ or {item["filename"] for item in artifacts} != expected):
+ raise SystemExit("Release manifest does not contain the complete matching artifact set")
+ filename = f"nanobot_ai-{version}-py3-none-{selected_platform}.whl"
+ artifact = next(item for item in artifacts if item["filename"] == filename)
+ if dry_run:
+ print("nanobot-ai @ " + base + filename + "#sha256=" + artifact["sha256"] + "|" + version)
+ raise SystemExit(0)
+ directory = Path(cache).expanduser().absolute() / version / artifact["sha256"]
+ directory.mkdir(parents=True, exist_ok=True, mode=0o700)
+ destination = directory / filename
+ if destination.exists() or destination.is_symlink():
+ if destination.is_symlink() or not destination.is_file() or destination.stat().st_size != artifact["size"]:
+ raise SystemExit("Invalid cached release file; inspect the release download directory")
+ return destination, artifact["sha256"]
+ descriptor, name = tempfile.mkstemp(prefix=".download-", suffix=".part", dir=directory)
+ temporary = Path(name)
+ try:
+ size = 0
+ digest = hashlib.sha256()
+ with os.fdopen(descriptor, "wb") as output:
+ with opener.open(Request(checked_url(base + filename),
+ headers={"Accept-Encoding": "identity"}), timeout=20) as response:
+ while chunk := response.read(64 * 1024):
+ size += len(chunk)
+ if size > artifact["size"]:
+ raise SystemExit("Release wheel exceeds its verified size")
+ digest.update(chunk)
+ output.write(chunk)
+ if size != artifact["size"] or digest.hexdigest() != artifact["sha256"]:
+ raise SystemExit("Release wheel size or SHA-256 mismatch")
+ try:
+ os.link(temporary, destination)
+ except FileExistsError:
+ if destination.is_symlink() or not destination.is_file() or destination.stat().st_size != size:
+ raise SystemExit("The cached release destination changed during download")
+ return destination, artifact["sha256"]
+ finally:
+ temporary.unlink(missing_ok=True)
+
+expected_hash = sys.argv[2]
+if sys.argv[4] not in ("", "-"):
+ path, expected_hash = fetch_release(sys.argv[4], sys.argv[5], sys.argv[6], sys.argv[7] == "1")
+else:
+ path = Path(sys.argv[1]).absolute()
+match = re.fullmatch(r"nanobot_ai-(\d+\.\d+\.\d+(?:\.dev\d+|\.post\d+)?)-py3-none-(macosx_13_0_(?:arm64|x86_64)|manylinux_2_17_(?:aarch64|x86_64)|win_amd64)\.whl", path.name)
+if not match or path.is_symlink() or not path.is_file() or not re.fullmatch(r"[0-9a-f]{64}", expected_hash):
+ raise SystemExit("Expected a saved native nanobot wheel and its published SHA-256")
+with path.open("rb") as stream:
+ if hashlib.file_digest(stream, "sha256").hexdigest() != expected_hash:
+ raise SystemExit("Wheel SHA-256 mismatch; no package manager was started")
+version = match[1]
+with ZipFile(path) as wheel:
+ metadata_path = f"nanobot_ai-{version}.dist-info/METADATA"
+ if wheel.getinfo(metadata_path).file_size > 256 * 1024:
+ raise SystemExit("Wheel metadata exceeds its size limit")
+ metadata = BytesParser().parsebytes(wheel.read(metadata_path))
+ if metadata["Name"] != "nanobot-ai" or metadata["Version"] != version:
+ raise SystemExit("Wheel identity does not match its filename")
+extras = []
+record = Path(sys.argv[3])
+if sys.argv[3] != "-" and record.is_file():
+ if record.stat().st_size > 1024 * 1024:
+ raise SystemExit("pipx installation record is too large; inspect it before updating")
+ spec = json.loads(record.read_text(encoding="utf-8"))["main_package"]["package_or_url"]
+ extra_match = re.match(r"(?i)^nanobot[-_.]ai\[([a-z0-9_., -]+)\]", spec)
+ if extra_match:
+ extras = sorted({re.sub(r"[-_.]+", "-", extra.strip().lower()) for extra in extra_match[1].split(",")})
+ if any(not re.fullmatch(r"[a-z0-9]+(?:-[a-z0-9]+)*", extra) for extra in extras):
+ raise SystemExit("Cannot preserve pipx extras; review the installation manually")
+ elif "[" in spec:
+ raise SystemExit("Cannot preserve pipx extras; review the installation manually")
+ provided = {re.sub(r"[-_.]+", "-", extra.lower()) for extra in metadata.get_all("Provides-Extra", [])}
+ if not set(extras) <= provided:
+ raise SystemExit("The target wheel does not provide all existing pipx extras")
+requirement = "nanobot-ai" + ("[" + ",".join(extras) + "]" if extras else "")
+print(requirement + " @ " + path.as_uri() + "|" + version)
+PY
+ )" || fail "Release verification failed; no installation was attempted."
+ install_target="${wheel_identity%|*}"
+ expected_version="${wheel_identity##*|}"
+ install_source="verified wheel $expected_version"
+ if [ "$release_kind" = "release" ] && [ "$dry_run" = "1" ]; then
+ info "Selected nanobot $expected_version from verified release metadata; its wheel was not downloaded."
+ else
+ info "Verified nanobot $expected_version. Keep the downloaded wheel at its current path."
+ fi
+fi
if [ "$dry_run" = "1" ]; then
info "Dry run: would install or upgrade nanobot from $install_source."
- if python_is_virtual_env; then
+ if [ "$install_method" = "python" ]; then
info "Dry run: active virtual environment detected; would run: $python_bin -m pip install --upgrade $install_target"
- info "Dry run: would run nanobot as: $python_bin -m nanobot"
- elif command -v uv >/dev/null 2>&1; then
- info "Dry run: would run: uv tool install --python $python_bin --force --upgrade $install_target"
- info "Dry run: would run nanobot as: uv tool run --from $install_target nanobot"
- elif command -v pipx >/dev/null 2>&1; then
- info "Dry run: would run: pipx install --python $python_bin --force $install_target"
- info "Dry run: would run nanobot as: pipx run --spec $install_target nanobot"
+ info "Dry run: would start nanobot with this environment's Python in isolated mode."
+ elif [ "$install_method" = "uv" ]; then
+ info "Dry run: would install with uv tool install, or use uv tool upgrade for an existing installation."
+ info "Dry run: would start nanobot from its persistent uv tool environment."
+ elif [ "$install_method" = "pipx" ]; then
+ info "Dry run: would review pipx installation settings before upgrading an existing environment."
+ info "Dry run: would start nanobot from its persistent pipx environment."
else
venv_dir="${NANOBOT_VENV:-$HOME/.nanobot/venv}"
info "Dry run: would create or reuse a dedicated virtual environment: $venv_dir"
info "Dry run: would run: $venv_dir/bin/python -m pip install --upgrade $install_target"
- info "Dry run: would run nanobot as: $venv_dir/bin/python -m nanobot"
+ info "Dry run: would start nanobot with $venv_dir/bin/python in isolated mode."
fi
if [ "${NANOBOT_SKIP_WIZARD:-}" = "1" ]; then
info "Dry run: would skip automatic setup because NANOBOT_SKIP_WIZARD=1."
@@ -259,31 +599,15 @@ if [ "$dry_run" = "1" ]; then
exit 0
fi
-if python_is_virtual_env; then
+if [ "$install_method" = "python" ]; then
install_with_active_python || install_failure_hint
+elif [ "$install_method" = "uv" ]; then
+ install_with_uv
+elif [ "$install_method" = "pipx" ]; then
+ install_with_pipx
else
- installed="0"
-
- if command -v uv >/dev/null 2>&1; then
- if install_with_uv; then
- installed="1"
- else
- info "uv tool install failed. Trying the next isolated install method..."
- fi
- fi
-
- if [ "$installed" != "1" ] && command -v pipx >/dev/null 2>&1; then
- if install_with_pipx; then
- installed="1"
- else
- info "pipx install failed. Trying the managed virtual environment..."
- fi
- fi
-
- if [ "$installed" != "1" ]; then
- info "Using a dedicated virtual environment to avoid system pip."
- install_with_managed_venv || install_failure_hint
- fi
+ info "Using a dedicated virtual environment to avoid system pip."
+ install_with_managed_venv || install_failure_hint
fi
info "Installed nanobot:"
diff --git a/scripts/release_candidate.py b/scripts/release_candidate.py
new file mode 100644
index 000000000..b30b4485d
--- /dev/null
+++ b/scripts/release_candidate.py
@@ -0,0 +1,363 @@
+"""Prepare and verify an exact release candidate without publishing anything.
+
+Preparation creates a separate checkout. Verification writes a manifest only after
+all five wheels, the sdist and licensed TUI archives pass their structural checks.
+Native execution, CI approval and public-download checks remain separate gates.
+"""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import os
+import re
+import shutil
+import stat
+import subprocess
+import tempfile
+import tomllib
+from email.parser import BytesParser
+from fnmatch import fnmatchcase
+from pathlib import Path
+
+from packaging.version import Version
+
+from nanobot.releases import (
+ PLATFORMS,
+ ReleaseArtifact,
+ ReleaseManifest,
+ release_filenames,
+ release_version,
+)
+from scripts.build_tui_wheels import build_wheel, release_bundle, source_files, wheel_files
+from scripts.release_install_guide import render_install_guide
+
+ROOT = Path(__file__).resolve().parents[1]
+VERSION_FILES = ("pyproject.toml", "nanobot/__init__.py")
+
+
+def _git(root: Path, *args: str, env: dict[str, str] | None = None, trim: bool = True) -> str:
+ output = subprocess.run(
+ ["git", *args], cwd=root, env=env, check=True, capture_output=True,
+ text=True, encoding="utf-8", timeout=120,
+ ).stdout
+ return output.strip() if trim else output
+
+
+def _commit(value: str) -> str:
+ if not re.fullmatch(r"[0-9a-f]{40}", value):
+ raise ValueError("Use an exact, full source commit SHA, not a branch or tag")
+ return value
+
+
+def preview_version(base: str, sequence: int) -> str:
+ release_version(base)
+ parsed = Version(base)
+ if parsed.is_prerelease or parsed.is_postrelease or sequence < 1:
+ raise ValueError("Use a stable base and a positive preview sequence")
+ return f"{base}.dev{sequence}"
+
+
+def _version_changes(pyproject: str, init: str, version: str) -> dict[str, str]:
+ current = tomllib.loads(pyproject)["project"]["version"]
+ updated_project, project_count = re.subn(
+ rf'(?m)^version = "{re.escape(current)}"$', f'version = "{version}"', pyproject,
+ )
+ updated_init, init_count = re.subn(
+ rf'return _read_pyproject_version\(\) or "{re.escape(current)}"',
+ f'return _read_pyproject_version() or "{version}"', init,
+ )
+ if project_count != 1 or init_count != 1:
+ raise ValueError("Package and fallback version declarations need maintainer review")
+ return dict(zip(VERSION_FILES, (updated_project, updated_init), strict=True))
+
+
+def prepare_preview(root: Path, output: Path, *, source_commit: str, base: str, sequence: int) -> dict[str, str]:
+ source_commit = _commit(source_commit)
+ version = preview_version(base, sequence)
+ root, output = root.resolve(), output.resolve()
+ if output.exists() or output == root or root in output.parents:
+ raise ValueError("Candidate output must be a new directory outside the source checkout")
+ if _git(root, "rev-parse", f"{source_commit}^{{commit}}") != source_commit:
+ raise ValueError("Source commit is not available in this repository")
+ original = {name: _git(root, "show", f"{source_commit}:{name}", trim=False) for name in VERSION_FILES}
+ current = Version(tomllib.loads(original["pyproject.toml"])["project"]["version"])
+ if Version(base).release < current.release or _git(root, "tag", "--list", f"v{base}"):
+ raise ValueError("Preview base must not precede the source or reuse an existing stable tag")
+ changes = _version_changes(original["pyproject.toml"], original["nanobot/__init__.py"], version)
+ # A separate clone preserves the source parent without touching the caller's worktree.
+ _git(root, "clone", "--shared", "--no-checkout", "-c", "core.autocrlf=false", str(root), str(output))
+ hooks = output / ".git" / "candidate-hooks"
+ hooks.mkdir()
+ _git(output, "-c", f"core.hooksPath={hooks}", "checkout", "--detach", source_commit)
+ for name, content in changes.items():
+ (output / name).write_text(content, encoding="utf-8", newline="\n")
+ _git(output, "add", "--", *VERSION_FILES)
+ timestamp = _git(root, "show", "-s", "--format=%cI", source_commit)
+ env = dict(os.environ)
+ for role in ("AUTHOR", "COMMITTER"):
+ env[f"GIT_{role}_NAME"] = "nanobot release"
+ env[f"GIT_{role}_EMAIL"] = "[email protected]"
+ env[f"GIT_{role}_DATE"] = timestamp
+ _git(output, "-c", "commit.gpgsign=false", "-c", f"core.hooksPath={hooks}",
+ "commit", "-m", f"Prepare {version} from {source_commit}", env=env)
+ return {"version": version, "source_commit": source_commit,
+ "candidate_commit": _git(output, "rev-parse", "HEAD")}
+
+
+def _candidate_identity(root: Path, source_commit: str) -> tuple[str, str, str]:
+ _commit(source_commit)
+ candidate_commit = _git(root, "rev-parse", "HEAD")
+ if _git(root, "status", "--porcelain", "--untracked-files=no"):
+ raise ValueError("Candidate has uncommitted tracked changes")
+ metadata = tomllib.loads((root / "pyproject.toml").read_text(encoding="utf-8"))["project"]
+ version, requires_python = release_version(metadata["version"]), metadata["requires-python"]
+ if source_commit != candidate_commit:
+ if _git(root, "rev-parse", "HEAD^") != source_commit:
+ raise ValueError("Candidate must be a direct child of its exact source commit")
+ original = {name: _git(root, "show", f"{source_commit}:{name}", trim=False) for name in VERSION_FILES}
+ expected = _version_changes(original["pyproject.toml"], original["nanobot/__init__.py"], version)
+ changed = set(_git(root, "diff", "--name-only", source_commit, "HEAD").splitlines())
+ if changed != set(VERSION_FILES) or any(
+ (root / name).read_text(encoding="utf-8") != text for name, text in expected.items()
+ ):
+ raise ValueError("Candidate contains changes beyond the two version declarations")
+ return version, requires_python, candidate_commit
+
+
+def _source_payload(root: Path, source: dict[str, bytes], prefix: str) -> dict[str, bytes]:
+ """Bind shipped application files to the clean candidate, not its commit label."""
+ tracked = set(_git(root, "ls-files", "-z", trim=False).split("\0")) - {""}
+ build = tomllib.loads((root / "pyproject.toml").read_text(encoding="utf-8"))["tool"]["hatch"]["build"]
+ # The sdist ships the tracked nanobot tree. Read its actual exclusions rather
+ # than maintaining a second list of channel test directories here.
+ exclusions = [*build.get("exclude", []), *build["targets"]["sdist"].get("exclude", [])]
+ expected = {name: name for name in tracked if name.startswith("nanobot/")
+ and not any(fnmatchcase(name, pattern) for pattern in exclusions)}
+ # The build hook copies tracked docs into the built-in documentation skill.
+ # Verify both copies: rebuilding the sdist must use the same reviewed bytes.
+ for name in tracked:
+ if (name.startswith("docs/") and name.endswith(".md")
+ and not any(fnmatchcase(name, pattern) for pattern in exclusions)):
+ if source.get(prefix + name) != (root / name).read_bytes():
+ raise ValueError(f"Source documentation differs from the candidate: {name}")
+ expected["nanobot/skills/nanobot-document/references/" + name.removeprefix("docs/")] = name
+ payload = {name.removeprefix(prefix): data for name, data in source.items()
+ if name.startswith(prefix + "nanobot/")}
+ generated = {name for name in payload if name == "nanobot/_build_commit.txt"
+ or name.startswith("nanobot/web/dist/")}
+ if payload.keys() - generated != expected.keys():
+ raise ValueError("Source application payload has missing or unexpected files")
+ for name, data in payload.items():
+ if name in generated:
+ continue
+ if data != (root / expected[name]).read_bytes():
+ raise ValueError(f"Source application payload differs from the candidate: {name}")
+ return payload
+
+
+def verify_candidate(root: Path, artifacts: Path, *, source_commit: str) -> ReleaseManifest:
+ version, requires_python, candidate_commit = _candidate_identity(root, source_commit)
+ expected = release_filenames(version)
+ present = {path.name for path in artifacts.iterdir()}
+ if present - {"release-manifest.json"} != expected:
+ raise ValueError("Artifact directory must contain exactly the complete release upload set")
+ for name in expected:
+ if (artifacts / name).is_symlink() or not (artifacts / name).is_file():
+ raise ValueError(f"Release artifact must be a regular file: {name}")
+ commit_bytes = (candidate_commit + "\n").encode()
+ source = source_files((artifacts / f"nanobot_ai-{version}.tar.gz").read_bytes())
+ prefix = f"nanobot_ai-{version}/"
+ source_metadata = BytesParser().parsebytes(source[f"{prefix}PKG-INFO"])
+ if (source_metadata["Name"], source_metadata["Version"], source_metadata["Requires-Python"]) != (
+ "nanobot-ai", version, requires_python,
+ ):
+ raise ValueError("Source distribution metadata differs from the candidate")
+ for name in VERSION_FILES:
+ if source[f"{prefix}{name}"] != (root / name).read_bytes():
+ raise ValueError(f"Source distribution differs from candidate: {name}")
+ if (source.get(f"{prefix}nanobot/_build_commit.txt") != commit_bytes
+ or not source.get(f"{prefix}nanobot/web/dist/index.html")):
+ raise ValueError("Source distribution must contain the candidate commit and built WebUI")
+ payload = _source_payload(root, source, prefix)
+ for target, platform in PLATFORMS.items():
+ wheel = artifacts / f"nanobot_ai-{version}-py3-none-{platform}.whl"
+ files, modes, info = wheel_files(wheel, version, platform=platform)
+ package_metadata = BytesParser().parsebytes(files[f"{info}/METADATA"])
+ if package_metadata["Requires-Python"] != requires_python:
+ raise ValueError("Wheel Python requirement differs from the candidate")
+ if files.get("nanobot/_build_commit.txt") != commit_bytes:
+ raise ValueError("Wheel build commit differs from the candidate")
+ if not files.get("nanobot/web/dist/index.html"):
+ raise ValueError("Wheel is missing its compiled WebUI")
+ application = {name: data for name, data in files.items()
+ if name.startswith("nanobot/") and not name.startswith("nanobot/tui/bin/")}
+ if application != payload:
+ raise ValueError(f"Wheel application payload differs from the source distribution: {target}")
+ bundle = release_bundle(artifacts, target, root=root)
+ embedded = {name.removeprefix("nanobot/tui/bin/"): data for name, data in files.items()
+ if name.startswith("nanobot/tui/bin/")}
+ if embedded != bundle:
+ raise ValueError("Wheel and fallback TUI archive differ")
+ asset = f"nanobot-tui-{target}" + (".exe" if target == "win32-x64" else "")
+ mode = modes[f"nanobot/tui/bin/{asset}"]
+ if not stat.S_ISREG(mode) or stat.S_IMODE(mode) != 0o755:
+ raise ValueError("Installed TUI must retain executable permissions")
+ records: list[ReleaseArtifact] = []
+ for name in sorted(expected):
+ path = artifacts / name
+ with path.open("rb") as stream:
+ digest = hashlib.file_digest(stream, "sha256").hexdigest()
+ records.append(ReleaseArtifact(filename=name, size=path.stat().st_size, sha256=digest))
+ return ReleaseManifest(
+ version=version, source_commit=source_commit, candidate_commit=candidate_commit,
+ requires_python=requires_python,
+ artifacts=records,
+ )
+
+
+def _write_candidate_text(payload: str, output: Path) -> None:
+ if output.exists():
+ if output.read_text(encoding="utf-8") == payload:
+ return
+ raise FileExistsError(f"Existing {output.name} differs; do not overwrite candidate evidence")
+ with tempfile.TemporaryDirectory(prefix=".candidate-report-", dir=output.parent) as temporary:
+ candidate = Path(temporary) / "report"
+ candidate.write_text(payload, encoding="utf-8")
+ output.hardlink_to(candidate)
+
+
+def write_manifest(manifest: ReleaseManifest, output: Path) -> None:
+ _write_candidate_text(manifest.model_dump_json(indent=2) + "\n", output)
+
+
+def write_install_guide(root: Path, artifacts: Path, output: Path, *, source_commit: str) -> None:
+ """Reverify the immutable upload set before emitting a manual installation handoff."""
+ if output.resolve().is_relative_to(artifacts.resolve()):
+ raise ValueError("Install guide must be outside the immutable artifact directory")
+ payload = (artifacts / "release-manifest.json").read_bytes()
+ recorded = ReleaseManifest.model_validate_json(payload)
+ manifest = verify_candidate(root, artifacts, source_commit=source_commit)
+ if recorded != manifest:
+ raise ValueError("Candidate differs from its recorded release manifest")
+ # Older retained candidates may not have the bootstrap options. Only link a
+ # candidate's scripts when they are the known implementation shipped here.
+ bootstrap = all(
+ (root / "scripts" / name).is_file()
+ and (root / "scripts" / name).read_bytes() == (ROOT / "scripts" / name).read_bytes()
+ for name in ("install.sh", "install.ps1")
+ )
+ digest = hashlib.sha256(payload).hexdigest() if bootstrap else None
+ _write_candidate_text(render_install_guide(manifest, manifest_sha256=digest), output)
+
+
+def assemble_candidate(root: Path, output: Path, *, wheel: Path, sdist: Path,
+ tui_dir: Path, source_commit: str) -> ReleaseManifest:
+ """Assemble in a fresh directory; failed output is never given a manifest."""
+ version, _, _ = _candidate_identity(root, source_commit)
+ if sdist.name != f"nanobot_ai-{version}.tar.gz":
+ raise ValueError("Source distribution filename differs from the candidate")
+ output.mkdir(parents=True, exist_ok=False)
+ for target in PLATFORMS:
+ build_wheel(wheel, tui_dir, output, target, root=root)
+ for name in sorted(release_filenames(version)):
+ if not name.endswith(".whl"):
+ shutil.copyfile(sdist if name == sdist.name else tui_dir / name, output / name)
+ manifest = verify_candidate(root, output, source_commit=source_commit)
+ write_manifest(manifest, output / "release-manifest.json")
+ return manifest
+
+
+def retain_candidate(root: Path, artifacts: Path, output: Path, *, source_commit: str) -> None:
+ """Preserve checked bytes and their source, without publishing or rebuilding.
+
+ A successful handoff has a final handoff.json. Partial copies are not accepted
+ release inputs. The self-contained shallow repository preserves the candidate
+ and its source parent, not unrelated history, untracked files or credentials.
+ """
+ root, artifacts, output = root.resolve(), artifacts.resolve(), output.resolve()
+ if output.is_relative_to(root) or output.is_relative_to(artifacts):
+ raise ValueError("Retained handoff must be outside the checkout and artifact directory")
+ recorded = (artifacts / "release-manifest.json").read_bytes()
+ manifest = verify_candidate(root, artifacts, source_commit=source_commit)
+ if ReleaseManifest.model_validate_json(recorded) != manifest:
+ raise ValueError("Candidate differs from its recorded release manifest")
+ output.mkdir(parents=True, exist_ok=False)
+ retained = output / "artifacts"
+ retained.mkdir()
+ for name in sorted(release_filenames(manifest.version) | {"release-manifest.json"}):
+ shutil.copyfile(artifacts / name, retained / name)
+ # Check the actual copies, not a report for the source directory. A future
+ # publisher must consume these bytes and verify this manifest again.
+ if ((retained / "release-manifest.json").read_bytes() != recorded
+ or verify_candidate(root, retained, source_commit=source_commit) != manifest):
+ raise ValueError("Retained artifacts differ from the reviewed candidate")
+ source = output / "source.git"
+ with tempfile.TemporaryDirectory(prefix=".candidate-template-", dir=output) as template:
+ # File transport copies real objects rather than borrowing alternates.
+ # Two commits retain the exact version-only candidate relationship.
+ _git(root, "-c", f"init.templateDir={template}", "clone", "--bare", "--depth", "2",
+ "--single-branch", "--no-tags", root.as_uri(), str(source))
+ (source / "config").write_text("[core]\nrepositoryformatversion = 0\nbare = true\n", encoding="utf-8")
+ _git(source, "fsck", "--full")
+ if _git(source, "rev-parse", "HEAD") != manifest.candidate_commit:
+ raise ValueError("Retained source differs from the candidate")
+ write_install_guide(root, retained, output / "install.md", source_commit=source_commit)
+ _write_candidate_text(json.dumps({
+ "version": manifest.version, "source_commit": source_commit,
+ "candidate_commit": manifest.candidate_commit,
+ "manifest_sha256": hashlib.sha256(recorded).hexdigest(),
+ "source_depth": 2,
+ "published": False,
+ }, indent=2) + "\n", output / "handoff.json")
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--root", type=Path, default=ROOT)
+ commands = parser.add_subparsers(dest="command", required=True)
+ prepare = commands.add_parser("prepare")
+ prepare.add_argument("--source-commit", required=True)
+ prepare.add_argument("--base", required=True)
+ prepare.add_argument("--sequence", type=int, required=True)
+ prepare.add_argument("--output", type=Path, required=True)
+ verify = commands.add_parser("verify")
+ verify.add_argument("--source-commit", required=True)
+ verify.add_argument("--artifacts", type=Path, required=True)
+ instructions = commands.add_parser("instructions")
+ instructions.add_argument("--source-commit", required=True)
+ instructions.add_argument("--artifacts", type=Path, required=True)
+ instructions.add_argument("--output", type=Path, required=True)
+ retain = commands.add_parser("retain")
+ retain.add_argument("--source-commit", required=True)
+ retain.add_argument("--artifacts", type=Path, required=True)
+ retain.add_argument("--output", type=Path, required=True)
+ assemble = commands.add_parser("assemble")
+ assemble.add_argument("--source-commit", required=True)
+ assemble.add_argument("--wheel", type=Path, required=True)
+ assemble.add_argument("--sdist", type=Path, required=True)
+ assemble.add_argument("--tui-dir", type=Path, required=True)
+ assemble.add_argument("--output", type=Path, required=True)
+ args = parser.parse_args()
+ if args.command == "prepare":
+ print(json.dumps(prepare_preview(args.root, args.output, source_commit=args.source_commit,
+ base=args.base, sequence=args.sequence)))
+ elif args.command == "verify":
+ manifest = verify_candidate(args.root, args.artifacts, source_commit=args.source_commit)
+ write_manifest(manifest, args.artifacts / "release-manifest.json")
+ print(manifest.model_dump_json(indent=2))
+ elif args.command == "instructions":
+ write_install_guide(args.root, args.artifacts, args.output, source_commit=args.source_commit)
+ print(f"Candidate install handoff: {args.output}")
+ elif args.command == "retain":
+ retain_candidate(args.root, args.artifacts, args.output, source_commit=args.source_commit)
+ print(f"Retained exact candidate (not published): {args.output}")
+ else:
+ manifest = assemble_candidate(args.root, args.output, wheel=args.wheel, sdist=args.sdist,
+ tui_dir=args.tui_dir, source_commit=args.source_commit)
+ print(manifest.model_dump_json(indent=2))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/release_install_guide.py b/scripts/release_install_guide.py
new file mode 100644
index 000000000..dedb554e0
--- /dev/null
+++ b/scripts/release_install_guide.py
@@ -0,0 +1,215 @@
+"""Render the initial manual install handoff for a verified release candidate.
+
+This is not a channel resolver or an updater. The caller must verify the candidate
+bytes first; public availability, migration notes and native acceptance are release
+gates, not properties inferred from a manifest.
+"""
+
+from __future__ import annotations
+
+import re
+import shlex
+from typing import Literal
+
+from nanobot.releases import PLATFORMS, ReleaseArtifact, ReleaseManifest
+
+Owner = Literal["uv", "pipx", "pip"]
+PLATFORM_LABELS = {
+ "darwin-arm64": "macOS 13+ · Apple silicon",
+ "darwin-x64": "macOS 13+ · Intel x64",
+ "linux-arm64": "Linux · glibc 2.17+ · ARM64",
+ "linux-x64": "Linux · glibc 2.17+ · x64",
+ "win32-x64": "Windows · x64",
+}
+
+# Uses only Python's standard library, so the first preview can be installed before
+# the user's nanobot has a channel-aware updater. The downloaded file is retained:
+# managers can record its location as the installation source.
+VERIFY_AND_INSTALL = '''from pathlib import Path
+import hashlib
+import subprocess
+import sys
+wheel = Path(sys.argv[1]).resolve(strict=True)
+with wheel.open("rb") as stream:
+ digest = hashlib.file_digest(stream, "sha256").hexdigest()
+if wheel.stat().st_size != int(sys.argv[2]) or digest != sys.argv[3]:
+ raise SystemExit("Wheel size or SHA-256 mismatch; no package manager was started.")
+command = sys.argv[4:]
+if command[0] == "python":
+ command[0] = sys.executable
+subprocess.run([*command, "nanobot-ai @ " + wheel.as_uri()], check=True)
+'''
+
+
+def install_command(manifest: ReleaseManifest, artifact: ReleaseArtifact, *,
+ owner: Owner, existing: bool) -> list[str]:
+ """Verify saved bytes before asking the original owner to install that file."""
+ if not artifact.filename.endswith(".whl"):
+ raise ValueError("Install instructions require a platform wheel")
+ if artifact not in manifest.artifacts:
+ raise ValueError("Artifact does not belong to this release")
+ if owner == "uv":
+ command = ["uv", "tool", "upgrade" if existing else "install", "--no-python-downloads"]
+ elif owner == "pipx":
+ command = ["pipx", "install", "--skip-maintenance", *(["--upgrade"] if existing else [])]
+ elif owner == "pip":
+ command = ["python", "-I", "-m", "pip", "install", *(["--upgrade"] if existing else [])]
+ else:
+ raise ValueError(f"Unsupported installation owner: {owner}")
+ return ["python", "-I", "-c", VERIFY_AND_INSTALL, artifact.filename,
+ str(artifact.size), artifact.sha256, *command]
+
+
+def verification_command(owner: Owner, *, windows: bool) -> str:
+ """Inspect the persistent environment, never an ephemeral uvx/pipx run cache."""
+ if owner == "pip":
+ return "python -I -m nanobot --version"
+ directory = "uv tool dir" if owner == "uv" else "pipx environment --value PIPX_LOCAL_VENVS"
+ if windows:
+ return f"& (Join-Path ({directory}) 'nanobot-ai\\Scripts\\python.exe') -I -m nanobot --version"
+ return f'"$({directory})/nanobot-ai/bin/python" -I -m nanobot --version'
+
+
+def render_install_command(command: list[str], *, windows: bool) -> str:
+ """Render install_command's Python helper for the target shell."""
+ if not windows:
+ return shlex.join(command)
+ # Windows PowerShell strips embedded quotes from native -c arguments. Feed
+ # the fixed ASCII helper on stdin instead; wheel identity remains in argv.
+ arguments = " ".join("'" + value.replace("'", "''") + "'" for value in command[4:])
+ return f"@'\n{command[3].rstrip()}\n'@ | python -I - {arguments}"
+
+
+def bootstrap_commands(manifest: ReleaseManifest, manifest_sha256: str) -> tuple[str, str]:
+ """Pin the installer to the candidate and the download to verified manifest bytes."""
+ if not re.fullmatch(r"[0-9a-f]{64}", manifest_sha256):
+ raise ValueError("Use the verified release manifest SHA-256")
+ base = f"https://raw.githubusercontent.com/HKUDS/nanobot/{manifest.candidate_commit}/scripts"
+ unix = f'''(
+ installer_dir="$(mktemp -d)" || exit 1
+ trap 'rm -f "$installer_dir/install.sh"; rmdir "$installer_dir"' 0
+ curl --fail --silent --show-error --location --proto '=https' \\
+ '{base}/install.sh' -o "$installer_dir/install.sh" &&
+ sh "$installer_dir/install.sh" --release '{manifest.version}' \\
+ --manifest-sha256 '{manifest_sha256}'
+)'''
+ windows = f'''$Installer = Join-Path ([IO.Path]::GetTempPath()) ("nanobot-install-" + [guid]::NewGuid() + ".ps1")
+try {{
+ Invoke-WebRequest -UseBasicParsing -Uri '{base}/install.ps1' -OutFile $Installer -ErrorAction Stop
+ & $Installer -Release '{manifest.version}' -ManifestSha256 '{manifest_sha256}'
+ if ($LASTEXITCODE -ne 0) {{ throw "Installation did not complete; review the output above." }}
+}} finally {{
+ Remove-Item -LiteralPath $Installer -ErrorAction SilentlyContinue
+}}'''
+ return unix, windows
+
+
+def render_install_guide(manifest: ReleaseManifest, *, manifest_sha256: str | None = None) -> str:
+ release_url = f"https://github.com/HKUDS/nanobot/releases/tag/v{manifest.version}"
+ lines = [
+ f"# Install nanobot {manifest.version}", "",
+ "> Candidate handoff — not publication approval. Use these commands only after",
+ "> the maintainer has published and publicly verified this exact release, added",
+ "> its changes/migration/recovery notes, and declared its native test coverage.", "",
+ f"- Release: [{manifest.version}]({release_url})",
+ f"- Source commit: `{manifest.source_commit}`",
+ f"- Packaged candidate: `{manifest.candidate_commit}`",
+ f"- Python requirement: `{manifest.requires_python}`", "",
+ "The wheel contains the built WebUI and matching native TUI. Installing nanobot",
+ "itself needs no Bun, Node or Git. Python and third-party dependencies have their",
+ "own requirements. Commands pin this one release; they do not subscribe to Preview.", "",
+ "## Before installing", "",
+ "1. Read this release's changes, known limitations and recovery instructions.",
+ " Prefer a separate environment **and separate data/profile/port** for an early",
+ " preview. A second environment alone does not isolate the default nanobot data.",
+ "2. For an existing install, identify its manager, interpreter and supervisor.",
+ " Finish active tasks, stop all affected writers through that supervisor, and",
+ " back up nanobot configuration/sessions and the owner's install metadata.",
+ " Do not install into a running gateway or assume this guide performs a backup.",
+ "3. Use automatic platform selection when offered below. For the manual route,",
+ " choose the target computer's platform, then **one** owner/operation.",
+ " Fresh commands are only for a new install; existing commands must target the",
+ " same account and manager home. For pip, activate the intended ordinary venv",
+ " and verify `python` belongs to it; never use system Python or a uv/pipx venv.", "",
+ "4. For the manual route, download the linked wheel into a directory you own. Open",
+ " a terminal in that directory. Each command uses Python 3.11+ (`python`) to",
+ " verify the saved file's size and SHA-256 **before** starting the manager.",
+ " For uv/pipx this helper Python does not replace the tool's interpreter.",
+ " Keep the wheel at that path: the manager may record it as the install source.", "",
+ "These commands cover a base `nanobot-ai` installation. If you use extras,",
+ "pipx constraints/options/suffix/lock, custom wrappers or several installations,",
+ "review the recorded",
+ "spec and target explicitly instead of copying a base-package command. Preserve",
+ "extras, injected packages, Python and index settings. Docker, Desktop, editable",
+ "checkouts and system packages use their own deployment instructions.", "",
+ "Command versions checked by the installer fixtures: uv 0.11.16 and pipx 1.17.12.",
+ "Check your manager's version/help; older versions may not support these flags.",
+ "This guide does not upgrade the manager. uv retains existing version constraints;",
+ "pipx can skip a pinned/locked package successfully. A zero exit code alone does",
+ "not prove the requested version was installed. Do not force/unpin automatically.", "",
+ ]
+ if manifest_sha256 is not None:
+ unix, windows = bootstrap_commands(manifest, manifest_sha256)
+ lines += [
+ "## Automatic platform selection", "",
+ "Run **one** command block on the computer to install or update, after the",
+ "checks above. It downloads this candidate's installer, preserves a recognized",
+ "existing installation owner and selects that Python environment's wheel.",
+ "It verifies the manifest, download size, hash and wheel identity before install.",
+ "Python/dependency compatibility is enforced by the manager; this command does",
+ "not provide a gateway maintenance window, backup or verified restart.", "",
+ "macOS / Linux (Python 3.11+ and curl):", "", "```sh", unix, "```", "",
+ "Windows (Python 3.11+ and PowerShell):", "", "```powershell", windows, "```", "",
+ "Do not bypass a system script-execution policy. Use your approved installation",
+ "route if this script is blocked. These commands target one release, not a",
+ "persistent Preview subscription. The downloaded wheel stays in the private",
+ "nanobot release cache because the original manager may retain its path.", "",
+ "<details>", "<summary>Manual platform and manager commands</summary>", "",
+ ]
+ lines += [
+ "## Select the target platform", "",
+ "Use the architecture of the target Python environment, not the browser. No musl",
+ "or Windows ARM64 wheel is provided. x64 native TUI builds require SSE4.2.",
+ "A platform label is not proof of a native test; consult the release's coverage.", "",
+ ]
+ for target, platform in PLATFORMS.items():
+ artifact = next(item for item in manifest.artifacts
+ if item.filename.endswith(f"-py3-none-{platform}.whl"))
+ shell = "powershell" if target == "win32-x64" else "sh"
+ lines += [f"### {PLATFORM_LABELS[target]}", "",
+ f"Download: [{artifact.filename}]({manifest.artifact_url(artifact)}) ({artifact.size:,} bytes).",
+ f"SHA-256: `{artifact.sha256}`.", ""]
+ owners: tuple[tuple[Owner, str], ...] = (
+ ("uv", "uv tool"), ("pipx", "pipx"), ("pip", "pip in an ordinary venv"),
+ )
+ for owner, title in owners:
+ lines += [f"#### {title}", "", "New installation:", "", f"```{shell}",
+ render_install_command(install_command(manifest, artifact, owner=owner, existing=False),
+ windows=target == "win32-x64"),
+ "```", "", "Existing base-package installation, after stopping and backing up:", "",
+ f"```{shell}",
+ render_install_command(install_command(manifest, artifact, owner=owner, existing=True),
+ windows=target == "win32-x64"),
+ "```", "", "Verify the version from this owner's persistent environment:", "",
+ f"```{shell}", verification_command(owner, windows=target == "win32-x64"), "```", ""]
+ if manifest_sha256 is not None:
+ lines += ["</details>", ""]
+ lines += [
+ "## Verify, restart and recover", "",
+ f"The verification command must report `{manifest.version}`. If it reports another",
+ "version, stop and inspect the manager result and installation identity. Do not",
+ "retry through another manager, run `pipx run`/`uvx`, or clear an intentional pin.", "",
+ "After package verification, restart the original gateway with its original",
+ "supervisor, profile and arguments. Verify that gateway's actual running version",
+ "and readiness, then check that existing sessions can be opened and appended to.",
+ "CLI version output is not proof that an already-running service has updated.", "",
+ "If download or installation fails, retain the error and backup, and do not start",
+ "an unverified environment. Follow the release's owner-specific recovery steps.",
+ "Retry this exact candidate only if it is still eligible. Never replace a backup",
+ "with partially migrated state. A package downgrade is not a data rollback; stop",
+ "all writers and review data compatibility before restoring or downgrading.", "",
+ "GitHub-only previews are not discovered by an ordinary index-only `pip --pre`",
+ "upgrade. A local wheel may remain in a manager receipt or be a one-time override;",
+ "neither means a daily-update subscription has been created.", "",
+ ]
+ return "\n".join(lines)
diff --git a/scripts/verify_installed_release.py b/scripts/verify_installed_release.py
new file mode 100644
index 000000000..081903758
--- /dev/null
+++ b/scripts/verify_installed_release.py
@@ -0,0 +1,335 @@
+"""Probe a wheel installed in a disposable venv, without a frontend toolchain.
+
+Run with that venv's ``python -I`` and exact expected version/commit. This checks
+installed identity, real loopback asset responses and native TUI protocol startup.
+Optionally start a loopback-only gateway with a disposable, unconfigured profile.
+Neither mode uses a model or claims interactive UI, migration or updater coverage.
+With --install-wheel, first exercise the public installer in a disposable home.
+"""
+
+from __future__ import annotations
+
+import argparse
+import asyncio
+import hashlib
+import http.client
+import importlib.metadata
+import json
+import os
+import platform
+import re
+import secrets
+import shutil
+import signal
+import socket
+import subprocess
+import sys
+import tempfile
+import time
+from pathlib import Path, PurePosixPath
+
+
+def host_environment(environment: dict[str, str]) -> dict[str, str]:
+ """Retain OS identity at both isolation boundaries, not user tools/config."""
+ return {key: value for key, value in environment.items()
+ if key.upper() in {"SYSTEMROOT", "WINDIR", "COMSPEC", "PATHEXT",
+ "PROCESSOR_ARCHITECTURE", "PROCESSOR_ARCHITEW6432",
+ "PROCESSOR_IDENTIFIER", "NUMBER_OF_PROCESSORS"}}
+
+
+def webui_assets(directory: Path) -> set[str]:
+ """Check Vite's complete manifest, including lazy chunks, before HTTP probing."""
+ manifest = json.loads((directory / "asset-manifest.json").read_text(encoding="utf-8"))
+ files: set[str] = set()
+ for key, record in manifest.items():
+ for dependency in [*record.get("imports", []), *record.get("dynamicImports", [])]:
+ if dependency not in manifest:
+ raise ValueError(f"Missing WebUI manifest dependency: {key} -> {dependency}")
+ for filename in [record["file"], *record.get("css", []), *record.get("assets", [])]:
+ relative = PurePosixPath(filename)
+ if (relative.is_absolute() or ".." in relative.parts or "\\" in filename
+ or not (directory / filename).resolve().is_relative_to(directory.resolve())):
+ raise ValueError(f"Invalid WebUI asset path: {filename}")
+ if not (directory / filename).is_file() or not (directory / filename).stat().st_size:
+ raise ValueError(f"Missing or empty WebUI asset: {filename}")
+ files.add(filename)
+ html = (directory / "index.html").read_text(encoding="utf-8")
+ entries = set(re.findall(r'(?:src|href)="/(assets/[^"?#]+\.(?:js|css))"', html))
+ if not entries or not entries <= files:
+ raise ValueError("WebUI HTML entrypoints are absent from the compiled manifest")
+ return files
+
+
+def _wait_for_closed_listeners(ports: tuple[int, ...], *, timeout: float = 5) -> None:
+ """Require listener teardown, not just the Windows redirector's exit."""
+ deadline = time.monotonic() + timeout
+ while True:
+ reachable = False
+ for port in ports:
+ with socket.socket() as connection:
+ connection.settimeout(0.2)
+ reachable |= connection.connect_ex(("127.0.0.1", port)) == 0
+ if not reachable:
+ return
+ if time.monotonic() >= deadline:
+ raise ValueError("A probe listener remained reachable after stopping its gateway")
+ time.sleep(0.05)
+
+
+def gateway_probe(version: str, directory: Path) -> dict[str, object]:
+ """Probe the installed CLI, actual readiness and WebUI, then stop only our child."""
+ directory.mkdir(mode=0o700)
+ config = directory / "config.json"
+ token = secrets.token_urlsafe(32)
+ # If another process wins the bind race, the child must fail; its unique
+ # bootstrap secret prevents accepting that other server's identity response.
+ with socket.socket() as health_socket, socket.socket() as web_socket:
+ health_socket.bind(("127.0.0.1", 0))
+ web_socket.bind(("127.0.0.1", 0))
+ health_port, web_port = health_socket.getsockname()[1], web_socket.getsockname()[1]
+ config.write_text(json.dumps({
+ "agents": {"defaults": {"workspace": str(directory / "workspace")}},
+ "gateway": {"host": "127.0.0.1", "port": health_port, "heartbeat": {"enabled": False}},
+ "channels": {"websocket": {"enabled": True, "host": "127.0.0.1", "port": web_port,
+ "tokenIssueSecret": token, "websocketRequiresToken": True}},
+ "tools": {"mcpServers": {}},
+ }), encoding="utf-8")
+ config.chmod(0o600)
+
+ def get(port: int, path: str) -> tuple[int, bytes]:
+ connection = http.client.HTTPConnection("127.0.0.1", port, timeout=2)
+ try:
+ connection.request("GET", path, headers={"X-Nanobot-Auth": token})
+ response = connection.getresponse()
+ return response.status, response.read(2 * 1024 * 1024)
+ finally:
+ connection.close()
+
+ command = [sys.executable, "-I", "-m", "nanobot", "gateway", "--foreground", "--config", str(config)]
+ # A file avoids pipe backpressure; print only a bounded, redacted tail on failure.
+ with (directory / "gateway.log").open("w+b") as log:
+ process = subprocess.Popen(command, cwd=directory, stdout=log, stderr=log)
+ try:
+ try:
+ deadline = time.monotonic() + 45
+ while True:
+ if process.poll() is not None:
+ raise ValueError(f"Installed gateway exited before readiness: {process.returncode}")
+ try:
+ code, body = get(health_port, "/health")
+ if code == 200 and json.loads(body).get("ready") is True:
+ break
+ except (OSError, ValueError, http.client.HTTPException):
+ pass
+ if time.monotonic() >= deadline:
+ raise ValueError("Installed gateway did not become ready within 45 seconds")
+ time.sleep(0.2)
+ code, body = get(web_port, "/webui/terminal")
+ if code != 200 or json.loads(body).get("webui", {}).get("version") != version:
+ raise ValueError("Running gateway did not report the installed candidate version")
+ code, body = get(web_port, "/")
+ if code != 200 or b"<html" not in body.lower() or b"/assets/" not in body:
+ raise ValueError("Running gateway did not serve the built WebUI")
+ finally:
+ if process.poll() is None:
+ # Windows termination is cleanup, not graceful-shutdown proof.
+ if os.name == "nt":
+ # A venv python.exe is a redirector: killing it alone
+ # leaves the actual interpreter and its listeners alive.
+ taskkill = Path(os.environ["SYSTEMROOT"]) / "System32/taskkill.exe"
+ subprocess.run([str(taskkill), "/PID", str(process.pid), "/T", "/F"],
+ check=True, capture_output=True, timeout=10)
+ else:
+ process.send_signal(signal.SIGINT)
+ try:
+ process.wait(timeout=15)
+ except subprocess.TimeoutExpired:
+ process.kill()
+ process.wait(timeout=5)
+ raise ValueError("Installed gateway required forced cleanup") from None
+ if os.name != "nt" and process.returncode != 0:
+ raise ValueError(f"Installed gateway did not exit cleanly: {process.returncode}")
+ # Windows process-tree termination and TCP teardown need not finish
+ # when the venv redirector exits. Wait for the actual postcondition;
+ # a listener that stays alive must still fail acceptance.
+ _wait_for_closed_listeners((health_port, web_port))
+ except Exception:
+ log.flush()
+ log.seek(max(0, os.fstat(log.fileno()).st_size - 8192))
+ print(log.read().decode("utf-8", errors="replace").replace(token, "[redacted]"), file=sys.stderr)
+ raise
+ return {"gateway_ready": True, "gateway_webui_served": True,
+ "gateway_process_stopped": True, "gateway_graceful_shutdown": os.name != "nt"}
+
+
+async def verify_installed_release(
+ version: str, commit: str, data_dir: Path, *, gateway: bool = False,
+) -> dict[str, object]:
+ # Imports deliberately happen only after main has isolated HOME, PATH and cwd.
+ from aiohttp import ClientTimeout, web
+ from aiohttp.test_utils import TestClient, TestServer
+
+ import nanobot
+ from nanobot.build_info import COMMIT
+ from nanobot.cli.tui_launcher import resolve_tui_command
+ from nanobot.webui.build import inspect_webui_bundle
+ from nanobot.webui.local_client_assets import LocalClientAssets
+
+ prefix = Path(sys.prefix).resolve()
+ package = Path(nanobot.__file__).resolve()
+ distribution = importlib.metadata.distribution("nanobot-ai")
+ if (not package.is_relative_to(prefix)
+ or package != Path(str(distribution.locate_file("nanobot/__init__.py"))).resolve()):
+ raise ValueError("Probe imported a checkout or another environment, not the installed wheel")
+ if nanobot.__version__ != version or distribution.version != version or COMMIT != commit:
+ raise ValueError("Installed package version/commit differs from the expected candidate")
+ if any(shutil.which(tool) for tool in ("bun", "node", "npm", "git")):
+ raise ValueError("Frontend development tools must not be on the probe PATH")
+ if os.environ.get("NANOBOT_TUI_NO_DOWNLOAD") != "1":
+ raise ValueError("The installed TUI probe must disable fallback downloads")
+
+ bundle = inspect_webui_bundle()
+ if not bundle.dist_available or bundle.needs_build or bundle.source_available:
+ raise ValueError("Installed wheel must contain a usable WebUI without a source build")
+ assets = LocalClientAssets()
+ if not assets.directory.is_relative_to(package.parent):
+ raise ValueError("WebUI assets do not belong to the installed package")
+ files = webui_assets(assets.directory)
+ app = web.Application()
+
+ async def serve(request: web.Request) -> web.FileResponse:
+ return assets.response(request)
+
+ app.router.add_get("/{path:.*}", serve)
+ async with asyncio.timeout(40), TestClient(
+ TestServer(app, host="127.0.0.1"), timeout=ClientTimeout(total=5),
+ headers={"Accept-Encoding": "identity"},
+ ) as client:
+ for filename in ["index.html", "asset-manifest.json", *sorted(files)]:
+ response = await client.get("/" if filename == "index.html" else f"/{filename}")
+ if response.status != 200 or response.headers.get("X-Nanobot-UI") != "local":
+ raise ValueError(f"Installed WebUI asset was not served: {filename}")
+ if await response.read() != (assets.directory / filename).read_bytes():
+ raise ValueError(f"Installed WebUI response differs from its file: {filename}")
+ if filename.endswith((".js", ".css")) and response.content_type == "text/html":
+ raise ValueError(f"WebUI asset unexpectedly served the HTML shell: {filename}")
+
+ command = resolve_tui_command(data_dir=data_dir)
+ executable = Path(command[0]).resolve()
+ if len(command) != 1 or not executable.is_relative_to(package.parent / "tui" / "bin"):
+ raise ValueError("TUI command must use the installed native bundle, not source or cache")
+ if not os.access(executable, os.X_OK):
+ raise ValueError("Installed TUI is not executable")
+ native = subprocess.run(
+ [str(executable), "--desktop-protocol"], check=True, capture_output=True,
+ text=True, encoding="utf-8", timeout=15,
+ )
+ if native.stdout.strip() != "1":
+ raise ValueError("Installed TUI returned an unsupported desktop protocol")
+ runtime = await asyncio.to_thread(gateway_probe, version, data_dir.parent / "gateway") if gateway else {}
+ return {
+ "version": version, "candidate_commit": commit, "package": str(package),
+ "platform": platform.system(), "machine": platform.machine(),
+ "python": platform.python_version(), "webui_assets_served": len(files),
+ "frontend_build_tools_on_path": False, "tui_download_enabled": False,
+ "native_tui": str(executable), "native_protocol_probe": native.stdout.strip(),
+ "gateway_started": gateway, "interactive_ui_e2e": False, **runtime,
+ }
+
+
+def install_and_probe(wheel: Path, *, version: str, commit: str, gateway: bool, report: Path | None) -> None:
+ """Exercise the public fresh installer with a real native wheel, no toolchain."""
+ wheel = wheel.resolve(strict=True)
+ scripts = Path(__file__).resolve().parent
+ digest = hashlib.sha256(wheel.read_bytes()).hexdigest()
+ with tempfile.TemporaryDirectory(prefix="nanobot-release-install-") as temporary:
+ root = Path(temporary).resolve()
+ # platform.machine() on Windows reads these OS-provided variables.
+ # Removing them creates an artificial unknown-architecture host, not a
+ # clean installation. Keep host identity, never user package/tool paths.
+ system = host_environment(dict(os.environ))
+ system.update(HOME=str(root), USERPROFILE=str(root), PYTHON=sys._base_executable,
+ NANOBOT_VENV=str(root / "managed"), NANOBOT_BIN_DIR=str(root / "bin"),
+ NANOBOT_SKIP_WIZARD="1", PIP_CONFIG_FILE=os.devnull, PIP_ONLY_BINARY=":all:",
+ PIP_DISABLE_PIP_VERSION_CHECK="1", PIP_NO_INPUT="1", PYTHONUTF8="1",
+ XDG_CONFIG_HOME=str(root / "config"), XDG_CACHE_HOME=str(root / "cache"),
+ XDG_DATA_HOME=str(root / "data"), APPDATA=str(root / "config"),
+ LOCALAPPDATA=str(root / "data"), TMPDIR=str(root), TMP=str(root), TEMP=str(root))
+ if os.name == "nt":
+ system["PATH"] = str(Path(system["SYSTEMROOT"]) / "System32")
+ shell = Path(system["SYSTEMROOT"]) / "System32/WindowsPowerShell/v1.0/powershell.exe"
+ command = [str(shell), "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File",
+ str(scripts / "install.ps1"), "-Wheel", str(wheel), "-Sha256", digest]
+ python = root / "managed/Scripts/python.exe"
+ else:
+ system["PATH"] = "/usr/bin:/bin"
+ command = ["/bin/sh", str(scripts / "install.sh"), "--wheel", str(wheel), "--sha256", digest]
+ python = root / "managed/bin/python"
+ subprocess.run(command, check=True, cwd=root, env=system, timeout=600)
+ receipt = json.loads((root / "managed/nanobot-install.json").read_bytes())
+ if receipt != {"schema_version": 1, "owner": "nanobot-installer",
+ "environment": str((root / "managed").resolve()), "extras": []}:
+ raise ValueError("The public installer did not establish its managed update identity")
+ command = [str(python), "-I", str(Path(__file__).resolve()), "--version", version, "--commit", commit]
+ if gateway:
+ command.append("--gateway")
+ if report:
+ command.extend(["--report", str(report)])
+ subprocess.run(command, check=True, cwd=root, env=system, timeout=120)
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--version", required=True)
+ parser.add_argument("--commit", required=True)
+ parser.add_argument("--gateway", action="store_true",
+ help="Also start a disposable loopback gateway; no model calls or user config")
+ parser.add_argument("--report", type=Path)
+ parser.add_argument("--install-wheel", type=Path,
+ help="First run the public installer against this exact wheel in a disposable home")
+ args = parser.parse_args()
+ if args.install_wheel is not None:
+ if not sys.flags.isolated:
+ parser.error("Run the installer probe with python -I")
+ if args.report is not None and args.report.exists():
+ parser.error("Use a new report path; prior evidence must not be overwritten")
+ install_and_probe(args.install_wheel, version=args.version, commit=args.commit,
+ gateway=args.gateway, report=args.report.resolve() if args.report else None)
+ return
+ if not sys.flags.isolated or sys.prefix == sys.base_prefix:
+ parser.error("Run the disposable installation's python -I, not the build/source interpreter")
+ report = args.report.resolve() if args.report else None
+ if report is not None and report.exists():
+ parser.error("Use a new report path; prior evidence must not be overwritten")
+ original_env, original_cwd = dict(os.environ), Path.cwd()
+ with tempfile.TemporaryDirectory(prefix="nanobot-installed-probe-") as temporary:
+ root = Path(temporary).resolve()
+ empty_path = root / "empty-path"
+ empty_path.mkdir()
+ env = host_environment(original_env)
+ env.update({
+ "PATH": str(empty_path), "HOME": str(root), "USERPROFILE": str(root),
+ "XDG_CONFIG_HOME": str(root / "config"), "XDG_CACHE_HOME": str(root / "cache"),
+ "XDG_DATA_HOME": str(root / "data"), "TMPDIR": str(root), "TMP": str(root),
+ "TEMP": str(root), "NANOBOT_TUI_NO_DOWNLOAD": "1", "NO_COLOR": "1",
+ })
+ os.environ.clear()
+ os.environ.update(env)
+ os.chdir(root)
+ try:
+ result = asyncio.run(verify_installed_release(
+ args.version, args.commit, root / "tui", gateway=args.gateway,
+ ))
+ finally:
+ os.chdir(original_cwd)
+ os.environ.clear()
+ os.environ.update(original_env)
+ payload = json.dumps(result, indent=2) + "\n"
+ if report is not None:
+ with report.open("x", encoding="utf-8") as stream:
+ stream.write(payload)
+ print(payload, end="")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/verify_packaged_update.py b/scripts/verify_packaged_update.py
new file mode 100644
index 000000000..f9e49837a
--- /dev/null
+++ b/scripts/verify_packaged_update.py
@@ -0,0 +1,772 @@
+"""Run native packaged upgrade/recovery journeys in a disposable account.
+
+The healthy target is the exact supplied wheel, not a patched application. The
+default baseline is explicitly a version-only fixture with a local feed transport
+and bounded fault injection. It does not stand for an older published release.
+Use --baseline-wheel to exercise an actual earlier updater-enabled package too.
+No public feed, user installation, model, credentials or OS service is used.
+"""
+
+from __future__ import annotations
+
+import argparse
+import asyncio
+import base64
+import csv
+import hashlib
+import importlib.util
+import io
+import json
+import os
+import platform
+import re
+import secrets
+import socket
+import sqlite3
+import subprocess
+import sys
+import time
+from contextlib import closing
+from pathlib import Path
+from unittest.mock import patch
+from urllib.parse import quote
+from zipfile import ZIP_DEFLATED, ZipFile
+
+SCENARIOS = ("upgrade", "upgrade-again", "skipped-preview", "import-failure", "restart-failure",
+ "backup-failure", "worker-exit", "metadata-loss", "restore-interruption")
+
+
+def digest(path: Path) -> str:
+ with path.open("rb") as stream:
+ return hashlib.file_digest(stream, "sha256").hexdigest()
+
+
+def read(path: Path):
+ return json.loads(path.read_text(encoding="utf-8"))
+
+
+def write(path: Path, value) -> None:
+ path.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
+
+
+def replace_once(source: bytes, old: bytes, new: bytes) -> bytes:
+ if source.count(old) != 1:
+ raise ValueError("The fault-injection seam changed; review the acceptance fixture")
+ return source.replace(old, new, 1)
+
+
+def fixture_wheel(source: Path, output: Path, version: str, *, feed: Path | None = None,
+ scenario: str = "upgrade") -> Path:
+ """Private instrumentation only; never overwrite or relabel the supplied target."""
+ from packaging.utils import parse_wheel_filename
+
+ _, previous, _, _ = parse_wheel_filename(source.name)
+ prefix, replacement = f"nanobot_ai-{previous}.dist-info/", f"nanobot_ai-{version}.dist-info/"
+ with ZipFile(source) as archive:
+ entries = [(item, archive.read(item)) for item in archive.infolist() if not item.filename.endswith("/RECORD")]
+ files = {item.filename.replace(prefix, replacement): data for item, data in entries}
+ metadata = replacement + "METADATA"
+ files[metadata] = replace_once(files[metadata], f"Version: {previous}\n".encode(), f"Version: {version}\n".encode())
+ if feed is not None:
+ # This existing injectable transport runs in both planner and preflight
+ # processes. It cannot reach external hosts. These private packages are
+ # not approved public releases: signature admission is exercised by the
+ # separate trust tests, not this installation/recovery fixture.
+ files["nanobot/_acceptance_feed.py"] = f'''import json
+from pathlib import Path
+import httpx
+def transport():
+ def respond(request):
+ record = json.loads(Path({str(feed)!r}).read_text(encoding="utf-8"))
+ if request.method != "GET" or str(request.url) not in record:
+ raise ValueError("Unexpected acceptance feed request: " + str(request.url))
+ item = record[str(request.url)]
+ return httpx.Response(200, content=Path(item["file"]).read_bytes() if "file" in item else json.dumps(item["json"]).encode())
+ return httpx.MockTransport(respond)
+'''.encode()
+ files["nanobot/release_feed.py"] = replace_once(
+ files["nanobot/release_feed.py"], b"transport=transport or PinnedDNSAsyncTransport(),",
+ b'transport=transport or __import__("nanobot._acceptance_feed", fromlist=["transport"]).transport(),')
+ if b"await self._authorize(target)" in files["nanobot/release_feed.py"]:
+ files["nanobot/release_feed.py"] = replace_once(
+ files["nanobot/release_feed.py"], b"await self._authorize(target)",
+ b"pass # Private unsigned acceptance fixture, never a distributable wheel.")
+ # Windows source archives can contain CRLF. Normalize only the private
+ # instrumentation copy; the final target's bytes remain untouched.
+ worker = files["nanobot/update_worker.py"].replace(b"\r\n", b"\n")
+ # Inject into the first job in this disposable account. The recovered
+ # updater must subsequently install a release without re-injecting it.
+ fault = f"__import__('pathlib').Path({str(feed.parent / 'injected-fault')!r})"
+ if scenario == "worker-exit":
+ needle = b' env = {key: value for key, value in os.environ.items() if not key.upper().startswith("PIP_")}\n'
+ worker = replace_once(worker, needle, f''' if not {fault}.exists():
+ {fault}.touch()
+ (directory / 'fault-fired').write_text('worker exit')
+ os._exit(91)
+'''.encode() + needle)
+ elif scenario == "metadata-loss":
+ needle = b"\n _verify(spec, directory)\n"
+ worker = replace_once(worker, needle, f'''
+ if not {fault}.exists():
+ {fault}.touch()
+ (directory / 'fault-fired').write_text('metadata loss')
+ next(Path(spec.baseline.environment).rglob('nanobot_ai-' + spec.version + '.dist-info/METADATA')).unlink()
+ os._exit(92)
+'''.encode() + needle)
+ elif scenario == "backup-failure":
+ needle = b" ensure_backup(directory, spec.backup_sources,\n"
+ worker = replace_once(worker, needle, f''' if not {fault}.exists():
+ {fault}.write_text(str(directory))
+ if {fault}.read_text() == str(directory):
+ raise OSError('Injected backup write failure')
+'''.encode() + needle)
+ files["nanobot/update_worker.py"] = worker
+ if scenario == "restore-interruption":
+ needle = b" os.rename(original, environment)\n"
+ files["nanobot/update_fallback.py"] = replace_once(files["nanobot/update_fallback.py"].replace(b"\r\n", b"\n"), needle, b''' if not (directory / 'restore-fault-fired').exists():
+ (directory / 'restore-fault-fired').write_text('interrupted between renames')
+ raise OSError('Injected rename interruption')
+''' + needle)
+ elif scenario in {"import-failure", "restore-interruption"}:
+ files["nanobot/__init__.py"] = b"raise RuntimeError('Injected candidate import failure')\n"
+ elif scenario == "restart-failure":
+ files["nanobot/update_restart.py"] = b"raise RuntimeError('Injected candidate startup failure')\n"
+ record = replacement + "RECORD"
+ rows = io.StringIO()
+ writer = csv.writer(rows, lineterminator="\n")
+ for name, content in files.items():
+ writer.writerow((name, "sha256=" + base64.urlsafe_b64encode(hashlib.sha256(content).digest()).rstrip(b"=").decode(), len(content)))
+ writer.writerow((record, "", ""))
+ files[record] = rows.getvalue().encode()
+ output.mkdir(parents=True, exist_ok=True)
+ result = output / source.name.replace(f"-{previous}-", f"-{version}-", 1)
+ info = {item.filename.replace(prefix, replacement): item for item, _ in entries}
+ with ZipFile(result, "x", compression=ZIP_DEFLATED) as archive:
+ for name, content in files.items():
+ if name in info:
+ item = info[name]
+ item.filename = name # Retain native executable permissions.
+ archive.writestr(item, content)
+ else:
+ archive.writestr(name, content)
+ return result
+
+
+def feed_records(wheel: Path, commit: str, *, generation: int = 1) -> dict:
+ from packaging.utils import parse_wheel_filename
+ from packaging.version import Version
+
+ from nanobot.release_feed import CATALOGUE_URL
+ from nanobot.releases import (
+ ReleaseArtifact,
+ ReleaseCatalogue,
+ ReleaseManifest,
+ ReleasePointer,
+ release_filenames,
+ )
+
+ version = str(parse_wheel_filename(wheel.name)[1])
+ artifacts = [ReleaseArtifact(filename=name, size=wheel.stat().st_size if name == wheel.name else 1,
+ sha256=digest(wheel) if name == wheel.name else "a" * 64)
+ for name in sorted(release_filenames(version))]
+ if not Version(version).is_prerelease:
+ base = "https://files.pythonhosted.org/packages/"
+ metadata = {"info": {"name": "nanobot-ai", "version": version, "requires_python": ">=3.11"},
+ "urls": [{"filename": item.filename, "size": item.size, "url": base + item.filename,
+ "digests": {"sha256": item.sha256}, "yanked": False}
+ for item in artifacts if item.filename.endswith((".whl", ".tar.gz"))]}
+ return {base + wheel.name: {"file": str(wheel)},
+ "https://pypi.org/pypi/nanobot-ai/json": {"json": metadata},
+ f"https://pypi.org/pypi/nanobot-ai/{version}/json": {"json": metadata}}
+ manifest = ReleaseManifest(version=version, source_commit=commit, candidate_commit=commit,
+ requires_python=">=3.11", artifacts=artifacts)
+ data = manifest.model_dump(mode="json")
+ pointer = ReleasePointer(version=version, candidate_commit=commit,
+ manifest_sha256=hashlib.sha256(json.dumps(data).encode()).hexdigest())
+ catalogue = ReleaseCatalogue(generation=generation, preview=pointer)
+ base = f"https://github.com/HKUDS/nanobot/releases/download/v{version}/"
+ return {CATALOGUE_URL: {"json": catalogue.model_dump(mode="json")},
+ base + "release-manifest.json": {"json": data}, base + wheel.name: {"file": str(wheel)}}
+
+
+def free_port() -> int:
+ with socket.socket() as listener:
+ listener.bind(("127.0.0.1", 0))
+ return listener.getsockname()[1]
+
+
+def gateway(root: Path, *arguments: str) -> None:
+ subprocess.run([sys.executable, "-I", "-m", "nanobot", "gateway", *arguments,
+ "--config", str(root / "account/.nanobot/config.json")], check=True, timeout=60)
+
+
+def _dock_supported(root: Path) -> bool:
+ return bool(read(root / "case.json").get("dock")
+ and importlib.util.find_spec("nanobot.cli.dock") is not None)
+
+
+def _desktop_webui(root: Path) -> None:
+ # The real managed receipt must select automatic detachment, not a test flag.
+ subprocess.run([sys.executable, "-I", "-m", "nanobot", "webui", "--yes", "--no-open",
+ "--config", str(root / "account/.nanobot/config.json")], check=True, timeout=60)
+
+
+def _dock_socket(root: Path) -> Path:
+ from nanobot.cli.dock import _directory
+ from nanobot.cli.webui_support import _webui_browser_url
+ from nanobot.config.loader import load_config
+ from nanobot.gateway.runtime import GatewayInstance
+
+ config = root / "account/.nanobot/config.json"
+ instance = GatewayInstance.resolve(config_path=config)
+ return _directory(instance.paths.state_path, _webui_browser_url(load_config(config))) / "s"
+
+
+def _wait_dock(address: Path, *, present: bool) -> None:
+ deadline = time.monotonic() + 8
+ while time.monotonic() < deadline:
+ processes = subprocess.run(["/usr/bin/pgrep", "-f", str(address)], capture_output=True,
+ text=True, check=False)
+ count = len(processes.stdout.split())
+ if count == (1 if present else 0):
+ return
+ time.sleep(0.1)
+ raise AssertionError(f"Expected {'one live' if present else 'no'} Dock helper")
+
+
+def request(root: Path, path: str):
+ import httpx
+
+ config = read(root / "account/.nanobot/config.json")
+ web = config["channels"]["websocket"]
+ base = f'http://127.0.0.1:{web["port"]}'
+ with httpx.Client(timeout=10, trust_env=False) as client:
+ bootstrap = client.get(base + "/webui/bootstrap", headers={"X-Nanobot-Auth": web["tokenIssueSecret"]})
+ bootstrap.raise_for_status()
+ if path == "/webui/bootstrap":
+ return bootstrap.json()
+ headers = ({"X-Nanobot-Auth": web["tokenIssueSecret"]} if path == "/webui/terminal"
+ else {"Authorization": "Bearer " + bootstrap.json()["api_token"]})
+ response = client.get(base + path, headers=headers)
+ response.raise_for_status()
+ return response.json()
+
+
+def history(root: Path, key: str):
+ rows = request(root, "/api/sessions")["sessions"]
+ assert key in {row["key"] for row in rows}, rows
+ response = request(root, "/api/sessions/" + quote(key, safe="") + "/webui-thread")
+ # Revision/ETag and gateway identity must change after restart. Compare the
+ # persisted transcript, not that intentionally volatile response envelope.
+ return {name: response[name] for name in ("events", "completed_turn_ids")}
+
+
+def assert_history_preserved(before: dict, after: dict) -> None:
+ """Allow only known additive defaults in the older transcript projection."""
+ assert after["completed_turn_ids"] == before["completed_turn_ids"]
+ assert len(after["events"]) == len(before["events"])
+ for previous, current in zip(before["events"], after["events"], strict=True):
+ current = dict(current)
+ # SQLite represents an unknown legacy timestamp as zero. New projection
+ # also exposes the already-persisted inactive goal on a completed turn.
+ # Do not ignore these fields when the old API supplied an actual value.
+ if "created_at_ms" not in previous and current.get("created_at_ms") == 0:
+ del current["created_at_ms"]
+ if (previous["event"] == "turn_end" and "goal_state" not in previous
+ and current.get("goal_state") == {"active": False}):
+ del current["goal_state"]
+ assert current == previous, (current, previous)
+
+
+def canonical_records(path: Path, tables: tuple[str, ...] = ("sessions", "messages", "checkpoints", "pending_inputs")) -> dict:
+ """Compare logical records, not SQLite's transient WAL/checkpoint layout."""
+ with closing(sqlite3.connect(path.as_uri() + "?mode=ro", uri=True)) as db:
+ assert db.execute("PRAGMA integrity_check").fetchone() == ("ok",)
+ return {table: [list(row) for row in db.execute(f"SELECT * FROM {table} ORDER BY 1, 2")]
+ for table in tables}
+
+
+def assert_canonical_preserved(before: dict, after: dict) -> None:
+ """Schema v2 may add a display-only owner, never model context or lost rows."""
+ key = "websocket:display-only"
+ existing = {row[0] for row in before["sessions"]}
+ added = [row for row in after["sessions"] if row[0] == key and key not in existing]
+ for row in added:
+ # A newly imported display transcript owns an empty Session. Only its
+ # identity/timestamps and the public handle allocated by /api/sessions
+ # are new; it must not manufacture agent context or other metadata.
+ metadata = json.loads(row[3])
+ if metadata:
+ assert set(metadata) == {"session_handle"}, row
+ handle = metadata["session_handle"]
+ assert isinstance(handle, str) and re.fullmatch("[a-z]{4,16}", handle), row
+ revision = 2 if metadata else 1
+ assert row[4:7] == [None, 0, revision] and row[8:] == ["", "", None], row
+ comparable = {**after, "sessions": [row for row in after["sessions"] if row not in added]}
+ assert comparable == before, (comparable, before)
+
+
+def canonical_context(root: Path) -> dict:
+ context = request(root, "/api/sessions/websocket%3Acanonical-only/context")
+ # Tokenizer availability can alter estimates; stored message content is
+ # checked separately against every canonical SQLite record.
+ return {key: value for key, value in context.items() if not key.startswith("estimated_")}
+
+
+async def chat(root: Path, chat_id: str | None = None) -> str:
+ import websockets
+
+ bootstrap = request(root, "/webui/bootstrap")
+ async def receive(ws, event):
+ async with asyncio.timeout(30):
+ while True:
+ value = json.loads(await ws.recv())
+ if value.get("event") == event:
+ return value
+ async with websockets.connect(bootstrap["ws_url"] + "?token=" + bootstrap["token"] + "&client_id=package-acceptance") as ws:
+ await receive(ws, "ready")
+ await ws.send(json.dumps({"type": "attach", "chat_id": chat_id} if chat_id else {"type": "new_chat"}))
+ attached = await receive(ws, "attached")
+ chat_id = attached["chat_id"]
+ await ws.send(json.dumps({"type": "message", "chat_id": chat_id, "content": "/model", "webui": True,
+ "turn_id": "acceptance-" + secrets.token_hex(8)}))
+ answer = await receive(ws, "message")
+ assert "acceptance-no-model" in answer["text"], answer
+ await receive(ws, "turn_end")
+ return chat_id
+
+
+def ready(root: Path, version: str):
+ from nanobot.gateway.runtime import GatewayRuntime
+ from nanobot.update_profiles import inspect_profiles
+
+ deadline = time.monotonic() + 60
+ while time.monotonic() < deadline:
+ profiles = inspect_profiles(str(Path(sys.prefix).resolve()))
+ if len(profiles) == 1:
+ receipt = profiles[0].receipt
+ if GatewayRuntime().verify_ready(receipt.health_identity, maintenance=False):
+ assert receipt.version == version, (receipt.version, version)
+ assert request(root, "/webui/terminal")["webui"]["version"] == version
+ return receipt
+ time.sleep(0.2)
+ raise RuntimeError("The actual installed gateway did not become ready")
+
+
+def seed(root: Path) -> None:
+ import nanobot
+ from nanobot.config.loader import load_config, save_config, set_config_path
+ from nanobot.config.paths import get_webui_dir
+
+ assert Path(nanobot.__file__).resolve().is_relative_to(Path(sys.prefix).resolve())
+ config_path = root / "account/.nanobot/config.json"
+ config_path.parent.mkdir(parents=True, exist_ok=True)
+ set_config_path(config_path)
+ config = load_config(config_path)
+ config.agents.defaults.workspace = str(root / "workspace")
+ config.agents.defaults.provider = "custom"
+ config.agents.defaults.model = "acceptance-no-model"
+ config.agents.defaults.dream.enabled = False
+ config.agents.defaults.session_ttl_minutes = 0
+ config.providers.custom.api_key = "fixture-not-a-secret"
+ config.providers.custom.api_base = "http://127.0.0.1:1/v1"
+ config.gateway.host, config.gateway.port = "127.0.0.1", free_port()
+ config.gateway.heartbeat.enabled = False
+ config.channels.websocket = {"enabled": True, "host": "127.0.0.1", "port": free_port(),
+ "tokenIssueSecret": secrets.token_urlsafe(32), "websocketRequiresToken": True}
+ save_config(config, config_path)
+ # Real historical canonical files are imported by the installed SQLite owner,
+ # not generated by a new-store round trip. Existing source bytes stay readable.
+ if importlib.util.find_spec("nanobot.session.location") is not None:
+ from nanobot.session.location import SessionLocation
+ location = SessionLocation(root / "workspace")
+ else:
+ # The retained pre-SQLite package owns the same namespace here. This is
+ # acceptance-fixture compatibility, not a fallback in the application.
+ from nanobot.session.manager import JsonlSessionStore
+ location = JsonlSessionStore(root / "workspace")
+ sessions = location.sessions_dir
+ key = "websocket:legacy-acceptance"
+ legacy = sessions / (location.storage_key(key) + ".jsonl")
+ legacy.write_text(json.dumps({"_type": "metadata", "key": key, "metadata": {"title": "升级前的聊天"},
+ "created_at": "2026-01-01T00:00:00", "updated_at": "2026-01-01T00:00:00"}) + "\n" +
+ json.dumps({"role": "user", "content": "配置和聊天不能丢失"}, ensure_ascii=False) + "\n", encoding="utf-8")
+ canonical_only = sessions / (location.storage_key("websocket:canonical-only") + ".jsonl")
+ canonical_only.write_bytes(legacy.read_bytes().replace(key.encode(), b"websocket:canonical-only"))
+ webui_dir = get_webui_dir()
+ webui_dir.mkdir(parents=True, exist_ok=True)
+ for chat_id in ("legacy-acceptance", "display-only"):
+ events = [{"event": "user", "chat_id": chat_id, "text": "配置和聊天不能丢失"},
+ {"event": "message", "chat_id": chat_id, "text": "独立验收数据"},
+ {"event": "turn_end", "chat_id": chat_id}]
+ (webui_dir / f"websocket_{chat_id}.jsonl").write_text(
+ "".join(json.dumps(event, ensure_ascii=False) + "\n" for event in events), encoding="utf-8")
+ if _dock_supported(root):
+ _desktop_webui(root)
+ _wait_dock(_dock_socket(root), present=True)
+ else:
+ gateway(root, "--background")
+
+
+def snapshot(root: Path) -> None:
+ from nanobot.config.loader import set_config_path
+ from nanobot.config.paths import get_webui_dir
+
+ case = read(root / "case.json")
+ config_path = root / "account/.nanobot/config.json"
+ set_config_path(config_path)
+ delivery = config_path.parent / "delivery/outbox.sqlite3"
+ if not delivery.exists() and importlib.util.find_spec("nanobot.channels.outbox") is not None:
+ from nanobot.bus.delivery import DeliveryRequest
+ from nanobot.bus.events import OutboundMessage
+ from nanobot.channels.outbox import DeliveryOutbox
+
+ # Keep a real durable result pending through the private journey without
+ # attempting an external send. Older retained code has no outbox owner.
+ with patch("nanobot.channels.outbox.time.time", return_value=time.time() + 3600):
+ DeliveryOutbox(delivery).record(OutboundMessage(
+ "whatsapp", "acceptance-offline", "Retain this scheduled result",
+ delivery=DeliveryRequest("acceptance-run", "websocket:legacy-acceptance", None),
+ ))
+ if importlib.util.find_spec("nanobot.session.location") is not None:
+ from nanobot.session.location import SessionLocation
+ location = SessionLocation(root / "workspace")
+ else:
+ from nanobot.session.manager import JsonlSessionStore
+ location = JsonlSessionStore(root / "workspace")
+ sessions, webui_dir = location.sessions_dir, get_webui_dir()
+ key = "websocket:legacy-acceptance"
+ legacy = sessions / (location.storage_key(key) + ".jsonl")
+ canonical_only = sessions / (location.storage_key("websocket:canonical-only") + ".jsonl")
+ receipt = ready(root, case["baseline_version"])
+ chat_id = (read(root / "before.json")["chat_id"] if (root / "before.json").exists()
+ else asyncio.run(chat(root)))
+ before = history(root, "websocket:" + chat_id)
+ legacy_before = history(root, key)
+ display_before = history(root, "websocket:display-only")
+ context_before = canonical_context(root)
+ assert context_before["total_messages"] == 1
+ assert "配置和聊天不能丢失" in json.dumps(legacy_before, ensure_ascii=False)
+ # Immutable files plus public logical records: SQLite/WAL checkpoint bytes
+ # may legitimately change across a clean shutdown without changing a record.
+ preserved = {str(path): digest(path) for path in (legacy, canonical_only,
+ webui_dir / "websocket_legacy-acceptance.jsonl", webui_dir / "websocket_display-only.jsonl")}
+ preserved[str(config_path)] = digest(config_path)
+ write(root / "before.json", {"chat_id": chat_id, "history": before, "legacy": legacy_before,
+ "display_only": display_before, "canonical_only": context_before,
+ "files": preserved, "run_id": receipt.run_id,
+ "database": str(sessions / "sessions.sqlite3"),
+ "delivery": (canonical_records(delivery, ("deliveries",)) if delivery.exists() else None),
+ "canonical": (canonical_records(sessions / "sessions.sqlite3")
+ if (sessions / "sessions.sqlite3").exists() else None)})
+
+
+def prepare(root: Path) -> None:
+ from packaging.version import Version
+
+ from nanobot.installation_lock import installation_state_dir
+ from nanobot.release_feed import ReleaseFeed
+ from nanobot.update_channel import UpdateChannelRequest, read_update_channel
+ from nanobot.update_jobs import prepare_job, start_handoff
+ from nanobot.update_plan import preview_release_update
+ from nanobot.update_service import UpdateJobService
+
+ if not (root / "before.json").exists():
+ seed(root)
+ snapshot(root)
+ case = read(root / "case.json")
+
+ async def plan_update():
+ state = installation_state_dir()
+ channel = "preview" if Version(case["target_version"]).is_prerelease else "stable"
+ UpdateJobService().change_channel(UpdateChannelRequest(channel=channel, revision=read_update_channel().revision))
+ plan = await preview_release_update(restart_running=True)
+ assert plan.stop_profiles and plan.restart_profiles
+ async with ReleaseFeed(state / "feed") as feed:
+ return await prepare_job(plan, feed)
+ directory = asyncio.run(plan_update())
+ # Capture the production launch, then let the outer, stdlib-only controller
+ # execute it after this process exits. Otherwise Windows DLL locks from the
+ # *test controller* prevent restoring the live venv directory.
+ with patch("nanobot.update_jobs.subprocess.Popen") as spawn:
+ start_handoff(directory, once=True)
+ command = spawn.call_args.args[0]
+ write(root / "launch.json", {"command": command, "directory": str(directory)})
+
+
+def verify(root: Path) -> dict:
+ import nanobot
+ from nanobot.build_info import COMMIT
+ from nanobot.config.loader import set_config_path
+ from nanobot.update_worker import JobStatus, Phase
+
+ set_config_path(root / "account/.nanobot/config.json")
+ case, before, launch = read(root / "case.json"), read(root / "before.json"), read(root / "launch.json")
+ directory = Path(launch["directory"])
+ restored = case["scenario"] not in {"upgrade", "upgrade-again", "skipped-preview", "worker-exit"}
+ status = JobStatus.read(directory)
+ assert status.phase == (Phase.RESTORED if restored else Phase.SUCCEEDED), status
+ expected = case["baseline_version"] if restored else case["target_version"]
+ receipt = ready(root, expected)
+ assert receipt.run_id != before["run_id"], "Update did not restart the gateway"
+ assert nanobot.__version__ == expected
+ if not restored:
+ assert COMMIT == case["commit"]
+ assert digest(Path(case["target_wheel"])) == case["target_sha256"]
+ sqlite_expected = verify_data(root, expected)
+ if case["scenario"] in {"worker-exit", "metadata-loss"}:
+ assert (directory / "fault-fired").exists()
+ if case["scenario"] in {"worker-exit", "metadata-loss", "backup-failure"}:
+ assert (root / "injected-fault").exists()
+ if case["scenario"] == "restore-interruption":
+ assert (directory / "restore-fault-fired").exists()
+ return {**case, "phase": status.phase.value, "running_version": receipt.version,
+ "restarted": True, "config_and_legacy_bytes_preserved": True,
+ "authenticated_history_preserved": True, "sqlite_records_preserved": True if sqlite_expected else None,
+ "scheduled_delivery_preserved": True if before.get("delivery") is not None else None,
+ "continued_write_and_second_start": True,
+ "dock_socket": str(_dock_socket(root)) if _dock_supported(root) else None,
+ "dock_restart_verified": True if _dock_supported(root) else None}
+
+
+def verify_data(root: Path, expected: str) -> bool:
+ """Public reads and subsequent writes, shared by inline and owner-driven updates."""
+ from nanobot.config.loader import set_config_path
+
+ set_config_path(root / "account/.nanobot/config.json")
+ before = read(root / "before.json")
+ receipt = ready(root, expected)
+ assert receipt.run_id != before["run_id"], "Update did not restart the gateway"
+ if _dock_supported(root):
+ from nanobot.gateway.runtime import GatewayInstance
+
+ instance = GatewayInstance.resolve(config_path=root / "account/.nanobot/config.json")
+ # A historical package without this feature cannot record desktop intent.
+ # After that first upgrade, exercise the real new launcher, then restart.
+ if not instance.paths.state_path.with_suffix(".dock").exists():
+ _desktop_webui(root)
+ _wait_dock(_dock_socket(root), present=True)
+ assert {name: digest(Path(name)) for name in before["files"]} == before["files"]
+ key = "websocket:" + before["chat_id"]
+ assert_history_preserved(before["history"], history(root, key))
+ assert_history_preserved(before["legacy"], history(root, "websocket:legacy-acceptance"))
+ assert_history_preserved(before["display_only"], history(root, "websocket:display-only"))
+ assert canonical_context(root) == before["canonical_only"], (canonical_context(root), before["canonical_only"])
+ database = Path(before["database"])
+ sqlite_expected = importlib.util.find_spec("nanobot.session.location") is not None
+ canonical = canonical_records(database) if sqlite_expected else None
+ if before["canonical"] is not None:
+ assert_canonical_preserved(before["canonical"], canonical)
+ delivery = root / "account/.nanobot/delivery/outbox.sqlite3"
+ if before.get("delivery") is not None:
+ assert canonical_records(delivery, ("deliveries",)) == before["delivery"]
+ if canonical is not None:
+ # Display transcripts are not canonical agent context. Check the actual
+ # imported message bodies too when the baseline predates SQLite.
+ assert not any(row[0] == "websocket:display-only" for row in canonical["messages"])
+ for session_key in ("websocket:legacy-acceptance", "websocket:canonical-only"):
+ messages = [json.loads(row[2]) for row in canonical["messages"] if row[0] == session_key]
+ assert [(message["role"], message["content"]) for message in messages] == [
+ ("user", "配置和聊天不能丢失")]
+ asyncio.run(chat(root, before["chat_id"]))
+ continued = history(root, key)
+ canonical = canonical_records(database) if sqlite_expected else None
+ assert len(continued["events"]) > len(before["history"]["events"])
+ gateway(root, "stop")
+ if _dock_supported(root):
+ _wait_dock(_dock_socket(root), present=False)
+ gateway(root, "--background")
+ ready(root, expected)
+ if _dock_supported(root):
+ _wait_dock(_dock_socket(root), present=True)
+ assert history(root, key) == continued
+ assert_history_preserved(before["legacy"], history(root, "websocket:legacy-acceptance"))
+ assert_history_preserved(before["display_only"], history(root, "websocket:display-only"))
+ assert canonical_context(root) == before["canonical_only"]
+ if sqlite_expected:
+ assert canonical_records(database) == canonical
+ if before.get("delivery") is not None:
+ assert canonical_records(delivery, ("deliveries",)) == before["delivery"]
+ assert {name: digest(Path(name)) for name in before["files"]} == before["files"]
+ return sqlite_expected
+
+
+def run(args) -> dict:
+ from packaging.utils import parse_wheel_filename
+ from packaging.version import Version
+
+ # The build environment supplies dependencies for metadata construction only.
+ # All product imports and execution happen in the separately installed wheel.
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+ from scripts.build_tui_wheels import wheel_files
+ from scripts.verify_installed_release import _wait_for_closed_listeners, host_environment
+
+ target = args.wheel.resolve(strict=True)
+ version = str(parse_wheel_filename(target.name)[1])
+ tags = parse_wheel_filename(target.name)[3]
+ if len(tags) != 1 or any(tag.platform == "any" for tag in tags):
+ raise ValueError("Acceptance requires the final native wheel, not an intermediate universal wheel")
+ files, _, _ = wheel_files(target, version, platform=next(iter(tags)).platform)
+ if files["nanobot/_build_commit.txt"].decode().strip() != args.commit:
+ raise ValueError("Target wheel does not contain the requested candidate commit")
+ original_hash = digest(target)
+ root = args.output.resolve()
+ root.mkdir(mode=0o700) # Exclusive evidence root. Never use a user's installation.
+ environment = root / "managed"
+ python = environment / ("Scripts/python.exe" if os.name == "nt" else "bin/python")
+ base = Version(version).release
+ baseline_version = ".".join(map(str, (*base[:-1], max(0, base[-1] - 1))))
+ if Version(baseline_version) >= Version(version):
+ raise ValueError("Select a baseline wheel for this candidate version")
+ baseline_source = args.baseline_wheel.resolve(strict=True) if args.baseline_wheel else target
+ if args.baseline_wheel:
+ baseline_version = str(parse_wheel_filename(baseline_source.name)[1])
+ if Version(baseline_version) >= Version(version):
+ raise ValueError("Baseline must precede the target")
+ results = []
+ system = host_environment(dict(os.environ))
+ system.update(HOME=str(root), USERPROFILE=str(root), APPDATA=str(root / "config"),
+ LOCALAPPDATA=str(root / "data"), XDG_CONFIG_HOME=str(root / "config"),
+ XDG_CACHE_HOME=str(root / "cache"), XDG_DATA_HOME=str(root / "data"),
+ TMPDIR=str(root), TMP=str(root), TEMP=str(root),
+ PIP_CONFIG_FILE=os.devnull, PIP_NO_INPUT="1", PIP_DISABLE_PIP_VERSION_CHECK="1", PYTHONUTF8="1",
+ NANOBOT_TUI_NO_DOWNLOAD="1", NO_COLOR="1", PATH=os.defpath)
+ if os.name == "nt":
+ system["PATH"] = str(Path(system["SYSTEMROOT"]) / "System32")
+ # Install once, without inherited user pip settings; every case resets only
+ # nanobot in this private environment. Dependencies stay pinned by its snapshot.
+ subprocess.run([sys.executable, "-I", "-m", "venv", str(environment)], check=True, env=system, timeout=90)
+ subprocess.run([str(python), "-I", "-m", "pip", "install", "--only-binary=:all:", str(target)],
+ check=True, env=system, timeout=600, stdout=subprocess.DEVNULL)
+ write(environment / "nanobot-install.json", {"schema_version": 1, "owner": "nanobot-installer",
+ "environment": str(environment), "extras": []})
+ for scenario in args.scenario or SCENARIOS:
+ case_root = root / scenario
+ case_root.mkdir()
+ account = case_root / "account"
+ account.mkdir()
+ env = dict(system, HOME=str(account), USERPROFILE=str(account), APPDATA=str(account / "config"),
+ LOCALAPPDATA=str(account / "data"), XDG_CONFIG_HOME=str(account / "config"),
+ XDG_CACHE_HOME=str(root / "cache"), XDG_DATA_HOME=str(account / "data"),
+ TMPDIR=str(case_root), TMP=str(case_root), TEMP=str(case_root))
+ selected = target
+ feed = case_root / "feed.json"
+ if scenario in {"upgrade-again", "import-failure", "restart-failure", "restore-interruption"}:
+ intermediate = Version(version).base_version + ".dev0"
+ if not Version(baseline_version) < Version(intermediate) < Version(version):
+ raise ValueError("Consecutive updates require baseline < target.dev0 < target")
+ # Faults and the instrumented intermediate get a distinct version:
+ # never overwrite a previously observed version with healthy bytes.
+ selected = fixture_wheel(target, case_root / "intermediate", intermediate,
+ feed=feed if scenario == "upgrade-again" else None, scenario=scenario)
+ write(feed, feed_records(selected, args.commit))
+ earlier = baseline_version
+ if scenario == "skipped-preview" and not args.baseline_wheel:
+ earlier = Version(version).base_version + ".dev0"
+ if Version(earlier) >= Version(version):
+ raise ValueError("Skipped Preview requires a target newer than dev0")
+ baseline = fixture_wheel(baseline_source, case_root / "baseline", earlier, feed=feed, scenario=scenario)
+ case = {"scenario": scenario, "baseline_version": earlier, "dock": args.dock,
+ "target_version": str(parse_wheel_filename(selected.name)[1]),
+ "baseline_kind": "instrumented historical wheel" if args.baseline_wheel else "instrumented version fixture",
+ "baseline_source_sha256": digest(baseline_source), "baseline_fixture_sha256": digest(baseline),
+ "target_wheel": str(selected), "target_sha256": digest(selected), "commit": args.commit,
+ "target_unmodified": selected == target}
+ write(case_root / "case.json", case)
+ subprocess.run([str(python), "-I", "-m", "pip", "install", "--no-deps", "--force-reinstall", str(baseline)],
+ check=True, env=env, timeout=120, stdout=subprocess.DEVNULL)
+ child = [str(python), "-I", str(Path(__file__).resolve())]
+ with (case_root / "acceptance.log").open("w", encoding="utf-8") as log:
+ def journey():
+ subprocess.run([*child, "--phase", "prepare", "--output", str(case_root)],
+ check=True, env=env, cwd=case_root, stdout=log, stderr=log, timeout=180)
+ launch = read(case_root / "launch.json")
+ subprocess.run(launch["command"], check=True, env=env, cwd=launch["directory"],
+ stdout=log, stderr=log, timeout=420)
+ subprocess.run([*child, "--phase", "verify", "--output", str(case_root)],
+ check=True, env=env, cwd=case_root, stdout=log, stderr=log, timeout=180)
+ return read(case_root / "result.json")
+
+ try:
+ result = journey()
+ if result["phase"] == "restored" or scenario == "upgrade-again":
+ previous_job = read(case_root / "launch.json")["directory"]
+ write(feed, feed_records(target, args.commit, generation=2))
+ write(case_root / "case.json", {
+ **case, "scenario": "upgrade", "baseline_version": result["running_version"],
+ "baseline_kind": "previous journey's running installation",
+ "baseline_source_sha256": (case["baseline_source_sha256"] if result["phase"] == "restored"
+ else case["target_sha256"]),
+ "baseline_fixture_sha256": (case["baseline_fixture_sha256"] if result["phase"] == "restored"
+ else case["target_sha256"]),
+ "target_version": version, "target_wheel": str(target),
+ "target_sha256": original_hash, "target_unmodified": True,
+ })
+ result["subsequent_update"] = journey()
+ assert read(case_root / "launch.json")["directory"] != previous_job
+ assert result["subsequent_update"]["phase"] == "succeeded"
+ write(case_root / "result.json", result)
+ results.append(result)
+ except (subprocess.CalledProcessError, subprocess.TimeoutExpired):
+ log.flush()
+ tail = (case_root / "acceptance.log").read_text(encoding="utf-8", errors="replace")[-8192:]
+ config_file = account / ".nanobot/config.json"
+ if config_file.exists():
+ token = read(config_file)["channels"]["websocket"]["tokenIssueSecret"]
+ tail = tail.replace(token, "[redacted]")
+ print(tail, file=sys.stderr)
+ raise
+ finally:
+ subprocess.run([str(python), "-I", "-m", "nanobot", "gateway", "stop", "--config",
+ str(account / ".nanobot/config.json")], env=env, cwd=case_root,
+ stdout=log, stderr=log, timeout=60, check=True)
+ config_file = account / ".nanobot/config.json"
+ if config_file.exists():
+ config = read(config_file)
+ _wait_for_closed_listeners((config["gateway"]["port"], config["channels"]["websocket"]["port"]))
+ results[-1]["gateway_process_stopped"] = True
+ dock_address = results[-1].get("dock_socket")
+ if not dock_address:
+ dock_address = results[-1].get("subsequent_update", {}).get("dock_socket")
+ if dock_address:
+ _wait_dock(Path(dock_address), present=False)
+ results[-1]["dock_stopped"] = True
+ print(f"PASS {scenario}: {results[-1]['phase']}", flush=True)
+ assert digest(target) == original_hash
+ return {"platform": platform.system(), "machine": platform.machine(), "python": platform.python_version(),
+ "target_sha256": original_hash, "candidate_commit": args.commit, "version": version,
+ "release_transport": "local fixture; no public-download proof", "interactive_ui_e2e": False,
+ "release_approval": "private unsigned fixture; not signature acceptance",
+ "scenarios": results}
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--wheel", type=Path)
+ parser.add_argument("--baseline-wheel", type=Path)
+ parser.add_argument("--commit")
+ parser.add_argument("--output", required=True, type=Path)
+ parser.add_argument("--scenario", action="append", choices=SCENARIOS)
+ parser.add_argument("--dock", action="store_true", help="Verify native macOS background Dock lifecycle")
+ parser.add_argument("--phase", choices=("prepare", "verify"), help=argparse.SUPPRESS)
+ args = parser.parse_args()
+ if not sys.flags.isolated:
+ parser.error("Run with python -I")
+ if args.dock and sys.platform != "darwin":
+ parser.error("--dock requires a real macOS desktop session")
+ if args.phase:
+ if sys.prefix == sys.base_prefix:
+ parser.error("Product phases must run in the disposable installation")
+ if args.phase == "prepare":
+ prepare(args.output)
+ else:
+ write(args.output / "result.json", verify(args.output))
+ return
+ if not args.wheel or not args.commit:
+ parser.error("--wheel and --commit are required")
+ result = run(args)
+ write(args.output / "packaged-update-report.json", result)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/verify_release_approval.py b/scripts/verify_release_approval.py
new file mode 100644
index 000000000..b36e2b5d2
--- /dev/null
+++ b/scripts/verify_release_approval.py
@@ -0,0 +1,41 @@
+"""Check a maintainer's exact release approval before requesting a signature.
+
+This script only reads data. It must run from the protected workflow checkout,
+never from a downloaded candidate, and must never import or execute that package.
+"""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+from pathlib import Path
+
+from nanobot.releases import ReleaseManifest
+
+
+def verify_manifest(path: Path, *, sha256: str, version: str,
+ source_commit: str, candidate_commit: str) -> ReleaseManifest:
+ if path.is_symlink() or not path.is_file() or path.stat().st_size > 64 * 1024:
+ raise ValueError("Expected a bounded, regular release manifest")
+ payload = path.read_bytes()
+ if hashlib.sha256(payload).hexdigest() != sha256:
+ raise ValueError("Manifest differs from the maintainer-approved digest")
+ manifest = ReleaseManifest.model_validate_json(payload)
+ if (manifest.version, manifest.source_commit, manifest.candidate_commit) != (version, source_commit, candidate_commit):
+ raise ValueError("Manifest differs from the maintainer-approved release identity")
+ return manifest
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--manifest", type=Path, required=True)
+ for name in ("sha256", "version", "source-commit", "candidate-commit"):
+ parser.add_argument("--" + name, required=True)
+ args = parser.parse_args()
+ manifest = verify_manifest(args.manifest, sha256=args.sha256, version=args.version,
+ source_commit=args.source_commit, candidate_commit=args.candidate_commit)
+ print(f"Verified exact approval for {manifest.version}; no candidate code was executed")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/agent/test_memory_store.py b/tests/agent/test_memory_store.py
index b83fcdfa3..7dce8360e 100644
--- a/tests/agent/test_memory_store.py
+++ b/tests/agent/test_memory_store.py
@@ -196,7 +196,7 @@ class TestHistoryWithCursor:
assert [entry["cursor"] for entry in entries] == list(range(21, 101))
def test_write_entries_uses_atomic_write(self, tmp_path):
- """_write_entries uses temp file + os.replace for atomicity."""
+ """_write_entries uses a temporary file and atomic replacement."""
store = MemoryStore(tmp_path)
store.append_history("event 1")
store.append_history("event 2")
@@ -221,11 +221,11 @@ class TestHistoryWithCursor:
store.append_history("event 1")
entries = store.read_unprocessed_history(since_cursor=0)
- # Mock os.replace to raise an exception
+ # Fail the platform-independent replacement boundary.
def failing_replace(*args, **kwargs):
raise RuntimeError("Simulated failure")
- monkeypatch.setattr('os.replace', failing_replace)
+ monkeypatch.setattr('nanobot.utils.atomic_file.replace_atomic', failing_replace)
with pytest.raises(RuntimeError):
store._write_entries(entries)
diff --git a/tests/agent/test_runtime_maintenance.py b/tests/agent/test_runtime_maintenance.py
new file mode 100644
index 000000000..1c479eb23
--- /dev/null
+++ b/tests/agent/test_runtime_maintenance.py
@@ -0,0 +1,574 @@
+"""Gateway task admission, without installing packages or contacting a model."""
+
+import asyncio
+import inspect
+import json
+import os
+import sys
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import pytest
+
+from nanobot.agent.runner import AgentRunResult
+from nanobot.bus.events import InboundMessage
+from nanobot.bus.runtime_events import RuntimeModelChanged
+from nanobot.cron.service import CronService
+from nanobot.cron.types import CronSchedule
+from nanobot.providers.base import LLMResponse
+from nanobot.runtime_admission import RuntimeBusyError, RuntimeMaintenanceError
+from nanobot.session.sqlite_store import SessionConflictError
+from nanobot.triggers.local_runner import run_local_trigger_queue
+from nanobot.triggers.local_store import LocalTriggerStore
+from nanobot.utils.llm_runtime import LLMRuntime
+
+
+async def agent(loop_factory):
+ loop = loop_factory()
+ loop.provider.provider_name = "test"
+ loop.provider.chat_stream_with_retry = AsyncMock(return_value=LLMResponse(content="done"))
+ loop.provider.can_resume_conversation_state.return_value = False
+ loop.provider.aclose = AsyncMock()
+ try:
+ yield loop
+ finally:
+ loop.stop()
+ await loop.aclose()
+
+
+def message(content="hello", *, kind=None):
+ metadata = {}
+ if kind == "cron":
+ metadata = {"_cron_trigger": {"job_id": "job", "run_id": "run"}}
+ elif kind == "trigger":
+ metadata = {"_local_trigger": {"trigger_id": "trigger", "delivery_id": "delivery"}}
+ return InboundMessage("cli", "user", "direct", content, metadata=metadata)
+
+
+async def settle(agent):
+ async with asyncio.timeout(3):
+ while agent._has_pending_work():
+ await asyncio.sleep(0)
+
+
+async def test_idle_maintenance_refuses_new_work_and_abort_restores_it(agent):
+ background = asyncio.sleep(0)
+ with pytest.raises(ValueError, match="abort"):
+ with agent.maintenance():
+ with pytest.raises(RuntimeMaintenanceError):
+ await agent.bus.publish_inbound(message())
+ with pytest.raises(RuntimeMaintenanceError):
+ await agent.process_direct("not accepted")
+ with pytest.raises(RuntimeMaintenanceError):
+ await agent.discard_session("cli:direct")
+ with pytest.raises(RuntimeMaintenanceError):
+ await agent.submit_cron_turn(message(kind="cron"))
+ with pytest.raises(RuntimeMaintenanceError):
+ await agent.submit_local_trigger_turn(message(kind="trigger"))
+ with pytest.raises(RuntimeMaintenanceError):
+ await agent.subagents.spawn("not accepted")
+ with pytest.raises(RuntimeMaintenanceError):
+ agent.schedule_background(background)
+ assert inspect.getcoroutinestate(background) == inspect.CORO_CLOSED
+ assert agent.bus.inbound_size == 0
+ assert not agent._pending_queues
+ assert agent.sessions.get_existing("cli:direct") is None
+ # A duplicate attempt must not reopen the first maintenance window.
+ with pytest.raises(RuntimeMaintenanceError):
+ with agent.maintenance():
+ pytest.fail("duplicate maintenance was admitted")
+ assert agent.bus.admission.paused
+ raise ValueError("abort")
+ assert not agent.bus.admission.paused
+ response = await agent.process_direct("accepted after abort")
+ assert response.content == "done"
+
+
[email protected]("cancel", [False, True])
+async def test_direct_turn_including_final_notification_stays_busy(agent, cancel):
+ entered, release, notifying, notified = (asyncio.Event() for _ in range(4))
+
+ async def reply(*args, **kwargs):
+ entered.set()
+ await release.wait()
+ return LLMResponse(content="done")
+
+ original = agent.runtime_event_publisher.run_status_changed
+
+ async def notify(msg, key, status, *args, **kwargs):
+ if status == "idle":
+ notifying.set()
+ await notified.wait()
+ await original(msg, key, status, *args, **kwargs)
+
+ agent.provider.chat_stream_with_retry.side_effect = reply
+ agent.runtime_event_publisher.run_status_changed = notify
+ task = asyncio.create_task(agent.process_direct("work"))
+ try:
+ async with asyncio.timeout(3):
+ await entered.wait()
+ with pytest.raises(RuntimeBusyError):
+ with agent.maintenance():
+ pytest.fail("active direct turn was missed")
+ assert not agent.bus.admission.paused
+ assert not task.done()
+ if cancel:
+ task.cancel()
+ else:
+ release.set()
+ await notifying.wait()
+ with pytest.raises(RuntimeBusyError):
+ with agent.maintenance():
+ pytest.fail("final notification was missed")
+ notified.set()
+ if cancel:
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ else:
+ await task
+ await settle(agent)
+ with agent.maintenance():
+ assert agent.bus.admission.paused
+ finally:
+ release.set()
+ notified.set()
+ if not task.done():
+ task.cancel()
+ await asyncio.gather(task, return_exceptions=True)
+
+
+async def test_dequeue_and_inline_dispatch_have_no_false_idle_gap(agent, monkeypatch):
+ entered, release = asyncio.Event(), asyncio.Event()
+ outcomes = []
+ consume = agent.bus.consume_inbound
+
+ def attempt_maintenance():
+ try:
+ with agent.maintenance():
+ outcomes.append("incorrectly idle")
+ except RuntimeBusyError:
+ outcomes.append("busy")
+
+ async def dequeue():
+ msg = await consume()
+ asyncio.get_running_loop().call_soon(attempt_maintenance)
+ return msg
+
+ async def accept(*args, **kwargs):
+ entered.set()
+ await release.wait()
+
+ monkeypatch.setattr(agent.bus, "consume_inbound", dequeue)
+ monkeypatch.setattr(agent.runtime_event_publisher, "user_input_accepted", accept)
+ await agent.bus.publish_inbound(message())
+ with pytest.raises(RuntimeBusyError):
+ with agent.maintenance():
+ pytest.fail("queued message was missed")
+ consumer = asyncio.create_task(agent.run())
+ try:
+ async with asyncio.timeout(3):
+ await entered.wait()
+ await asyncio.sleep(0)
+ assert outcomes == ["busy"]
+ assert agent.bus.inbound_size == 0
+ assert not agent._active_tasks
+ with pytest.raises(RuntimeBusyError):
+ with agent.maintenance():
+ pytest.fail("inline acceptance was missed")
+ release.set()
+ await agent.bus.consume_outbound()
+ await settle(agent)
+ with agent.maintenance():
+ assert agent.bus.admission.paused
+ finally:
+ release.set()
+ consumer.cancel()
+ await asyncio.gather(consumer, return_exceptions=True)
+
+
+async def test_rejected_input_keeps_failure_delivery_owned(agent, monkeypatch):
+ entered, release = asyncio.Event(), asyncio.Event()
+
+ async def reject(msg):
+ raise SessionConflictError("session changed before admission")
+
+ async def fail(**kwargs):
+ entered.set()
+ await release.wait()
+
+ monkeypatch.setattr(agent, "_dispatch_inbound", reject)
+ monkeypatch.setattr(agent.turn_delivery_factory, "unrouted",
+ lambda *args: SimpleNamespace(fail=fail))
+ await agent.bus.publish_inbound(message())
+ consumer = asyncio.create_task(agent.run())
+ try:
+ async with asyncio.timeout(3):
+ await entered.wait()
+ assert agent.bus.inbound_size == 0
+ assert not agent._active_tasks
+ with pytest.raises(RuntimeBusyError):
+ with agent.maintenance():
+ pytest.fail("failure notification was interrupted by maintenance")
+ finally:
+ release.set()
+ consumer.cancel()
+ await asyncio.gather(consumer, return_exceptions=True)
+
+
+async def test_scheduled_background_work_blocks_before_it_starts(agent):
+ entered, release = asyncio.Event(), asyncio.Event()
+
+ async def work():
+ entered.set()
+ await release.wait()
+
+ agent.schedule_background(work())
+ try:
+ with pytest.raises(RuntimeBusyError):
+ with agent.maintenance():
+ pytest.fail("scheduled task was missed")
+ async with asyncio.timeout(3):
+ await entered.wait()
+ with pytest.raises(RuntimeBusyError):
+ with agent.maintenance():
+ pytest.fail("running task was missed")
+ finally:
+ release.set()
+ await settle(agent)
+ with agent.maintenance():
+ await agent._check_expired_sessions_if_due()
+ assert not agent._background_tasks
+
+
+async def test_queued_event_dispatch_cannot_be_overtaken_by_maintenance(agent):
+ entered, release = asyncio.Event(), asyncio.Event()
+ background_finished = asyncio.Event()
+
+ async def background():
+ background_finished.set()
+
+ async def observe(event):
+ entered.set()
+ await release.wait()
+ agent.schedule_background(background())
+
+ disconnect = agent.bus.subscribe(observe, RuntimeModelChanged)
+ agent.bus.publish_nowait(RuntimeModelChanged("test-model", None))
+ try:
+ with pytest.raises(RuntimeBusyError):
+ with agent.maintenance():
+ pytest.fail("queued event was missed")
+ async with asyncio.timeout(3):
+ await entered.wait()
+ with pytest.raises(RuntimeBusyError):
+ with agent.maintenance():
+ pytest.fail("awaiting subscriber was missed")
+ finally:
+ release.set()
+ await agent.bus.drain()
+ await settle(agent)
+ disconnect()
+ with agent.maintenance():
+ assert background_finished.is_set()
+ assert not agent.bus.has_pending_events
+
+
+async def test_async_idle_scan_keeps_storage_work_owned(agent, monkeypatch):
+ entered, release = asyncio.Event(), asyncio.Event()
+
+ async def scan(*args, **kwargs):
+ entered.set()
+ await release.wait()
+
+ monkeypatch.setattr(agent.auto_compact, "check_expired", scan)
+ agent._next_idle_compact_check_at = 0
+ task = asyncio.create_task(agent._check_expired_sessions_if_due())
+ try:
+ async with asyncio.timeout(3):
+ await entered.wait()
+ with pytest.raises(RuntimeBusyError):
+ with agent.maintenance():
+ pytest.fail("SQLite idle scan was mistaken for an idle runtime")
+ finally:
+ release.set()
+ await task
+ with agent.maintenance():
+ assert agent.bus.admission.paused
+
+
+async def test_cancelled_exec_startup_stays_busy_until_cleanup_finishes(agent, tmp_path, monkeypatch):
+ manager = agent._exec_session_manager
+ entered, cancelling, release = (asyncio.Event() for _ in range(3))
+
+ async def spawn(*args, **kwargs):
+ entered.set()
+ try:
+ await asyncio.Future()
+ finally:
+ cancelling.set()
+ await release.wait()
+
+ monkeypatch.setattr(manager, "_spawn", spawn)
+ task = asyncio.create_task(manager.start(
+ command=[sys.executable, "-c", "pass"], cwd=str(tmp_path), env=dict(os.environ),
+ timeout=10, shell_program=None, login=False, yield_time_ms=0,
+ max_output_chars=1000, owner_session_key="cli:direct",
+ ))
+ stop = None
+ try:
+ async with asyncio.timeout(3):
+ await entered.wait()
+ with pytest.raises(RuntimeBusyError):
+ with agent.maintenance():
+ pytest.fail("launch reservation was missed")
+ stop = asyncio.create_task(manager.terminate_by_owner("cli:direct"))
+ async with asyncio.timeout(3):
+ await cancelling.wait()
+ assert not manager._starting
+ with pytest.raises(RuntimeBusyError):
+ with agent.maintenance():
+ pytest.fail("cancelled launch cleanup was missed")
+ finally:
+ release.set()
+ await asyncio.gather(task, *([stop] if stop is not None else []), return_exceptions=True)
+ with agent.maintenance():
+ assert not manager.has_pending_work
+
+
+async def test_detached_real_exec_blocks_maintenance_without_being_killed(agent, tmp_path):
+ manager = agent._exec_session_manager
+ session_id, result = await manager.start(
+ command=[sys.executable, "-I", "-c", "import sys; print('ready', flush=True); sys.stdin.readline()"],
+ cwd=str(tmp_path), env=dict(os.environ), timeout=10, shell_program=None,
+ login=False, yield_time_ms=100, max_output_chars=1000, owner_session_key="cli:direct",
+ )
+ assert not result.done
+ with pytest.raises(RuntimeBusyError):
+ with agent.maintenance():
+ pytest.fail("detached command was missed")
+ assert (await manager.list(owner_session_key="cli:direct"))[0].returncode is None
+ result = await manager.write(
+ session_id=session_id, chars="finish\n", close_stdin=False, terminate=False,
+ yield_time_ms=3000, max_output_chars=1000, owner_session_key="cli:direct",
+ )
+ assert result.done and result.exit_code == 0 and result.finish_reason == "exit"
+ with agent.maintenance():
+ assert not manager.has_pending_work
+
+
[email protected]("operation", ["close_all", "terminate_by_owner", "discard_session"])
+async def test_exec_cleanup_is_owned_through_failure_and_retry(agent, tmp_path, monkeypatch, operation):
+ manager = agent._exec_session_manager
+ session_id, _ = await manager.start(
+ command=[sys.executable, "-I", "-c", "import sys; sys.stdin.readline()"],
+ cwd=str(tmp_path), env=dict(os.environ), timeout=10, shell_program=None,
+ login=False, yield_time_ms=0, max_output_chars=1000, owner_session_key="cli:direct",
+ )
+ session = manager._sessions[session_id]
+ original = session._kill
+ entered, release = asyncio.Event(), asyncio.Event()
+ fail = True
+
+ async def cleanup():
+ entered.set()
+ await release.wait()
+ await original()
+ if fail:
+ raise OSError("cleanup was not confirmed")
+
+ async def terminate():
+ if operation == "close_all":
+ await manager.close_all()
+ elif operation == "terminate_by_owner":
+ await manager.terminate_by_owner("cli:direct")
+ else:
+ await agent.discard_session("cli:direct")
+
+ monkeypatch.setattr(session, "_kill", cleanup)
+ task = asyncio.create_task(terminate())
+ try:
+ async with asyncio.timeout(3):
+ await entered.wait()
+ with pytest.raises(RuntimeBusyError):
+ with agent.maintenance():
+ pytest.fail("in-flight process cleanup was missed")
+ release.set()
+ with pytest.raises(OSError, match="cleanup was not confirmed"):
+ await task
+ # An exited parent alone cannot prove that failed process-tree cleanup settled.
+ assert session.process.returncode is not None
+ with pytest.raises(RuntimeBusyError):
+ with agent.maintenance():
+ pytest.fail("failed cleanup was treated as idle")
+ fail = False
+ await terminate()
+ with agent.maintenance():
+ assert not manager.has_pending_work
+ finally:
+ fail = False
+ release.set()
+ await asyncio.gather(task, return_exceptions=True)
+ await manager.close_all()
+
+
+async def test_cancelled_exec_close_keeps_unfinished_cleanup_owned(agent, tmp_path, monkeypatch):
+ manager = agent._exec_session_manager
+ session_id, _ = await manager.start(
+ command=[sys.executable, "-I", "-c", "import sys; sys.stdin.readline()"],
+ cwd=str(tmp_path), env=dict(os.environ), timeout=10, shell_program=None,
+ login=False, yield_time_ms=0, max_output_chars=1000, owner_session_key="cli:direct",
+ )
+ session = manager._sessions[session_id]
+ original = session._kill
+ entered, release = asyncio.Event(), asyncio.Event()
+
+ async def cleanup():
+ entered.set()
+ await release.wait()
+ await original()
+
+ monkeypatch.setattr(session, "_kill", cleanup)
+ task = asyncio.create_task(manager.close_all())
+ try:
+ async with asyncio.timeout(3):
+ await entered.wait()
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ with pytest.raises(RuntimeBusyError):
+ with agent.maintenance():
+ pytest.fail("cancelled close lost its still-running cleanup")
+ release.set()
+ await manager.close_all()
+ with agent.maintenance():
+ assert not manager.has_pending_work
+ finally:
+ release.set()
+ await asyncio.gather(task, return_exceptions=True)
+ await manager.close_all()
+
+
+async def test_subagent_execution_and_cleanup_are_both_busy(agent, monkeypatch):
+ manager = agent.subagents
+ manager.runner.run = AsyncMock(return_value=AgentRunResult(messages=[], final_content="finished"))
+ runtime = LLMRuntime.capture(agent.provider, "test-model", context_window_tokens=4096)
+ await manager.spawn("child", runtime=runtime)
+ record = next(iter(manager._tasks.values()))
+ cleaning, release = asyncio.Event(), asyncio.Event()
+ original = record.exec_manager.close_all
+
+ async def cleanup():
+ cleaning.set()
+ await release.wait()
+ return await original()
+
+ monkeypatch.setattr(record.exec_manager, "close_all", cleanup)
+ try:
+ with pytest.raises(RuntimeBusyError):
+ with agent.maintenance():
+ pytest.fail("subagent was missed")
+ async with asyncio.timeout(3):
+ await cleaning.wait()
+ with pytest.raises(RuntimeBusyError):
+ with agent.maintenance():
+ pytest.fail("subagent cleanup was missed")
+ finally:
+ release.set()
+ await manager.close()
+ await agent.bus.drain()
+ assert not manager.has_pending_work
+
+
[email protected]("stop", [False, True])
+async def test_cron_timer_waits_without_consuming_and_manual_run_is_refused(agent, tmp_path, stop):
+ ran = asyncio.Event()
+
+ async def callback(job):
+ with pytest.raises(RuntimeBusyError):
+ with agent.maintenance():
+ pytest.fail("cron callback was missed")
+ ran.set()
+
+ cron = CronService(tmp_path / "cron/jobs.json", callback, admission=agent.bus.admission)
+ await cron.start()
+ job = cron.add_job(
+ name="scheduled", schedule=CronSchedule(kind="every", every_ms=3600000),
+ message="work", session_key="websocket:test", origin_channel="websocket",
+ origin_chat_id="test",
+ )
+ timer = None
+ try:
+ with agent.maintenance():
+ job.state.next_run_at_ms = 1
+ cron._save_store()
+ before = cron.store_path.read_bytes()
+ cron._arm_timer()
+ timer = cron._timer_task
+ await asyncio.sleep(0)
+ await asyncio.sleep(0)
+ assert not ran.is_set() and not timer.done()
+ with pytest.raises(RuntimeMaintenanceError):
+ await cron.run_job(job.id, force=True)
+ assert cron.store_path.read_bytes() == before
+ if stop:
+ cron.stop()
+ await asyncio.gather(timer, return_exceptions=True)
+ if stop:
+ assert not ran.is_set()
+ else:
+ # A user may abort and immediately retry before this waiter resumes.
+ with agent.maintenance():
+ await asyncio.sleep(0)
+ assert not ran.is_set() and not timer.done()
+ assert cron.store_path.read_bytes() == before
+ async with asyncio.timeout(3):
+ await ran.wait()
+ # The scheduler cancels its previous timer when rearming itself.
+ await asyncio.gather(timer, return_exceptions=True)
+ assert len(cron.get_job(job.id).state.run_history) == 1
+ assert cron._timer_task is not timer and not cron._timer_task.done()
+ finally:
+ timer = cron._timer_task
+ cron.stop()
+ if timer is not None:
+ await asyncio.gather(timer, return_exceptions=True)
+
+
+async def test_trigger_intake_does_not_claim_until_maintenance_released(agent, tmp_path):
+ store = LocalTriggerStore(tmp_path)
+ trigger = store.create(name="test", channel="cli", chat_id="test", session_key="cli:test")
+ delivery = store.enqueue(trigger.id, "work")
+ entered, release = asyncio.Event(), asyncio.Event()
+
+ async def submit(msg):
+ entered.set()
+ await release.wait()
+
+ worker = None
+ try:
+ with agent.maintenance():
+ worker = asyncio.create_task(run_local_trigger_queue(
+ store=store, submit_turn=submit, is_channel_enabled=lambda name: True,
+ poll_interval_s=0.01, admission=agent.bus.admission,
+ ))
+ await asyncio.sleep(0)
+ assert not entered.is_set()
+ assert len(list(store.inbox_dir.glob("*.json"))) == 1
+ assert not list(store.processing_dir.glob("*.json"))
+ async with asyncio.timeout(3):
+ await entered.wait()
+ with pytest.raises(RuntimeBusyError):
+ with agent.maintenance():
+ pytest.fail("claimed trigger batch was missed")
+ release.set()
+ path = store.runs_dir / f"{delivery.id}.json"
+ while json.loads(path.read_text())["status"] != "ok":
+ await asyncio.sleep(0)
+ with agent.maintenance():
+ assert not list(store.inbox_dir.glob("*.json"))
+ finally:
+ release.set()
+ if worker is not None:
+ worker.cancel()
+ await asyncio.gather(worker, return_exceptions=True)
diff --git a/tests/agent/test_subagent_control.py b/tests/agent/test_subagent_control.py
index fea3aba7e..4f942b1ac 100644
--- a/tests/agent/test_subagent_control.py
+++ b/tests/agent/test_subagent_control.py
@@ -185,6 +185,9 @@ async def test_default_loop_keeps_slack_thread_for_late_subagent_result(
tmp_path, monkeypatch, cache_invalidation,
):
monkeypatch.setattr("nanobot.agent.loop._SUBAGENT_TERMINAL_WAIT_SECONDS", 0.01)
+ # This checks real default-runtime routing and persistence, not disk latency.
+ # Keep bounded waits without treating a loaded Windows runner as a routing failure.
+ timeout = 30
child_started, release_child, parent_idle = (asyncio.Event() for _ in range(3))
class Provider(LLMProvider):
@@ -229,7 +232,7 @@ async def test_default_loop_keeps_slack_thread_for_late_subagent_result(
unsubscribe = bus.subscribe(observe_idle, TurnRunStatusChanged)
async def next_reply(content):
- async with asyncio.timeout(5):
+ async with asyncio.timeout(timeout):
while True:
message = await bus.consume_outbound()
if message.content == content and message.event is None:
@@ -242,8 +245,8 @@ async def test_default_loop_keeps_slack_thread_for_late_subagent_result(
metadata={"slack": slack_route}, session_key_override=session_key,
))
initial_reply = await next_reply("Parent reply")
- await asyncio.wait_for(child_started.wait(), timeout=5)
- await asyncio.wait_for(parent_idle.wait(), timeout=5)
+ await asyncio.wait_for(child_started.wait(), timeout=timeout)
+ await asyncio.wait_for(parent_idle.wait(), timeout=timeout)
saved = SessionManager(workspace, sessions_root=sessions_root).get_existing(session_key)
assert saved is not None
saved_route = saved.metadata["_compaction_route"]
@@ -263,8 +266,10 @@ async def test_default_loop_keeps_slack_thread_for_late_subagent_result(
finally:
release_child.set()
loop.stop()
- await asyncio.wait_for(consumer, timeout=2)
- unsubscribe()
+ try:
+ await asyncio.wait_for(consumer, timeout=timeout)
+ finally:
+ unsubscribe()
@pytest.mark.asyncio
diff --git a/tests/architecture/test_import_boundaries.py b/tests/architecture/test_import_boundaries.py
index 08029cf36..1403aee64 100644
--- a/tests/architecture/test_import_boundaries.py
+++ b/tests/architecture/test_import_boundaries.py
@@ -11,6 +11,34 @@ import pytest
from scripts.check_import_boundaries import Violation, find_violations
[email protected]("module", [
+ "nanobot.agent.loop", "nanobot.session.state", "nanobot.runtime_admission",
+ "nanobot.data_access", "nanobot.installation_lock",
+])
+def test_runtime_owners_do_not_depend_on_update_policy(module: str) -> None:
+ assert find_violations("from nanobot.update_service import UpdateService", module) == [
+ Violation("update-policy-direction", "nanobot.update_service.UpdateService", 1),
+ ]
+
+
+def test_updater_uses_process_contracts_not_agent_or_client_implementations() -> None:
+ assert find_violations("from nanobot.agent.loop import AgentLoop", "nanobot.update_stop") == [
+ Violation("update-domain", "nanobot.agent.loop.AgentLoop", 1),
+ ]
+ assert find_violations(
+ "from nanobot.gateway.runtime import GatewayRuntime", "nanobot.update_stop",
+ ) == []
+ assert find_violations(
+ "from nanobot.update_stop import watch_gateway_stop", "nanobot.cli.gateway_runtime",
+ ) == []
+ assert find_violations(
+ "from nanobot.cli.gateway_runtime import _run_gateway", "nanobot.update_restart",
+ ) == []
+ assert find_violations(
+ "from nanobot.agent.loop import AgentLoop", "nanobot.update_restart",
+ ) == [Violation("update-restart-adapter", "nanobot.agent.loop.AgentLoop", 1)]
+
+
@pytest.mark.parametrize(
("source", "target", "line"),
[
diff --git a/tests/channels/test_channel_manager_concurrency.py b/tests/channels/test_channel_manager_concurrency.py
index 4ae168cc6..b053a890c 100644
--- a/tests/channels/test_channel_manager_concurrency.py
+++ b/tests/channels/test_channel_manager_concurrency.py
@@ -1,12 +1,15 @@
import asyncio
from unittest.mock import AsyncMock, MagicMock
+import pytest
+
from nanobot.bus.events import OutboundMessage
from nanobot.bus.queue import MessageBus
from nanobot.channels import manager as manager_module
from nanobot.channels.base import BaseChannel
from nanobot.channels.manager import ChannelManager
from nanobot.config.schema import Config
+from nanobot.runtime_admission import RuntimeBusyError
def make_manager():
@@ -15,10 +18,66 @@ def make_manager():
channel = MagicMock(spec=BaseChannel)
channel.send = AsyncMock()
channel.stop = AsyncMock()
+ channel.has_pending_delivery = False
manager.channels["websocket"] = channel
return manager, channel
+async def test_delivery_has_no_idle_gap_between_queue_dispatch_and_send(monkeypatch):
+ manager, channel = make_manager()
+ started, release = asyncio.Event(), asyncio.Event()
+ observations = []
+ consume = manager.bus.consume_outbound
+
+ def require_busy():
+ if manager.bus.admission.paused:
+ observations.append("parked")
+ return
+ with pytest.raises(RuntimeBusyError):
+ with manager.bus.admission.pause_if_idle(lambda: False):
+ pytest.fail("Delivery was incorrectly reported idle")
+ observations.append("busy")
+ assert not manager.bus.admission.paused
+
+ async def dequeue():
+ message = await consume()
+ asyncio.get_running_loop().call_soon(require_busy)
+ return message
+
+ async def send(message):
+ started.set()
+ await release.wait()
+
+ monkeypatch.setattr(manager.bus, "consume_outbound", dequeue)
+ channel.send.side_effect = send
+ await manager.bus.publish_outbound(OutboundMessage("websocket", "chat", "final reply"))
+ require_busy()
+ manager._dispatch_task = asyncio.create_task(manager._dispatch_outbound())
+ try:
+ await asyncio.wait_for(started.wait(), 2)
+ assert manager.bus.outbound_size == 0
+ require_busy()
+ assert observations == ["busy", "busy", "busy"]
+ release.set()
+ await wait_until(lambda: not manager.has_pending_delivery)
+ with manager.bus.admission.pause_if_idle(lambda: False):
+ assert manager.bus.admission.paused
+ # A late producer may queue a lifecycle notice while the consumer
+ # is awaiting an empty queue. It must remain parked until admission
+ # is restored, rather than start new transport writes under the gate.
+ await manager.bus.publish_outbound(OutboundMessage("websocket", "chat", "late notice"))
+ await wait_until(lambda: manager._outbound_dispatching)
+ await wait_until(lambda: len(observations) == 4)
+ channel.send.assert_awaited_once()
+ assert not manager.bus.admission.paused
+ await wait_until(lambda: not manager.has_pending_delivery)
+ assert [call.args[0].content for call in channel.send.await_args_list] == ["final reply", "late notice"]
+ assert observations == ["busy", "busy", "busy", "parked"]
+ finally:
+ release.set()
+ await manager.stop_all()
+
+
async def wait_until(predicate):
async with asyncio.timeout(2):
while not predicate():
diff --git a/tests/channels/test_channel_plugins.py b/tests/channels/test_channel_plugins.py
index c6ab82372..269241aae 100644
--- a/tests/channels/test_channel_plugins.py
+++ b/tests/channels/test_channel_plugins.py
@@ -306,12 +306,17 @@ def test_special_setup_validation_is_owned_by_channel_package(name: str):
@pytest.mark.parametrize("name", ["feishu", "linear", "qq", "weixin", "whatsapp"])
def test_interactive_connector_is_owned_by_channel_package(name: str):
+ from nanobot.channels.connect import ManagedChannelConnector
+
plugin = load_channel_package(name)
assert plugin is not None
assert plugin.connector is not None
assert plugin.connector.startswith(f"nanobot.channels.{name}.")
- assert plugin.load_connector().__class__.__module__ == f"nanobot.channels.{name}.connect"
+ connector = plugin.load_connector()
+ assert connector.__class__.__module__ == f"nanobot.channels.{name}.connect"
+ assert isinstance(connector, ManagedChannelConnector)
+ assert connector.has_pending_work is False
def test_descriptor_defaults_cover_onboarding_fields_without_runtime_import():
@@ -3559,9 +3564,8 @@ async def test_stop_all_cancels_dispatcher_and_stops_channels():
providers=SimpleNamespace(groq=SimpleNamespace(api_key="")),
)
- mgr = ChannelManager.__new__(ChannelManager)
+ mgr = ChannelManager(Config.model_validate({"channels": {"websocket": {"enabled": False}}}), MessageBus())
mgr.config = fake_config
- mgr.bus = MessageBus()
ch = _StartableChannel(fake_config, mgr.bus)
mgr.channels = {"startable": ch}
@@ -3641,9 +3645,8 @@ async def test_stop_all_handles_channel_exception():
providers=SimpleNamespace(groq=SimpleNamespace(api_key="")),
)
- mgr = ChannelManager.__new__(ChannelManager)
+ mgr = ChannelManager(Config.model_validate({"channels": {"websocket": {"enabled": False}}}), MessageBus())
mgr.config = fake_config
- mgr.bus = MessageBus()
mgr.channels = {"stopfailing": _StopFailingChannel(fake_config, mgr.bus)}
mgr._channel_tasks = {}
mgr._outbound_tasks = {}
@@ -3678,9 +3681,8 @@ async def test_stop_all_handles_channel_stop_cancelled_task():
providers=SimpleNamespace(groq=SimpleNamespace(api_key="")),
)
- mgr = ChannelManager.__new__(ChannelManager)
+ mgr = ChannelManager(Config.model_validate({"channels": {"websocket": {"enabled": False}}}), MessageBus())
mgr.config = fake_config
- mgr.bus = MessageBus()
next_channel = _StartableChannel(fake_config, mgr.bus)
mgr.channels = {
"stopcancelled": _StopCancelledChannel(fake_config, mgr.bus),
@@ -3704,9 +3706,8 @@ async def test_start_all_no_channels_logs_warning():
providers=SimpleNamespace(groq=SimpleNamespace(api_key="")),
)
- mgr = ChannelManager.__new__(ChannelManager)
+ mgr = ChannelManager(Config.model_validate({"channels": {"websocket": {"enabled": False}}}), MessageBus())
mgr.config = fake_config
- mgr.bus = MessageBus()
mgr.channels = {} # No channels
mgr._dispatch_task = None
@@ -3724,9 +3725,8 @@ async def test_start_all_creates_dispatch_task():
providers=SimpleNamespace(groq=SimpleNamespace(api_key="")),
)
- mgr = ChannelManager.__new__(ChannelManager)
+ mgr = ChannelManager(Config.model_validate({"channels": {"websocket": {"enabled": False}}}), MessageBus())
mgr.config = fake_config
- mgr.bus = MessageBus()
ch = _StartableChannel(fake_config, mgr.bus)
mgr.channels = {"startable": ch}
diff --git a/tests/channels/test_scheduled_delivery.py b/tests/channels/test_scheduled_delivery.py
index 083d07740..813775b99 100644
--- a/tests/channels/test_scheduled_delivery.py
+++ b/tests/channels/test_scheduled_delivery.py
@@ -33,6 +33,7 @@ from nanobot.cron.bound_runner import run_bound_cron_job
from nanobot.cron.service import CronService
from nanobot.cron.types import CronSchedule
from nanobot.providers.base import GenerationSettings, LLMResponse, ToolCallRequest
+from nanobot.runtime_admission import RuntimeBusyError, RuntimeMaintenanceError
from nanobot.session.manager import SessionManager
@@ -62,6 +63,58 @@ async def drain(manager):
await asyncio.sleep(0.01)
+async def test_parked_gateway_neither_initializes_nor_records_scheduled_delivery(tmp_path):
+ manager = make_manager(tmp_path)
+ try:
+ with manager.bus.admission.pause_before_start():
+ manager._dispatch_task = asyncio.create_task(manager._dispatch_outbound())
+ await asyncio.sleep(0)
+ assert not manager._outbox.path.exists()
+ with pytest.raises(RuntimeMaintenanceError):
+ await manager.bus.publish_outbound(message())
+ with pytest.raises(RuntimeMaintenanceError):
+ await manager._recover_scheduled()
+ assert not manager._outbox.path.exists()
+ assert manager.bus.outbound_size == 0
+ await manager.bus.publish_outbound(message())
+ assert manager._outbox.path.exists()
+ finally:
+ await manager.stop_all()
+
+
+async def test_scheduled_recovery_remains_busy_while_waiting_for_a_send_slot(tmp_path, monkeypatch):
+ manager = make_manager(tmp_path)
+ channel = MagicMock(spec=BaseChannel, send=AsyncMock(), stop=AsyncMock())
+ channel.has_pending_delivery = False
+ manager.channels["whatsapp"] = channel
+ manager._outbox.record(message())
+ manager._outbound_slots = asyncio.Semaphore(0)
+ queued = asyncio.Event()
+ queue = manager._queue_outbound
+
+ async def wait_for_slot(channel, msg):
+ queued.set()
+ await queue(channel, msg)
+
+ monkeypatch.setattr(manager, "_queue_outbound", wait_for_slot)
+ recovery = asyncio.create_task(manager._recover_scheduled())
+ try:
+ await asyncio.wait_for(queued.wait(), 2)
+ assert not manager._outbound_tasks
+ with pytest.raises(RuntimeBusyError):
+ with manager.bus.admission.pause_if_idle(lambda: False):
+ pytest.fail("Durable recovery was admitted during maintenance")
+ manager._outbound_slots.release()
+ await asyncio.wait_for(recovery, 2)
+ await drain(manager)
+ channel.send.assert_awaited_once()
+ assert rows(manager._outbox)[0]["status"] == "sent"
+ finally:
+ recovery.cancel()
+ await asyncio.gather(recovery, return_exceptions=True)
+ await manager.stop_all()
+
+
@pytest.mark.parametrize("legacy_message,one_shot,origin", [
(False, False, "whatsapp"), (True, False, "whatsapp"), (True, True, "whatsapp"),
(True, False, "websocket"),
diff --git a/tests/cli/test_cli_input.py b/tests/cli/test_cli_input.py
index f296be31c..ba1f473f7 100644
--- a/tests/cli/test_cli_input.py
+++ b/tests/cli/test_cli_input.py
@@ -1,3 +1,4 @@
+import asyncio
from contextlib import nullcontext
from io import StringIO
from unittest.mock import AsyncMock, MagicMock, call, patch
@@ -9,6 +10,14 @@ from nanobot.cli import stream as stream_mod
from nanobot.cli import terminal
[email protected](autouse=True)
+def isolate_prompt_session(tmp_path, monkeypatch):
+ """Keep real parser tests out of user history and other prompt sessions."""
+ monkeypatch.setattr("nanobot.config.paths.get_cli_history_path", lambda: tmp_path / "history")
+ monkeypatch.setattr(terminal, "_prompt_session", None)
+ monkeypatch.setattr(terminal, "_saved_term_attrs", None)
+
+
@pytest.fixture
def mock_prompt_session():
"""Mock the global prompt session."""
@@ -105,7 +114,10 @@ async def test_raw_lf_enter_still_submits_like_wsl_terminals():
terminal._init_prompt_session()
session = terminal._prompt_session
pipe_input.send_text("hello\x0aworld\r")
- result = await session.prompt_async("> ")
+ # CI has no user to acknowledge prompt_toolkit's exception prompt.
+ result = await asyncio.wait_for(
+ session.prompt_async("> ", set_exception_handler=False), timeout=10,
+ )
assert result == "hello"
@@ -122,7 +134,9 @@ async def test_alt_enter_inserts_newline_on_lf_terminals():
terminal._init_prompt_session()
session = terminal._prompt_session
pipe_input.send_text("foo\x1b\x0abar\r")
- result = await session.prompt_async("> ")
+ result = await asyncio.wait_for(
+ session.prompt_async("> ", set_exception_handler=False), timeout=10,
+ )
assert result == "foo\nbar"
@@ -139,7 +153,9 @@ async def test_csi_u_shift_enter_inserts_newline_not_raw_escape():
terminal._init_prompt_session()
session = terminal._prompt_session
pipe_input.send_text("foo\x1b[13;2ubar\r")
- result = await session.prompt_async("> ")
+ result = await asyncio.wait_for(
+ session.prompt_async("> ", set_exception_handler=False), timeout=10,
+ )
# A newline is inserted and no raw escape bytes leak into the result.
assert result == "foo\nbar"
diff --git a/tests/cli/test_commands.py b/tests/cli/test_commands.py
index c913a1a0a..69b057290 100644
--- a/tests/cli/test_commands.py
+++ b/tests/cli/test_commands.py
@@ -3,8 +3,9 @@ import json
import re
import shutil
import signal
+import sys
import urllib.error
-from contextlib import contextmanager, suppress
+from contextlib import contextmanager, nullcontext, suppress
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
@@ -48,6 +49,8 @@ runner = CliRunner()
def mock_webui_bundle(monkeypatch) -> MagicMock:
prepare_bundle = MagicMock()
monkeypatch.setattr(cli_webui, "_prepare_webui_bundle_for_gateway", prepare_bundle)
+ monkeypatch.setattr(cli_webui, "dock_icon", lambda *_args, **_kwargs: nullcontext())
+ monkeypatch.setattr(cli_webui, "request_gateway_icon", lambda *_args, **_kwargs: None)
return prepare_bundle
@@ -93,6 +96,10 @@ class _GatewayAgentContractStub:
tools = ToolRegistry()
subagents = MagicMock(spec=SubagentManager)
+ @contextmanager
+ def maintenance(self):
+ yield
+
async def discard_session(self, _session_key: str) -> None:
pass
@@ -1717,7 +1724,7 @@ def test_agent_uses_workspace_directory_for_cron_store(monkeypatch, tmp_path: Pa
monkeypatch.setattr("nanobot.bus.queue.MessageBus", lambda: object())
class _FakeCron:
- def __init__(self, store_path: Path) -> None:
+ def __init__(self, store_path: Path, *, admission=None) -> None:
seen["cron_store"] = store_path
class _FakeAgentLoop:
@@ -1767,7 +1774,7 @@ def test_agent_workspace_override_does_not_migrate_legacy_cron(
monkeypatch.setattr("nanobot.config.paths.get_cron_dir", lambda: legacy_dir)
class _FakeCron:
- def __init__(self, store_path: Path) -> None:
+ def __init__(self, store_path: Path, *, admission=None) -> None:
seen["cron_store"] = store_path
class _FakeAgentLoop:
@@ -1823,7 +1830,7 @@ def test_agent_custom_config_workspace_does_not_migrate_legacy_cron(
monkeypatch.setattr("nanobot.config.paths.get_cron_dir", lambda: legacy_dir)
class _FakeCron:
- def __init__(self, store_path: Path) -> None:
+ def __init__(self, store_path: Path, *, admission=None) -> None:
seen["cron_store"] = store_path
class _FakeAgentLoop:
@@ -1853,9 +1860,8 @@ def test_agent_custom_config_workspace_does_not_migrate_legacy_cron(
assert not (custom_workspace / "cron" / "jobs.json").exists()
-def test_agent_overrides_workspace_path(mock_agent_runtime):
- workspace_path = Path("/tmp/agent-workspace")
-
[email protected]("workspace_path", [Path("/tmp/agent-workspace"), Path("relative-agent-workspace")])
+def test_agent_overrides_workspace_path(mock_agent_runtime, workspace_path):
result = runner.invoke(app, ["agent", "-m", "hello", "-w", str(workspace_path)])
assert result.exit_code == 0
@@ -2174,7 +2180,7 @@ def test_heartbeat_empty_response_is_not_evaluated(
return [{"key": "telegram:u1"}]
class _FakeCron:
- def __init__(self, _store_path: Path) -> None:
+ def __init__(self, _store_path: Path, *, admission=None) -> None:
self.on_job = None
seen["cron"] = self
@@ -2367,6 +2373,36 @@ def test_webui_background_points_to_the_single_persistent_gateway_command(
assert not config_file.exists()
[email protected]("managed", [False, True], ids=["explicit-detach", "fresh-installer"])
[email protected]("no_dock", [False, True])
+def test_webui_detached_gateway_does_not_retain_launcher_lease(monkeypatch, tmp_path, managed, no_dock):
+ config = tmp_path / "config.json"
+ _patch_webui_provider_ready(monkeypatch)
+ _patch_gateway_ports_free(monkeypatch)
+ seen = _patch_webui_managed_gateway(monkeypatch)
+ requested = []
+ monkeypatch.setattr(cli_webui, "request_gateway_icon",
+ lambda instance, *, enabled: requested.append((instance, enabled)))
+ if managed:
+ prefix = tmp_path / "managed"
+ prefix.mkdir()
+ (prefix / "nanobot-install.json").write_text(json.dumps({
+ "schema_version": 1, "owner": "nanobot-installer", "environment": str(prefix), "extras": [],
+ }))
+ monkeypatch.setattr(sys, "prefix", str(prefix))
+ result = runner.invoke(app, ["webui", "--config", str(config), "--yes", "--no-open",
+ *([] if managed else ["--detach"]),
+ *(["--no-dock"] if no_dock else [])])
+ assert result.exit_code == 0, result.output
+ assert "start_options" in seen
+ assert "attached_runtime" not in seen
+ assert "lease_release_wait_for_stop" not in seen
+ assert "Stop nanobot" in result.stdout
+ assert len(requested) == 1
+ assert requested[0][0].parent == tmp_path / "run"
+ assert requested[0][1] is not no_dock
+
+
def test_webui_dev_starts_vite_sidecar_and_gateway(monkeypatch, tmp_path: Path) -> None:
config_file = tmp_path / "config.json"
config_file.write_text("{}", encoding="utf-8")
@@ -2725,6 +2761,35 @@ def test_launch_browser_uses_unix_launcher_on_linux(monkeypatch) -> None:
assert opened == ["http://127.0.0.1:8765/"]
[email protected]("no_dock", [False, True])
+def test_webui_dock_lifetime_wraps_the_attached_client(monkeypatch, tmp_path, no_dock):
+ config_file = tmp_path / "config.json"
+ config_file.write_text("{}")
+ _patch_gateway_ports_free(monkeypatch)
+ _patch_webui_provider_ready(monkeypatch)
+ _patch_webui_managed_gateway(monkeypatch)
+ events = []
+
+ @contextmanager
+ def desktop(url, *, instance, enabled):
+ assert url.startswith("http://127.0.0.1:")
+ assert instance.parent == tmp_path / "run"
+ assert enabled is not no_dock
+ events.append("icon attached")
+ try:
+ yield
+ finally:
+ events.append("icon detached")
+
+ monkeypatch.setattr(cli_webui, "dock_icon", desktop)
+ monkeypatch.setattr(cli_webui, "_attach_to_background_gateway",
+ lambda *_args, **_kwargs: events.append("gateway attached"))
+ result = runner.invoke(app, ["webui", "--config", str(config_file), "--no-open", "--yes",
+ *(["--no-dock"] if no_dock else [])])
+ assert result.exit_code == 0, result.output
+ assert events == ["icon attached", "gateway attached", "icon detached"]
+
+
def test_webui_foreground_attaches_to_existing_managed_gateway(monkeypatch, tmp_path: Path) -> None:
config_file = tmp_path / "config.json"
config_file.write_text("{}")
@@ -3151,7 +3216,7 @@ def test_gateway_uses_workspace_directory_for_cron_store(monkeypatch, tmp_path:
seen: dict[str, Path] = {}
class _StopCron:
- def __init__(self, store_path: Path) -> None:
+ def __init__(self, store_path: Path, *, admission=None) -> None:
seen["cron_store"] = store_path
raise _StopGatewayError("stop")
@@ -3221,7 +3286,7 @@ def test_gateway_unbound_agent_cron_is_skipped(
monkeypatch.setattr("nanobot.session.manager.SessionManager", _FakeSessionManager)
class _FakeCron:
- def __init__(self, _store_path: Path) -> None:
+ def __init__(self, _store_path: Path, *, admission=None) -> None:
self.on_job = None
seen["cron"] = self
@@ -3334,7 +3399,7 @@ def test_gateway_bound_cron_runs_as_session_turn(
monkeypatch.setattr("nanobot.session.manager.SessionManager", _FakeSessionManager)
class _FakeCron:
- def __init__(self, _store_path: Path) -> None:
+ def __init__(self, _store_path: Path, *, admission=None) -> None:
self.on_job = None
seen["cron"] = self
@@ -3526,7 +3591,7 @@ def test_gateway_local_trigger_queue_submits_agent_turns(
config,
message_bus=lambda: bus,
session_manager=lambda _workspace: _FakeSessionManager(),
- cron_service=lambda _store_path: _FakeCronService(),
+ cron_service=lambda _store_path, **_kwargs: _FakeCronService(),
)
class _FakeMemory:
@@ -3687,7 +3752,7 @@ def test_gateway_workspace_override_does_not_migrate_legacy_cron(
seen: dict[str, Path] = {}
class _StopCron:
- def __init__(self, store_path: Path) -> None:
+ def __init__(self, store_path: Path, *, admission=None) -> None:
seen["cron_store"] = store_path
raise _StopGatewayError("stop")
@@ -3726,7 +3791,7 @@ def test_gateway_custom_config_workspace_does_not_migrate_legacy_cron(
seen: dict[str, Path] = {}
class _StopCron:
- def __init__(self, store_path: Path) -> None:
+ def __init__(self, store_path: Path, *, admission=None) -> None:
seen["cron_store"] = store_path
raise _StopGatewayError("stop")
@@ -3879,7 +3944,7 @@ def test_gateway_health_endpoint_binds_and_serves_expected_responses(
return None
class _FakeCronService:
- def __init__(self, _store_path: Path) -> None:
+ def __init__(self, _store_path: Path, *, admission=None) -> None:
self.on_job = None
async def start(self) -> None:
@@ -3971,6 +4036,10 @@ def test_gateway_health_endpoint_binds_and_serves_expected_responses(
assert health_writer.closed is True
assert "HTTP/1.0 200 OK" in health_response
health_body = json.loads(health_response.split("\r\n\r\n", 1)[1])
+ assert health_body.pop("maintenance") is False
+ identity = health_body.pop("runtime")
+ assert identity["version"] == cli_commands.__version__
+ assert identity["instance_id"] and identity["run_id"]
assert health_body == {
"status": "ok",
"process": "alive",
@@ -4114,7 +4183,7 @@ def test_gateway_agent_task_owns_initial_mcp_provider_close(
seen["channels_stopped"] = True
class _FakeCronService:
- def __init__(self, _store_path: Path) -> None:
+ def __init__(self, _store_path: Path, *, admission=None) -> None:
self.on_job = None
async def start(self) -> None:
@@ -4251,7 +4320,7 @@ def test_gateway_shutdown_event_exits_forever_runtime_tasks(
await asyncio.wait_for(channel_finished.wait(), timeout=1)
class _FakeCronService:
- def __init__(self, _store_path: Path) -> None:
+ def __init__(self, _store_path: Path, *, admission=None) -> None:
self.on_job = None
async def start(self) -> None:
diff --git a/tests/cli/test_dock.py b/tests/cli/test_dock.py
new file mode 100644
index 000000000..1b26ff3fa
--- /dev/null
+++ b/tests/cli/test_dock.py
@@ -0,0 +1,333 @@
+"""The Dock shortcut never owns gateway execution, data, or credentials on disk."""
+
+import asyncio
+import os
+import socket
+import sys
+import tempfile
+import threading
+from contextlib import contextmanager
+from pathlib import Path
+
+import pytest
+
+from nanobot.cli import dock
+from nanobot.cli._macos_dock import _Clients, _serve, is_local_browser_url
+
+
[email protected]("platform", ["linux", "win32"])
+def test_other_platforms_do_not_prepare_or_launch_an_icon(monkeypatch, tmp_path, platform):
+ monkeypatch.setattr(dock.sys, "platform", platform)
+ monkeypatch.setattr(dock, "_attach", lambda *_: pytest.fail("must not launch"))
+ with dock.dock_icon("http://127.0.0.1:8765/", instance=tmp_path / "gateway.json"):
+ pass
+ assert list(tmp_path.iterdir()) == []
+
+
+def test_explicit_opt_out_and_ssh_do_not_launch(monkeypatch, tmp_path):
+ monkeypatch.setattr(dock.sys, "platform", "darwin")
+ monkeypatch.setattr(dock, "_attach", lambda *_: pytest.fail("must not launch"))
+ with dock.dock_icon("http://127.0.0.1:8765/", instance=tmp_path, enabled=False):
+ pass
+ monkeypatch.setenv("SSH_CONNECTION", "test")
+ with dock.dock_icon("http://127.0.0.1:8765/", instance=tmp_path):
+ pass
+
+
+def test_optional_failure_does_not_swallow_webui_failure_or_log_credentials(monkeypatch, tmp_path):
+ warnings = []
+ monkeypatch.setattr(dock, "_desktop_available", lambda: True)
+ monkeypatch.setattr(dock, "_directory", lambda *_: tmp_path)
+ monkeypatch.setattr(dock.logger, "warning", warnings.append)
+
+ def unavailable(*_):
+ raise OSError("sensitive-url-fragment")
+
+ monkeypatch.setattr(dock, "_attach", unavailable)
+ with pytest.raises(RuntimeError, match="gateway failure"):
+ with dock.dock_icon("http://127.0.0.1:8765/", instance=tmp_path):
+ raise RuntimeError("gateway failure")
+ assert len(warnings) == 1
+ assert "sensitive" not in warnings[0]
+
+
+def test_context_releases_its_connection_even_when_the_launcher_is_interrupted(monkeypatch, tmp_path):
+ first, other = socket.socketpair()
+ monkeypatch.setattr(dock, "_desktop_available", lambda: True)
+ monkeypatch.setattr(dock, "_directory", lambda *_: tmp_path)
+ monkeypatch.setattr(dock, "_attach", lambda *_: first)
+ with other, pytest.raises(KeyboardInterrupt):
+ try:
+ with dock.dock_icon("http://127.0.0.1:8765/", instance=tmp_path):
+ raise KeyboardInterrupt
+ finally:
+ other.settimeout(1)
+ assert other.recv(1) == b""
+
+
[email protected](sys.platform == "win32", reason="Darwin/Unix helper startup contract")
+def test_interrupt_during_handshake_closes_connection_and_stops_new_helper(monkeypatch):
+ from unittest.mock import MagicMock
+
+ connection = MagicMock()
+ connection.recv.side_effect = KeyboardInterrupt
+ process = MagicMock()
+ process.poll.return_value = None
+ attempts = iter((None, connection))
+ monkeypatch.setattr(dock, "_connect", lambda *_: next(attempts))
+ monkeypatch.setattr(dock, "_bundle", lambda *_: Path("unused-test-interpreter"))
+ monkeypatch.setattr(dock.subprocess, "Popen", lambda *_args, **_kwargs: process)
+ with tempfile.TemporaryDirectory(prefix="nb-dock-") as name, pytest.raises(KeyboardInterrupt):
+ dock._attach(Path(name), "http://127.0.0.1:8765/")
+ connection.close.assert_called_once()
+ process.terminate.assert_called_once()
+
+
[email protected](sys.platform == "win32", reason="Darwin/Unix helper startup contract")
+def test_cold_helper_startup_keeps_the_connection_until_ready(monkeypatch, tmp_path):
+ # Native AppKit startup was measured at 1.928s after an update, already at
+ # the old 2s socket deadline. Exercise a cold start without requiring a GUI.
+ helper = tmp_path / "slow-helper.py"
+ helper.write_text("""import socket, sys, time
+listener = socket.socket(fileno=int(sys.argv[1]))
+time.sleep(2.5)
+connection, _ = listener.accept()
+with connection:
+ assert connection.recv(8192).endswith(b'\\n')
+ connection.sendall(b'1')
+ assert connection.recv(1) == b''
+listener.close()
+""")
+ spawned = []
+ popen = dock.subprocess.Popen
+
+ def launch(*args, **kwargs):
+ process = popen(*args, **kwargs)
+ spawned.append(process)
+ return process
+
+ monkeypatch.setattr(dock, "_WORKER", helper)
+ monkeypatch.setattr(dock, "_bundle", lambda _: Path(sys.executable))
+ monkeypatch.setattr(dock.subprocess, "Popen", launch)
+ with tempfile.TemporaryDirectory(prefix="nb-dock-") as name:
+ try:
+ connection = dock._attach(Path(name), "http://127.0.0.1:8765/")
+ connection.close()
+ assert spawned[0].wait(timeout=3) == 0
+ finally:
+ for process in spawned:
+ if process.poll() is None:
+ process.terminate()
+ process.wait(timeout=3)
+
+
[email protected](sys.platform == "win32", reason="macOS private-directory contract")
+def test_private_cache_rejects_symlink_and_shared_directory(tmp_path):
+ shared = tmp_path / "shared"
+ shared.mkdir(mode=0o755)
+ shared.chmod(0o755)
+ with pytest.raises(PermissionError):
+ dock._private_directory(shared)
+ private = tmp_path / "private"
+ dock._private_directory(private)
+ link = tmp_path / "link"
+ link.symlink_to(private, target_is_directory=True)
+ with pytest.raises(PermissionError):
+ dock._private_directory(link)
+
+
[email protected]("url, valid", [
+ ("http://127.0.0.1:8765/#/?bootstrapSecret=test", True),
+ ("http://localhost:8765/", True),
+ ("http://[::1]:5173/", True),
+ ("http://example.com:8765/", False),
+ ("http://127.0.0.1.example.com:8765/", False),
+ ("http://user:[email protected]:8765/", False),
+ ("file:///tmp/index.html", False),
+ ("http://127.0.0.1:8765/\n", False),
+ ("http://127.0.0.1:99999/", False),
+])
+def test_private_socket_only_accepts_local_browser_urls(url, valid):
+ assert is_local_browser_url(url) is valid
+
+
+@contextmanager
+def _server():
+ # macOS has a short AF_UNIX address limit; pytest's nested tmp_path can exceed it.
+ with tempfile.TemporaryDirectory(prefix="nb-dock-") as name:
+ address = Path(name) / "s"
+ listener = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+ listener.bind(str(address))
+ listener.listen()
+ clients = _Clients()
+ stopped = threading.Event()
+ # Keep startup serialized just like the launcher: first connect before release.
+ from filelock import FileLock
+ with FileLock(str(address.parent / "start.lock")):
+ thread = threading.Thread(target=_serve, args=(listener, address, clients, stopped.set))
+ thread.start()
+ first = _join(address, "http://127.0.0.1:8765/#/first")
+ try:
+ yield address, first, clients, stopped
+ finally:
+ first.close()
+ assert stopped.wait(3)
+ thread.join(timeout=1)
+
+
+def _join(address, url):
+ connection = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+ connection.settimeout(2)
+ connection.connect(str(address))
+ connection.sendall(url.encode() + b"\n")
+ assert connection.recv(1) == b"1"
+ return connection
+
+
[email protected](sys.platform == "win32", reason="Darwin/Unix socket lifetime contract")
+def test_shared_icon_survives_first_launcher_and_stops_after_last():
+ with _server() as (address, first, clients, stopped):
+ second = _join(address, "http://127.0.0.1:8765/#/second")
+ try:
+ assert clients.current_url().endswith("/second")
+ first.close()
+ assert not stopped.wait(0.15)
+ assert address.exists()
+ finally:
+ second.close()
+ assert stopped.wait(3)
+ assert not address.exists()
+ assert clients.current_url() is None
+
+
[email protected](sys.platform == "win32", reason="Darwin/Unix socket lifetime contract")
+def test_rejected_peer_does_not_replace_live_url_or_stop_the_icon():
+ with _server() as (address, first, clients, stopped):
+ with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as invalid:
+ invalid.settimeout(2)
+ invalid.connect(str(address))
+ invalid.sendall(b"https://example.com/\n")
+ assert invalid.recv(1) == b""
+ assert clients.current_url().endswith("/first")
+ assert not stopped.is_set()
+ first.close()
+
+
[email protected](sys.platform == "win32", reason="Darwin/Unix socket lifetime contract")
+def test_new_launcher_can_join_while_the_previous_launcher_exits():
+ from filelock import FileLock
+
+ with _server() as (address, first, _clients, stopped):
+ with FileLock(str(address.parent / "start.lock")):
+ first.close()
+ assert not stopped.wait(0.15)
+ second = _join(address, "http://127.0.0.1:8765/#/next")
+ try:
+ assert not stopped.wait(0.15)
+ finally:
+ second.close()
+
+
[email protected](sys.platform == "win32", reason="macOS interpreter wrapper")
+def test_bundle_uses_current_python_and_never_contains_the_login_url(tmp_path):
+ import plistlib
+
+ executable = dock._bundle(tmp_path)
+ assert executable.is_symlink()
+ assert os.readlink(executable) == sys.executable
+ info = plistlib.loads((executable.parent.parent / "Info.plist").read_bytes())
+ assert info["CFBundleDisplayName"] == "nanobot"
+ assert (executable.parent.parent / "Resources" / "dock-icon.png").read_bytes() == dock._ICON.read_bytes()
+ assert len([path for path in tmp_path.rglob("*") if path.is_file()]) == 3
+
+
+async def test_background_presence_waits_for_activation_and_remembers_explicit_requests(monkeypatch, tmp_path):
+ monkeypatch.setattr(dock, "_desktop_available", lambda: True)
+ instance = tmp_path / "run" / "gateway.json"
+ entered, closed = threading.Event(), threading.Event()
+
+ @contextmanager
+ def icon(url, **_kwargs):
+ assert url == "http://127.0.0.1:8765/"
+ entered.set()
+ try:
+ yield
+ finally:
+ closed.set()
+
+ monkeypatch.setattr(dock, "dock_icon", icon)
+ dock.request_gateway_icon(instance, enabled=True)
+ intent = instance.with_suffix(".dock").read_text()
+ assert intent.startswith("show:") and "http" not in intent
+ activated = asyncio.Event()
+ watcher = asyncio.create_task(dock.watch_gateway_icon(
+ "http://127.0.0.1:8765/", instance=instance, activated=activated,
+ ))
+ try:
+ await asyncio.sleep(0)
+ assert not entered.is_set()
+ activated.set()
+ assert await asyncio.to_thread(entered.wait, 2)
+ dock.request_gateway_icon(instance, enabled=False)
+ assert await asyncio.to_thread(closed.wait, 2)
+ entered.clear()
+ closed.clear()
+ dock.request_gateway_icon(instance, enabled=True)
+ assert await asyncio.to_thread(entered.wait, 2)
+ finally:
+ watcher.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await watcher
+ assert closed.is_set()
+ # A new gateway generation, including a protected update restart, reads the
+ # same intent without rewriting configuration or learning an updater protocol.
+ entered.clear()
+ watcher = asyncio.create_task(dock.watch_gateway_icon(
+ "http://127.0.0.1:8765/", instance=instance, activated=activated,
+ ))
+ try:
+ assert await asyncio.to_thread(entered.wait, 2)
+ finally:
+ watcher.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await watcher
+
+
+async def test_cancelled_gateway_joins_pending_dock_startup_before_releasing_it(monkeypatch, tmp_path):
+ monkeypatch.setattr(dock, "_desktop_available", lambda: True)
+ started, release, closed = threading.Event(), threading.Event(), threading.Event()
+
+ @contextmanager
+ def slow_icon(*_args, **_kwargs):
+ started.set()
+ assert release.wait(3)
+ try:
+ yield
+ finally:
+ closed.set()
+
+ monkeypatch.setattr(dock, "dock_icon", slow_icon)
+ instance = tmp_path / "gateway.json"
+ dock.request_gateway_icon(instance, enabled=True)
+ activated = asyncio.Event()
+ activated.set()
+ watcher = asyncio.create_task(dock.watch_gateway_icon(
+ "http://127.0.0.1:8765/", instance=instance, activated=activated,
+ ))
+ try:
+ assert await asyncio.to_thread(started.wait, 2)
+ watcher.cancel()
+ await asyncio.sleep(0)
+ assert not watcher.done()
+ finally:
+ release.set()
+ with pytest.raises(asyncio.CancelledError):
+ await watcher
+ assert closed.is_set()
+
+
+def test_background_preference_failure_never_blocks_the_launcher(monkeypatch, tmp_path):
+ monkeypatch.setattr(dock, "_desktop_available", lambda: True)
+ not_directory = tmp_path / "file"
+ not_directory.write_text("test")
+ dock.request_gateway_icon(not_directory / "gateway.json", enabled=True)
diff --git a/tests/cli/test_entry.py b/tests/cli/test_entry.py
index 8c923cfc1..9d3a5a0d3 100644
--- a/tests/cli/test_entry.py
+++ b/tests/cli/test_entry.py
@@ -7,6 +7,7 @@ import pytest
from nanobot.cli import entry
from nanobot.cli.entry import _agent_invocation_args, _native_tui_candidate
+from nanobot.installation_lock import InstallationBusyError, installation_access, installation_id
def test_root_command_routes_to_agent_without_copying_agent_options() -> None:
@@ -70,7 +71,7 @@ def test_root_alias_dispatches_the_shared_agent_command(monkeypatch) -> None:
"set_cli_process_identity",
lambda args: calls.__setitem__("identity", args),
)
- monkeypatch.setattr(entry, "_configure_windows_console", lambda: None)
+ monkeypatch.setattr(entry, "configure_windows_console", lambda: None)
monkeypatch.setattr(
entry,
"_run_agent",
@@ -91,7 +92,7 @@ def test_desktop_handled_bare_invocation_does_not_start_python(monkeypatch) -> N
monkeypatch.setattr(entry.sys, "argv", ["nanobot"])
monkeypatch.setattr(entry, "set_cli_process_identity", lambda _args: None)
- monkeypatch.setattr(entry, "_configure_windows_console", lambda: None)
+ monkeypatch.setattr(entry, "configure_windows_console", lambda: None)
monkeypatch.setattr(desktop_target, "dispatch_bare_desktop_target", lambda _args: 0)
monkeypatch.setattr(
entry,
@@ -114,3 +115,69 @@ def test_classic_and_one_shot_agent_invocations_keep_the_full_cli_entrypoint() -
assert not _native_tui_candidate(["agent", "-mhello"])
assert not _native_tui_candidate(["agent", "--message=hello"])
assert not _native_tui_candidate(["status"])
+
+
+def test_entry_refuses_dispatch_during_update(tmp_path, monkeypatch, capsys):
+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path))
+ monkeypatch.setattr(sys, "prefix", str(tmp_path / "environment"))
+ monkeypatch.setattr(sys, "argv", ["nanobot", "gateway"])
+ monkeypatch.setattr(entry, "_dispatch", lambda: pytest.fail("Runtime dispatched during update"))
+ with installation_access(updating=True):
+ with pytest.raises(SystemExit) as result:
+ entry.main()
+ assert result.value.code == 1
+ assert "being updated" in capsys.readouterr().err
+
+
[email protected]("args", [["update"], ["--home", "/test", "update"], ["--home=/test", "update"]])
+def test_update_command_can_reach_its_own_lease_and_recovery(tmp_path, monkeypatch, args):
+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path))
+ monkeypatch.setattr(sys, "prefix", str(tmp_path / "environment"))
+ monkeypatch.setattr(sys, "argv", ["nanobot", *args])
+ called = []
+ monkeypatch.setattr(entry, "_dispatch", lambda: called.append(True))
+ with installation_access(updating=True):
+ entry.main()
+ assert called == [True]
+
+
[email protected]("args", [["update", "--job", "saved-id"],
+ ["--home=/test", "update", "--job=saved-id", "--retry-handoff"]])
+def test_saved_update_recovery_owns_runtime_before_application_imports(tmp_path, monkeypatch, args):
+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path))
+ monkeypatch.setattr(sys, "prefix", str(tmp_path / "environment"))
+ monkeypatch.setattr(sys, "argv", ["nanobot", *args])
+ entered = []
+
+ def dispatch():
+ with pytest.raises(InstallationBusyError):
+ with installation_access(updating=True):
+ pytest.fail("Recovery imported without a runtime lease")
+ entered.append(True)
+
+ monkeypatch.setattr(entry, "_dispatch", dispatch)
+ entry.main()
+ assert entered == [True]
+ with installation_access(updating=True):
+ with pytest.raises(SystemExit):
+ entry.main()
+ assert entered == [True]
+
+
[email protected]("action,allowed", [("stop", True), ("status", True), ("logs", True), ("restart", False)])
+def test_interrupted_installation_keeps_stop_commands_usable(tmp_path, monkeypatch, action, allowed):
+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path))
+ monkeypatch.setattr(sys, "prefix", str(tmp_path / "environment"))
+ pending = tmp_path / ".nanobot/run" / f"update-{installation_id()[:16]}.pending"
+ pending.parent.mkdir(parents=True)
+ pending.write_text("incomplete")
+ monkeypatch.setattr(sys, "argv", ["nanobot", "--home", str(tmp_path / "profile"), "gateway", action])
+ called = []
+ monkeypatch.setattr(entry, "_dispatch", lambda: called.append(True))
+ if allowed:
+ entry.main()
+ assert called == [True]
+ else:
+ with pytest.raises(SystemExit):
+ entry.main()
+ assert not called
diff --git a/tests/cli/test_gateway_commands.py b/tests/cli/test_gateway_commands.py
index 2c2d71294..2c02c605d 100644
--- a/tests/cli/test_gateway_commands.py
+++ b/tests/cli/test_gateway_commands.py
@@ -139,6 +139,7 @@ def _test_app(
config: Config,
*,
port: int | None = None,
+ verbose: bool = False,
webui_bundle_mode: str | None = None,
unconfigured_provider_error: str | None = None,
gateway_instance: GatewayInstance | None = None,
diff --git a/tests/cli/test_tui_launcher.py b/tests/cli/test_tui_launcher.py
index 409998608..e1f8eeaea 100644
--- a/tests/cli/test_tui_launcher.py
+++ b/tests/cli/test_tui_launcher.py
@@ -356,13 +356,16 @@ def test_source_checkout_does_not_fall_back_to_a_release_tui_without_bun(
"nanobot.cli.tui_launcher._source_checkout_tui_dir",
lambda: source_dir,
)
- monkeypatch.setattr("nanobot.cli.tui_launcher.shutil.which", lambda _name: None)
+ def unavailable():
+ raise tui_launcher.BunUnavailableError("Bun download failed")
+
+ monkeypatch.setattr(tui_launcher, "ensure_bun", unavailable)
monkeypatch.setattr(
"nanobot.cli.tui_launcher._download_release_tui",
lambda _asset: pytest.fail("a source checkout must not download a release TUI"),
)
- with pytest.raises(TuiUnavailableError, match="source checkout requires Bun"):
+ with pytest.raises(TuiUnavailableError, match="Bun download failed"):
resolve_tui_command()
@@ -539,6 +542,7 @@ def test_source_checkout_refreshes_locked_tui_dependencies(
source_dir.mkdir()
(source_dir / "node_modules" / "@opentui" / "core").mkdir(parents=True)
bun = str(tmp_path / "bun")
+ Path(bun).write_bytes(b"runtime")
def install(command: list[str], **kwargs: object) -> subprocess.CompletedProcess[str]:
assert command == [bun, "install", "--frozen-lockfile"]
@@ -563,13 +567,15 @@ def test_source_checkout_fails_when_locked_dependencies_cannot_be_refreshed(
) -> None:
source_dir = tmp_path / "tui"
source_dir.mkdir()
+ bun = tmp_path / "bun"
+ bun.write_bytes(b"runtime")
monkeypatch.setattr(
"nanobot.cli.tui_launcher.subprocess.run",
lambda *args, **kwargs: subprocess.CompletedProcess(args, 1, "", "lockfile mismatch"),
)
with pytest.raises(TuiUnavailableError, match="lockfile mismatch"):
- _resolve_source_tui_command(source_dir, "bun")
+ _resolve_source_tui_command(source_dir, str(bun))
def test_release_tui_is_verified_and_cached(
diff --git a/tests/cli/test_tui_wheels.py b/tests/cli/test_tui_wheels.py
index 78e886400..f5980fa97 100644
--- a/tests/cli/test_tui_wheels.py
+++ b/tests/cli/test_tui_wheels.py
@@ -7,6 +7,7 @@ import json
import runpy
import stat
import struct
+import subprocess
import tarfile
import tomllib
import zipfile
@@ -17,6 +18,13 @@ import pytest
from nanobot.cli import tui_launcher
from scripts import build_tui_wheels as packager
+from scripts import release_candidate
+from scripts.release_candidate import (
+ retain_candidate,
+ verify_candidate,
+ write_install_guide,
+ write_manifest,
+)
@pytest.fixture
@@ -186,3 +194,186 @@ def test_installed_tui_never_downloads_or_requires_bun(tmp_path, monkeypatch, sy
cache = tmp_path / "empty-cache"
assert tui_launcher.resolve_tui_command(data_dir=cache) == [str(binary)]
assert not cache.exists()
+
+
+def complete_candidate(tmp_path, candidate):
+ """Actual checkout payload, with synthetic native binaries (not native execution)."""
+ from hatch_build import WebUIBuildHook
+
+ root = tmp_path / "checkout"
+ subprocess.run(["git", "clone", "--shared", str(packager.ROOT), str(root)],
+ check=True, capture_output=True)
+ commit = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=root, text=True).strip()
+ metadata = tomllib.loads((root / "pyproject.toml").read_text())["project"]
+ wheel, info = candidate
+ with zipfile.ZipFile(wheel) as archive:
+ files = {name: archive.read(name) for name in archive.namelist()}
+ tracked = subprocess.check_output(["git", "ls-files", "-z", "--", "nanobot"], cwd=root).decode().split("\0")
+ for name in filter(None, tracked):
+ parts = name.split("/")
+ if len(parts) > 3 and parts[1] == "channels" and parts[3] == "tests":
+ continue
+ files[name] = (root / name).read_bytes()
+ hook = WebUIBuildHook(str(root), {}, None, {}, "", "wheel",
+ SimpleNamespace(display_info=lambda message: None))
+ hook.initialize("editable", {})
+ references = root / "nanobot/skills/nanobot-document/references"
+ documentation = {}
+ for reference in references.rglob("*.md"):
+ files[reference.relative_to(root).as_posix()] = reference.read_bytes()
+ name = "docs/" + reference.relative_to(references).as_posix()
+ documentation[name] = (root / name).read_bytes()
+ files[f"{info}/METADATA"] += f'Requires-Python: {metadata["requires-python"]}\n'.encode()
+ files["nanobot/_build_commit.txt"] = f"{commit}\n".encode()
+ files["nanobot/web/dist/index.html"] = b"<html>compiled fixture</html>"
+ record = io.StringIO()
+ writer = csv.writer(record)
+ for name, content in files.items():
+ if not name.endswith("/RECORD"):
+ writer.writerow((name, packager._digest(content), len(content)))
+ writer.writerow((f"{info}/RECORD", "", ""))
+ files[f"{info}/RECORD"] = record.getvalue().encode()
+ with zipfile.ZipFile(wheel, "w") as archive:
+ for name, content in files.items():
+ archive.writestr(name, content)
+ artifacts = tmp_path / "artifacts"
+ artifacts.mkdir()
+ for target in packager.PLATFORMS:
+ make_bundle(artifacts, target)
+ packager.build_wheel(wheel, artifacts, artifacts, target, root=root)
+ version = metadata["version"]
+ source_files = {
+ "PKG-INFO": files[f"{info}/METADATA"],
+ "pyproject.toml": (root / "pyproject.toml").read_bytes(),
+ **documentation,
+ **{name: data for name, data in files.items() if name.startswith("nanobot/")},
+ }
+ with tarfile.open(artifacts / f"nanobot_ai-{version}.tar.gz", "w:gz") as archive:
+ for name, data in source_files.items():
+ member = tarfile.TarInfo(f"nanobot_ai-{version}/{name}")
+ member.size = len(data)
+ archive.addfile(member, io.BytesIO(data))
+ return root, commit, artifacts
+
+
+def test_complete_manifest_binds_wheels_sdist_and_fallback_archives(tmp_path, complete_candidate):
+ """Real archive/RECORD checks, with synthetic binaries (not native execution)."""
+ root, commit, artifacts = complete_candidate
+ manifest = verify_candidate(root, artifacts, source_commit=commit)
+ assert len(manifest.artifacts) == 16
+ assert manifest.candidate_commit == commit
+ output = artifacts / "release-manifest.json"
+ write_manifest(manifest, output)
+ original = output.read_bytes()
+ write_manifest(verify_candidate(root, artifacts, source_commit=commit), output)
+ assert output.read_bytes() == original
+ with pytest.raises(FileExistsError):
+ write_manifest(manifest.model_copy(update={"source_commit": "f" * 40}), output)
+ guide = tmp_path / "install.md"
+ write_install_guide(root, artifacts, guide, source_commit=commit)
+ original_guide = guide.read_bytes()
+ write_install_guide(root, artifacts, guide, source_commit=commit)
+ assert guide.read_bytes() == original_guide
+ assert commit.encode() in original_guide
+ assert len(list(artifacts.iterdir())) == 17 # 16 artifacts and the manifest, no guide.
+ with pytest.raises(ValueError, match="outside"):
+ write_install_guide(root, artifacts, artifacts / "install.md", source_commit=commit)
+ guide.write_text("previous reviewed handoff\n")
+ with pytest.raises(FileExistsError, match="overwrite"):
+ write_install_guide(root, artifacts, guide, source_commit=commit)
+ assert guide.read_text() == "previous reviewed handoff\n"
+ recorded = json.loads(original)
+ recorded["artifacts"][0]["sha256"] = "f" * 64
+ output.write_text(json.dumps(recorded))
+ with pytest.raises(ValueError, match="recorded release manifest"):
+ write_install_guide(root, artifacts, tmp_path / "unverified.md", source_commit=commit)
+ assert not (tmp_path / "unverified.md").exists()
+ output.write_bytes(original)
+ damaged = artifacts / "nanobot-tui-linux-x64.zip.sha256"
+ damaged.write_text("0" * 64 + " nanobot-tui-linux-x64.zip\n")
+ with pytest.raises(ValueError, match="checksum mismatch"):
+ verify_candidate(root, artifacts, source_commit=commit)
+ with pytest.raises(ValueError, match="checksum mismatch"):
+ write_install_guide(root, artifacts, tmp_path / "damaged.md", source_commit=commit)
+ assert not (tmp_path / "damaged.md").exists()
+
+
+def test_retained_candidate_keeps_checked_bytes_and_independent_source(tmp_path, complete_candidate):
+ root, commit, artifacts = complete_candidate
+ manifest = verify_candidate(root, artifacts, source_commit=commit)
+ write_manifest(manifest, artifacts / "release-manifest.json")
+ (root / "private-untracked.txt").write_text("not release input")
+ output = tmp_path / "retained"
+ retain_candidate(root, artifacts, output, source_commit=commit)
+ identity = json.loads((output / "handoff.json").read_text())
+ assert identity["candidate_commit"] == commit and identity["published"] is False
+ assert identity["manifest_sha256"] == hashlib.sha256((artifacts / "release-manifest.json").read_bytes()).hexdigest()
+ assert verify_candidate(root, output / "artifacts", source_commit=commit) == manifest
+ for original in artifacts.iterdir():
+ assert (output / "artifacts" / original.name).read_bytes() == original.read_bytes()
+ independent = tmp_path / "independent"
+ subprocess.run(["git", "clone", "--no-local", str(output / "source.git"), str(independent)],
+ check=True, capture_output=True)
+ assert subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=independent, text=True).strip() == commit
+ assert not (independent / "private-untracked.txt").exists()
+ assert not (output / "source.git/objects/info/alternates").exists()
+ assert str(root) not in (output / "source.git/config").read_text()
+ assert verify_candidate(independent, output / "artifacts", source_commit=commit) == manifest
+ with pytest.raises(FileExistsError):
+ retain_candidate(root, artifacts, output, source_commit=commit)
+
+
+def test_interrupted_retention_has_no_accepted_handoff(tmp_path, complete_candidate, monkeypatch):
+ root, commit, artifacts = complete_candidate
+ write_manifest(verify_candidate(root, artifacts, source_commit=commit), artifacts / "release-manifest.json")
+
+ def interrupted_copy(source, target):
+ raise OSError("controlled interrupted copy")
+
+ monkeypatch.setattr(release_candidate.shutil, "copyfile", interrupted_copy)
+ output = tmp_path / "interrupted"
+ with pytest.raises(OSError, match="interrupted copy"):
+ retain_candidate(root, artifacts, output, source_commit=commit)
+ assert not (output / "handoff.json").exists()
+
+
[email protected]("mutation", ["wheel-code", "wheel-webui", "source-code", "source-missing", "source-extra"])
+def test_complete_candidate_rejects_mixed_or_incomplete_application_payload(tmp_path, complete_candidate, mutation):
+ root, commit, artifacts = complete_candidate
+ # These are intact archives with valid versions/commit markers and RECORDs.
+ # A stale intermediate or a stray local file can still be packaged correctly.
+ if mutation.startswith("wheel-"):
+ wheel = next(artifacts.glob("*-macosx_13_0_arm64.whl"))
+ with zipfile.ZipFile(wheel) as archive:
+ entries = archive.infolist()
+ files = {entry.filename: archive.read(entry) for entry in entries}
+ name = "nanobot/__init__.py" if mutation == "wheel-code" else "nanobot/web/dist/index.html"
+ files[name] += b"\n# stale build\n"
+ record_name = next(name for name in files if name.endswith(".dist-info/RECORD"))
+ record = io.StringIO()
+ writer = csv.writer(record)
+ for name, data in files.items():
+ writer.writerow((name, "", "") if name == record_name else (name, packager._digest(data), len(data)))
+ files[record_name] = record.getvalue().encode()
+ with zipfile.ZipFile(wheel, "w") as archive:
+ for entry in entries:
+ archive.writestr(entry, files[entry.filename])
+ else:
+ source = next(artifacts.glob("nanobot_ai-*.tar.gz"))
+ files = packager.source_files(source.read_bytes())
+ module = next(name for name in files if name.endswith("/nanobot/agent/loop.py"))
+ if mutation == "source-code":
+ files[module] += b"\n# stale build\n"
+ elif mutation == "source-missing":
+ del files[module]
+ else:
+ files[module.split("/", 1)[0] + "/nanobot/local-settings.json"] = b'{"local": true}'
+ with tarfile.open(source, "w:gz") as archive:
+ for name, data in files.items():
+ member = tarfile.TarInfo(name)
+ member.size = len(data)
+ archive.addfile(member, io.BytesIO(data))
+ with pytest.raises(ValueError, match="application payload"):
+ verify_candidate(root, artifacts, source_commit=commit)
+ assert not (artifacts / "release-manifest.json").exists()
diff --git a/tests/cli/test_wsl_browser.py b/tests/cli/test_wsl_browser.py
index 8dc0c0494..0dedbaac3 100644
--- a/tests/cli/test_wsl_browser.py
+++ b/tests/cli/test_wsl_browser.py
@@ -71,11 +71,12 @@ Test-Trace 'PowerShell started'
result = subprocess.run(
["powershell.exe", "-NoProfile", "-NonInteractive", "-STA", "-EncodedCommand",
base64.b64encode(script.encode("utf-16-le")).decode("ascii")],
- input=base64.b64encode(content) + b"\n", capture_output=True, timeout=15,
+ # Cold C# compilation on a Windows runner is not the acknowledgement deadline.
+ input=base64.b64encode(content) + b"\n", capture_output=True, timeout=60,
)
except subprocess.TimeoutExpired as exc:
stages = (exc.stderr or b"").decode("utf-8", errors="replace")
- pytest.fail(f"Windows handoff exceeded 15s. Native stages:\n{stages}", pytrace=False)
+ pytest.fail(f"Windows handoff exceeded 60s. Native stages:\n{stages}", pytrace=False)
assert result.returncode == (0 if opens else 1), result.stderr
assert result.stdout == b"private;" + (b"1" if opens else b"") + b"removed=True"
diff --git a/tests/cron/test_cron_persistence.py b/tests/cron/test_cron_persistence.py
index 2c8cd6874..56628fcdf 100644
--- a/tests/cron/test_cron_persistence.py
+++ b/tests/cron/test_cron_persistence.py
@@ -201,7 +201,8 @@ def test_atomic_write_ignores_unsupported_directory_fsync(
dir_fd = 987654
def fake_open(path: str, flags: int) -> int:
- assert Path(path) == store_path.parent
+ # Windows I/O uses an extended path to this same directory.
+ assert Path(path).samefile(store_path.parent)
return dir_fd
def fake_fsync(fd: int) -> None:
diff --git a/tests/fixtures/sigstore/LICENSE b/tests/fixtures/sigstore/LICENSE
new file mode 100644
index 000000000..d64569567
--- /dev/null
+++ b/tests/fixtures/sigstore/LICENSE
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/tests/fixtures/sigstore/README.md b/tests/fixtures/sigstore/README.md
new file mode 100644
index 000000000..7d6abca75
--- /dev/null
+++ b/tests/fixtures/sigstore/README.md
@@ -0,0 +1,13 @@
+# Public verification fixture
+
+`bundle_v3.txt` and `bundle_v3.txt.sigstore` are copied, without modification, from
+the Sigstore project's Apache-2.0-licensed public test assets at commit
+`7ee385ac8be192771bff1cc553434b11282ecce6`:
+https://github.com/sigstore/sigstore-python/tree/7ee385ac8be192771bff1cc553434b11282ecce6/test/assets
+
+Copyright The Sigstore Authors. Licensed under the Apache License, Version 2.0:
+https://www.apache.org/licenses/LICENSE-2.0
+
+These use Sigstore's staging root and contain a public artifact, public certificate and transparency proof, not
+a private key or token. They prove cryptographic validation and rejection of a
+valid but unauthorized publisher. They are **not** nanobot release approvals.
diff --git a/tests/fixtures/sigstore/bundle_v3.txt b/tests/fixtures/sigstore/bundle_v3.txt
new file mode 100644
index 000000000..f1d260a0f
--- /dev/null
+++ b/tests/fixtures/sigstore/bundle_v3.txt
@@ -0,0 +1,5 @@
+DO NOT MODIFY ME!
+
+this is the input for bundle_v3, which tests support for "v3" bundles.
+
+DO NOT MODIFY ME!
diff --git a/tests/fixtures/sigstore/bundle_v3.txt.sigstore b/tests/fixtures/sigstore/bundle_v3.txt.sigstore
new file mode 100644
index 000000000..1e3838481
--- /dev/null
+++ b/tests/fixtures/sigstore/bundle_v3.txt.sigstore
@@ -0,0 +1,53 @@
+{
+ "mediaType": "application/vnd.dev.sigstore.bundle.v0.3+json",
+ "verificationMaterial": {
+ "certificate": {
+ "rawBytes": "MIIC1DCCAlqgAwIBAgIUO3tlVbLtvLPp+6zGOtep1SPkRigwCgYIKoZIzj0EAwMwNzEVMBMGA1UEChMMc2lnc3RvcmUuZGV2MR4wHAYDVQQDExVzaWdzdG9yZS1pbnRlcm1lZGlhdGUwHhcNMjQwNDAyMTkxOTA5WhcNMjQwNDAyMTkyOTA5WjAAMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAENdrfpgNU1Rjmz+j65rpJWKc08ruKYy4FX7nmmOnbauFZimsQXrdyDSXKNRtEXX4X3t/Amt+euwPDBh+eq7BCnqOCAXkwggF1MA4GA1UdDwEB/wQEAwIHgDATBgNVHSUEDDAKBggrBgEFBQcDAzAdBgNVHQ4EFgQUGRlBhD0wvzAfLb2dMWOgPrrJuRkwHwYDVR0jBBgwFoAUcYYwphR8Ym/599b0BRp/X//rb6wwIwYDVR0RAQH/BBkwF4EVd2lsbGlhbUB5b3NzYXJpYW4ubmV0MCwGCisGAQQBg78wAQEEHmh0dHBzOi8vZ2l0aHViLmNvbS9sb2dpbi9vYXV0aDAuBgorBgEEAYO/MAEIBCAMHmh0dHBzOi8vZ2l0aHViLmNvbS9sb2dpbi9vYXV0aDCBigYKKwYBBAHWeQIEAgR8BHoAeAB2ACswvNxoiMni4dgmKV50H0g5MZYC8pwzy15DQP6yrIZ6AAABjqBAQZ4AAAQDAEcwRQIgeWUmtnD0MFUl5kkX7nbMdLWCsDGIPzdIlN+WaZF0TmkCIQC7+31saqrFe9RmduVZ2dxXhUPrajltuSDHb1vSGOcuHjAKBggqhkjOPQQDAwNoADBlAjEAn2+uuLHsnH9Db7zkIdF65YhiXbgMMF//iHc+B/QETK0HYVcOPTK3p46FUzXFD6xrAjAO2hrkfjBKANKjJJxHV3FVrtS+TR0GCP0HzC3D7Br95TXzfO7+j4Dd8/N/aAr6Ibs="
+ },
+ "tlogEntries": [
+ {
+ "logIndex": "25915956",
+ "logId": {
+ "keyId": "0y8wo8MtY5wrdiIFohx7sHeI5oKDpK5vQhGHI6G+pJY="
+ },
+ "kindVersion": {
+ "kind": "hashedrekord",
+ "version": "0.0.1"
+ },
+ "integratedTime": "1712085549",
+ "inclusionPromise": {
+ "signedEntryTimestamp": "MEYCIQD2KXW1NppUhkPPzGR8NrUIyN+MzZSSqGZQO7CzvhSnYgIhAO9AHzjbsr1AHXRHmEpdPZcoFHEwwMTgfqwjoOXVMmqN"
+ },
+ "inclusionProof": {
+ "logIndex": "25901137",
+ "rootHash": "iGAoHccJIyFemFxmEftti2YC8hvPqixBi5y1EyvfF4c=",
+ "treeSize": "25901138",
+ "hashes": [
+ "UHUr+lvxENI+G902oEsFW5ovQILgqO9mUWWxvvwHZZc=",
+ "IcMBsbH3GRW8FX2CiL/ljMb45vzmENmhp5Yp/7IW998=",
+ "SxC6nr0zP+a6kWb6nO2fmEtz8BYAbqEXc+dsqGLdRPM=",
+ "sppZRSz/vdeLlavgvICrXHLeReMTJw98bs9HJ0I8WnE=",
+ "c8lCSuBS6MzrRnt6OiyYjqhTyxUI/22gpVB7dblfDis=",
+ "eJk64J6cMpIljPSX/72kH0kiIeElyypQm5vJ2gMMyHw=",
+ "hbIK+jmAwQjU7Yi3iKvnfR1u7GNippk7QsRwJXIuRaw=",
+ "tpHWIEB2vNU5ZmC68dj1Hh9cwQK083ozogA6zJ3cJ8A=",
+ "arvuzAipUJ14nDj14OBlvkMSicjdsE9Eus3hq9Jpqdk=",
+ "Edul4W41O3EfxKEEMlX2nW0+GTgCv00nGmcpwhALgVA=",
+ "rBWB37+HwkTZgDv0rMtGBUoDI0UZqcgDZp48M6CaUlA="
+ ],
+ "checkpoint": {
+ "envelope": "rekor.sigstage.dev - 8050909264565447525\n25901138\niGAoHccJIyFemFxmEftti2YC8hvPqixBi5y1EyvfF4c=\n\n\u2014 rekor.sigstage.dev 0y8wozBFAiAMJJLbnNOnmizMbVBz9/A/qnMK15BudWoZkuE+obD6CAIhAJf6A3h2iOpuhz/duEhG3fbAQG9PXln4wXPHFBT5wT1a\n"
+ }
+ },
+ "canonicalizedBody": "eyJhcGlWZXJzaW9uIjoiMC4wLjEiLCJraW5kIjoiaGFzaGVkcmVrb3JkIiwic3BlYyI6eyJkYXRhIjp7Imhhc2giOnsiYWxnb3JpdGhtIjoic2hhMjU2IiwidmFsdWUiOiI1ZTZhZTlkZTU4YzExNzdiZWE2MTViNGZjYmZiMmZkNjg4ZThjNGI1MWMyZTU2YjZhMzhlODE3ODMzZWMyNGEyIn19LCJzaWduYXR1cmUiOnsiY29udGVudCI6Ik1FVUNJRFFTSmk5YWVydFFobVQrY2UxaktOZENlNEtTY3NLR3E5ZlBtMzQyMkRCU0FpRUFoajFzeFo5Nm9ySVRzUXh5TUxJRFJKaW1wb3kxSjFNeWZsY1FWd2tremhzPSIsInB1YmxpY0tleSI6eyJjb250ZW50IjoiTFMwdExTMUNSVWRKVGlCRFJWSlVTVVpKUTBGVVJTMHRMUzB0Q2sxSlNVTXhSRU5EUVd4eFowRjNTVUpCWjBsVlR6TjBiRlppVEhSMlRGQndLelo2UjA5MFpYQXhVMUJyVW1sbmQwTm5XVWxMYjFwSmVtb3dSVUYzVFhjS1RucEZWazFDVFVkQk1WVkZRMmhOVFdNeWJHNWpNMUoyWTIxVmRWcEhWakpOVWpSM1NFRlpSRlpSVVVSRmVGWjZZVmRrZW1SSE9YbGFVekZ3WW01U2JBcGpiVEZzV2tkc2FHUkhWWGRJYUdOT1RXcFJkMDVFUVhsTlZHdDRUMVJCTlZkb1kwNU5hbEYzVGtSQmVVMVVhM2xQVkVFMVYycEJRVTFHYTNkRmQxbElDa3R2V2tsNmFqQkRRVkZaU1V0dldrbDZhakJFUVZGalJGRm5RVVZPWkhKbWNHZE9WVEZTYW0xNksybzJOWEp3U2xkTFl6QTRjblZMV1hrMFJsZzNibTBLYlU5dVltRjFSbHBwYlhOUldISmtlVVJUV0V0T1VuUkZXRmcwV0ROMEwwRnRkQ3RsZFhkUVJFSm9LMlZ4TjBKRGJuRlBRMEZZYTNkblowWXhUVUUwUndwQk1WVmtSSGRGUWk5M1VVVkJkMGxJWjBSQlZFSm5UbFpJVTFWRlJFUkJTMEpuWjNKQ1owVkdRbEZqUkVGNlFXUkNaMDVXU0ZFMFJVWm5VVlZIVW14Q0NtaEVNSGQyZWtGbVRHSXlaRTFYVDJkUWNuSktkVkpyZDBoM1dVUldVakJxUWtKbmQwWnZRVlZqV1ZsM2NHaFNPRmx0THpVNU9XSXdRbEp3TDFndkwzSUtZalozZDBsM1dVUldVakJTUVZGSUwwSkNhM2RHTkVWV1pESnNjMkpIYkdoaVZVSTFZak5PZWxsWVNuQlpWelIxWW0xV01FMURkMGREYVhOSFFWRlJRZ3BuTnpoM1FWRkZSVWh0YURCa1NFSjZUMms0ZGxveWJEQmhTRlpwVEcxT2RtSlRPWE5pTW1Sd1ltazVkbGxZVmpCaFJFRjFRbWR2Y2tKblJVVkJXVTh2Q2sxQlJVbENRMEZOU0cxb01HUklRbnBQYVRoMldqSnNNR0ZJVm1sTWJVNTJZbE01YzJJeVpIQmlhVGwyV1ZoV01HRkVRMEpwWjFsTFMzZFpRa0pCU0ZjS1pWRkpSVUZuVWpoQ1NHOUJaVUZDTWtGRGMzZDJUbmh2YVUxdWFUUmtaMjFMVmpVd1NEQm5OVTFhV1VNNGNIZDZlVEUxUkZGUU5ubHlTVm8yUVVGQlFncHFjVUpCVVZvMFFVRkJVVVJCUldOM1VsRkpaMlZYVlcxMGJrUXdUVVpWYkRWcmExZzNibUpOWkV4WFEzTkVSMGxRZW1SSmJFNHJWMkZhUmpCVWJXdERDa2xSUXpjck16RnpZWEZ5Um1VNVVtMWtkVlphTW1SNFdHaFZVSEpoYW14MGRWTkVTR0l4ZGxOSFQyTjFTR3BCUzBKblozRm9hMnBQVUZGUlJFRjNUbThLUVVSQ2JFRnFSVUZ1TWl0MWRVeEljMjVJT1VSaU4zcHJTV1JHTmpWWmFHbFlZbWROVFVZdkwybElZeXRDTDFGRlZFc3dTRmxXWTA5UVZFc3pjRFEyUmdwVmVsaEdSRFo0Y2tGcVFVOHlhSEpyWm1wQ1MwRk9TMnBLU25oSVZqTkdWbkowVXl0VVVqQkhRMUF3U0hwRE0wUTNRbkk1TlZSWWVtWlBOeXRxTkVSa0NqZ3ZUaTloUVhJMlNXSnpQUW90TFMwdExVVk9SQ0JEUlZKVVNVWkpRMEZVUlMwdExTMHRDZz09In19fX0="
+ }
+ ]
+ },
+ "messageSignature": {
+ "messageDigest": {
+ "algorithm": "SHA2_256",
+ "digest": "Xmrp3ljBF3vqYVtPy/sv1ojoxLUcLla2o46BeDPsJKI="
+ },
+ "signature": "MEUCIDQSJi9aertQhmT+ce1jKNdCe4KScsKGq9fPm3422DBSAiEAhj1sxZ96orITsQxyMLIDRJimpoy1J1MyflcQVwkkzhs="
+ }
+}
diff --git a/tests/gateway/test_readiness.py b/tests/gateway/test_readiness.py
new file mode 100644
index 000000000..c2eedc6d1
--- /dev/null
+++ b/tests/gateway/test_readiness.py
@@ -0,0 +1,76 @@
+"""Identity-bound local HTTP readiness; ordinary legacy health remains compatible."""
+
+import json
+import threading
+from dataclasses import asdict, replace
+from http.server import BaseHTTPRequestHandler, HTTPServer
+
+import pytest
+
+from nanobot.gateway.runtime import (
+ GatewayHealthIdentity,
+ GatewayRuntime,
+ GatewayRuntimePaths,
+ GatewayStartOptions,
+ _gateway_health_ready,
+)
+
+
+def health_server():
+ reply = {"status": 200, "body": b'{"status":"ok"}'}
+
+ class Handler(BaseHTTPRequestHandler):
+ def do_GET(self):
+ assert self.path == "/health"
+ self.send_response(reply["status"])
+ self.end_headers()
+ self.wfile.write(reply["body"])
+
+ def log_message(self, *_args):
+ pass
+
+ server = HTTPServer(("127.0.0.1", 0), Handler)
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ try:
+ yield server.server_address[1], reply
+ finally:
+ server.shutdown()
+ server.server_close()
+ thread.join(timeout=5)
+ assert not thread.is_alive()
+
+
+def test_restart_requires_identity_while_legacy_health_still_works(tmp_path, health_server):
+ port, reply = health_server
+ runtime = GatewayRuntime(paths=GatewayRuntimePaths.for_instance(data_dir=tmp_path))
+ identity = GatewayHealthIdentity("a" * 64, "b" * 32, "0.3.6")
+ with runtime.foreground_instance(GatewayStartOptions(port=port)):
+ runtime.publish_health_host("127.0.0.1")
+ assert _gateway_health_ready("127.0.0.1", port)
+ assert not runtime.verify_ready(identity) # Older / unrelated HTTP 200.
+ reply["body"] = json.dumps({
+ "status": "ok", "ready": True,
+ "runtime": {**asdict(identity), "future_optional_field": "ignored"},
+ }).encode()
+ assert runtime.verify_ready(identity)
+ for wrong in (
+ replace(identity, instance_id="c" * 64),
+ replace(identity, run_id="d" * 32),
+ replace(identity, version="0.3.5"),
+ ):
+ assert not runtime.verify_ready(wrong)
+ assert not runtime.verify_ready(identity) # Port alone outlives its owner.
+
+
[email protected]("status,body", [
+ (503, b'{"status":"ok","ready":true}'),
+ (200, b'{"status":"ok","ready":false}'),
+ (200, b'{"status":"ok"}' + b' ' * 4096),
+ (200, b'[]'),
+])
+def test_unready_or_invalid_response_cannot_confirm_restart(health_server, status, body):
+ port, reply = health_server
+ reply.update(status=status, body=body)
+ assert not _gateway_health_ready("127.0.0.1", port, expected=GatewayHealthIdentity("a" * 64, "b" * 32, "0.3.6"))
diff --git a/tests/gateway/test_runtime.py b/tests/gateway/test_runtime.py
index 8db5963ba..d896d5404 100644
--- a/tests/gateway/test_runtime.py
+++ b/tests/gateway/test_runtime.py
@@ -49,6 +49,41 @@ def _paths(tmp_path: Path) -> GatewayRuntimePaths:
return GatewayRuntimePaths.for_instance(data_dir=tmp_path)
+def test_runtime_state_publish_keeps_existing_snapshot_readable(tmp_path):
+ """Status polling must not prevent a gateway from publishing readiness."""
+ from nanobot.utils.atomic_file import _open_snapshot
+
+ runtime = GatewayRuntime(paths=_paths(tmp_path / "网关 home"))
+ previous = {"pid": os.getpid(), "identity": "fixture", "command": ["nanobot", "gateway"]}
+ current = {**previous, "health_host": "127.0.0.1"}
+ runtime._write_state(previous)
+ with _open_snapshot(runtime.paths.state_path) as snapshot:
+ runtime._write_state(current)
+ assert json.loads(snapshot.read()) == previous
+ assert runtime._read_state() == current
+ assert list(runtime.paths.run_dir.glob("*.tmp")) == []
+ if os.name != "nt":
+ assert runtime.paths.state_path.stat().st_mode & 0o777 == 0o600
+
+
+def test_runtime_state_reader_does_not_block_publish_while_decoding(tmp_path, monkeypatch):
+ """Pause a real status read while a readiness update replaces its record."""
+ runtime = GatewayRuntime(paths=_paths(tmp_path))
+ previous = {"pid": os.getpid(), "identity": "fixture"}
+ current = {**previous, "health_host": "127.0.0.1"}
+ runtime._write_state(previous)
+ decode = json.loads
+
+ def publish_during_decode(value, **kwargs):
+ runtime._write_state(current)
+ return decode(value, **kwargs)
+
+ with monkeypatch.context() as patch:
+ patch.setattr("nanobot.process_runtime.json.loads", publish_during_decode)
+ assert runtime._read_state() == previous
+ assert runtime._read_state() == current
+
+
_FOREGROUND_CHILD = r"""
import os
import signal
diff --git a/tests/providers/test_openai_codex_oauth.py b/tests/providers/test_openai_codex_oauth.py
index 07211d2d7..914d7dadf 100644
--- a/tests/providers/test_openai_codex_oauth.py
+++ b/tests/providers/test_openai_codex_oauth.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import threading
import time
from collections.abc import Callable
from types import SimpleNamespace
@@ -43,6 +44,7 @@ def _fake_interactive_login(
provider,
proxy,
open_browser,
+ storage,
) -> OAuthToken:
captured.update(
provider=provider,
@@ -80,6 +82,7 @@ def test_authorization_url_comes_from_oauth_cli_kit() -> None:
assert params["state"]
finally:
flow.cancel()
+ flow.wait_closed()
def test_local_flow_delegates_browser_and_callback_to_public_oauth_cli_kit(
@@ -248,3 +251,41 @@ def test_remote_flow_expires_while_waiting_for_callback(
complete_openai_codex_oauth_login(flow)
finally:
flow.cancel()
+ flow.wait_closed()
+
+
[email protected]("finish", ["cancel", "expiry", "success"])
+def test_worker_exit_and_credential_commit_are_distinct(monkeypatch, tmp_path, finish):
+ entered, release = threading.Event(), threading.Event()
+ target = tmp_path / "oauth.json"
+ monkeypatch.setenv("OAUTH_CLI_KIT_TOKEN_PATH", str(target))
+
+ def login(*, print_fn, storage, **_kwargs):
+ print_fn(_authorization_url())
+ entered.set()
+ assert release.wait(3)
+ token = OAuthToken(access="fixture-access", refresh="fixture-refresh", expires=123)
+ storage.save(token)
+ return token
+
+ monkeypatch.setattr(codex_oauth, "login_oauth_interactive", login)
+ flow = start_openai_codex_oauth_login(timeout_s=5, open_browser=False)
+ try:
+ assert entered.wait(1)
+ assert flow.has_pending_work
+ if finish == "cancel":
+ flow.cancel()
+ elif finish == "expiry":
+ # Advance the shared clock used by both the flow and its save guard.
+ now = time.monotonic() + 10
+ monkeypatch.setattr(codex_oauth, "time", SimpleNamespace(monotonic=lambda: now))
+ assert flow.has_pending_work
+ assert not target.exists()
+ finally:
+ release.set()
+ flow.wait_closed()
+ assert not flow.has_pending_work
+ assert target.exists() is (finish == "success")
+ if finish != "success":
+ with pytest.raises(OpenAICodexOAuthError):
+ flow.complete()
diff --git a/tests/providers/test_xai_oauth.py b/tests/providers/test_xai_oauth.py
index 1da7d4789..ac8605d5f 100644
--- a/tests/providers/test_xai_oauth.py
+++ b/tests/providers/test_xai_oauth.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import asyncio
import json
import queue
import threading
@@ -191,6 +192,50 @@ def test_pending_login_accepts_authorization_code_from_remote_browser(
assert get_xai_oauth_login_status() == token
+async def test_cancel_joins_accepted_callback_request_and_expiry_timer(monkeypatch):
+ entered, release, server_closing = threading.Event(), threading.Event(), threading.Event()
+ monkeypatch.setattr(xai_oauth, "_discover", lambda _: _Discovery(
+ authorization_endpoint="https://auth.x.ai/oauth2/authorize",
+ token_endpoint="https://auth.x.ai/oauth2/token", userinfo_endpoint=None,
+ ))
+ callback_page = xai_oauth._callback_page
+
+ def render_callback(*args):
+ entered.set()
+ assert release.wait(3)
+ return callback_page(*args)
+
+ monkeypatch.setattr(xai_oauth, "_callback_page", render_callback)
+ flow = start_xai_oauth_login(timeout_s=5)
+ server_close = flow._server.server_close
+
+ def observed_close():
+ server_closing.set()
+ server_close()
+
+ monkeypatch.setattr(flow._server, "server_close", observed_close)
+ params = parse_qs(urlsplit(flow.authorization_url).query)
+ request = asyncio.create_task(asyncio.to_thread(httpx.get, flow.redirect_uri, params={
+ "code": "fixture-code", "state": params["state"][0],
+ }, trust_env=False))
+ try:
+ assert await asyncio.to_thread(entered.wait, 1)
+ flow.cancel()
+ closing = asyncio.create_task(asyncio.to_thread(flow.wait_closed))
+ assert await asyncio.to_thread(server_closing.wait, 1)
+ assert flow.has_pending_work
+ assert not closing.done()
+ finally:
+ release.set()
+ flow.cancel()
+ await asyncio.to_thread(flow.wait_closed)
+ response = await request
+ await closing
+ assert response.status_code == 200
+ assert not flow.has_pending_work
+
+
def test_expired_token_refreshes_once_and_persists_rotated_refresh_token(
monkeypatch: pytest.MonkeyPatch,
tmp_path,
diff --git a/tests/test_bun.py b/tests/test_bun.py
new file mode 100644
index 000000000..6741f034f
--- /dev/null
+++ b/tests/test_bun.py
@@ -0,0 +1,78 @@
+import hashlib
+import io
+import os
+import zipfile
+from pathlib import Path
+
+import pytest
+
+from nanobot import bun
+
+
+def test_ensure_bun_reuses_matching_system_runtime(monkeypatch, tmp_path):
+ monkeypatch.setattr(bun.shutil, "which", lambda _: "/bin/bun")
+ monkeypatch.setattr(bun, "_matches_version", lambda _: True)
+ assert bun.ensure_bun(cache_dir=tmp_path / "unused") == "/bin/bun"
+ assert not (tmp_path / "unused").exists()
+
+
+def download(monkeypatch):
+ target = "windows-x64-baseline" if os.name == "nt" else "linux-x64-baseline"
+ name = "bun.exe" if os.name == "nt" else "bun"
+ data = io.BytesIO()
+ with zipfile.ZipFile(data, "w") as archive:
+ archive.writestr(f"bun-{target}/{name}", b"runtime")
+ archive.writestr("../../unwanted", b"do not extract")
+ raw = data.getvalue()
+ calls = []
+
+ def open_url(url, *, timeout):
+ calls.append(url)
+ return io.BytesIO(raw)
+
+ monkeypatch.setattr(bun.shutil, "which", lambda _: None)
+ monkeypatch.setattr(bun, "_target", lambda: target)
+ monkeypatch.setitem(bun._ARCHIVES, target, hashlib.sha256(raw).hexdigest())
+ monkeypatch.setattr(bun.urllib.request, "urlopen", open_url)
+ monkeypatch.setattr(bun, "_matches_version", lambda path: Path(path).read_bytes() == b"runtime")
+ return target, calls
+
+
+def test_bun_download_checks_hash_extracts_only_runtime_and_caches(download, tmp_path):
+ _, calls = download
+ executable = bun.ensure_bun(cache_dir=tmp_path)
+ assert Path(executable).read_bytes() == b"runtime"
+ assert not list(tmp_path.rglob("unwanted"))
+ assert bun.ensure_bun(cache_dir=tmp_path) == executable
+ assert len(calls) == 1
+ assert calls[0].startswith("https://github.com/oven-sh/bun/releases/download/bun-v")
+
+
+def test_bun_rejects_corrupt_download(download, monkeypatch, tmp_path):
+ target, _ = download
+ monkeypatch.setitem(bun._ARCHIVES, target, "0" * 64)
+ with pytest.raises(bun.BunUnavailableError, match="checksum"):
+ bun.ensure_bun(cache_dir=tmp_path)
+ assert not list(tmp_path.rglob("bun.exe"))
+ assert not list(tmp_path.rglob("bun"))
+
+
+def test_bun_rejects_unrunnable_download(download, monkeypatch, tmp_path):
+ monkeypatch.setattr(bun, "_matches_version", lambda _: False)
+ with pytest.raises(bun.BunUnavailableError, match="cannot run"):
+ bun.ensure_bun(cache_dir=tmp_path)
+ assert not list(tmp_path.rglob(".install-*"))
+
+
+def test_private_bun_path_does_not_modify_parent_environment(monkeypatch, tmp_path):
+ monkeypatch.setenv("PATH", "original")
+ runtime = tmp_path / "bun"
+ runtime.write_bytes(b"runtime")
+ with bun.bun_environment(str(runtime)) as env:
+ alias_dir = Path(env["PATH"].split(os.pathsep)[0])
+ node = alias_dir / ("node.exe" if os.name == "nt" else "node")
+ assert node.read_bytes() == b"runtime"
+ assert env["PATH"].endswith(os.pathsep + "original")
+ assert not alias_dir.exists()
+ assert os.environ["PATH"] == "original"
diff --git a/tests/test_data_access.py b/tests/test_data_access.py
new file mode 100644
index 000000000..d59d98838
--- /dev/null
+++ b/tests/test_data_access.py
@@ -0,0 +1,271 @@
+"""Real shared-data leases across process and installation identities."""
+
+import json
+import os
+import subprocess
+import sys
+from contextlib import ExitStack, contextmanager
+from uuid import uuid4
+
+import pytest
+
+from nanobot.data_access import (
+ DataStartupGrant,
+ data_access,
+ profile_data_access,
+ profile_data_paths,
+)
+from nanobot.installation_lock import InstallationBusyError
+
+_CHILD = """
+import json, os, sys
+from nanobot.data_access import DataStartupGrant, data_access
+sys.prefix = sys.argv[1]
+grant = DataStartupGrant(**json.loads(os.environ['TEST_DATA_GRANT'])) if 'TEST_DATA_GRANT' in os.environ else None
+with data_access(sys.argv[4:], updating=sys.argv[2] == 'update', job_id=sys.argv[3] or None, grant=grant) as lease:
+ if sys.argv[3] and sys.argv[2] == 'update':
+ lease.reserve()
+ print('ready', flush=True)
+ sys.stdin.read(1)
+"""
+
+
+def private_home(tmp_path, monkeypatch):
+ home = tmp_path / "private home"
+ home.mkdir()
+ monkeypatch.setenv("HOME", str(home))
+ monkeypatch.setenv("USERPROFILE", str(home))
+ return home
+
+
+@contextmanager
+def process_access(environment, paths, *, updating=False, job_id=None, grant=None):
+ env = os.environ.copy()
+ if grant is not None:
+ env["TEST_DATA_GRANT"] = json.dumps({"job_id": grant.job_id, "participant": grant.participant, "token": grant.token})
+ process = subprocess.Popen(
+ [sys.executable, "-c", _CHILD, str(environment), "update" if updating else "runtime", job_id or "", *map(str, paths)],
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, env=env,
+ )
+ try:
+ assert process.stdout.readline().strip() == "ready", process.stderr.read()
+ yield process
+ finally:
+ if process.poll() is None:
+ process.stdin.write("x")
+ process.stdin.flush()
+ process.communicate(timeout=10)
+
+
+def crash_process(process):
+ # Windows venv python.exe redirects to a child interpreter. Killing only
+ # that launcher leaves the actual lease holder alive until stdin closes.
+ if os.name == "nt":
+ subprocess.run(["taskkill", "/PID", str(process.pid), "/T", "/F"],
+ check=True, capture_output=True, timeout=10)
+ else:
+ process.kill()
+ process.wait(timeout=10)
+
+
+def test_shared_data_blocks_update_across_installations_until_last_writer_exits(private_home, tmp_path):
+ store = tmp_path / "shared sessions"
+ with process_access(tmp_path / "first environment", [store]) as first:
+ with process_access(tmp_path / "second environment", [store]):
+ with data_access([store]):
+ pass # Normal runtime sharing remains allowed.
+ crash_process(first)
+ with pytest.raises(InstallationBusyError, match="data is in use"):
+ with data_access([store], updating=True):
+ pytest.fail("The other installation's writer was ignored")
+ with data_access([store], updating=True):
+ pass
+
+
[email protected]("held_parent", [False, True])
+def test_overlapping_roots_block_but_siblings_remain_usable(private_home, tmp_path, held_parent):
+ parent = tmp_path / "sessions"
+ child = parent / "chat.jsonl"
+ held, requested = (parent, child) if held_parent else (child, parent)
+ with process_access(tmp_path / "another environment", [held], updating=True):
+ with pytest.raises(InstallationBusyError):
+ with data_access([requested]):
+ pytest.fail("An ancestor/descendant path bypassed maintenance")
+ with data_access([tmp_path / "separate sessions"]):
+ pass
+
+
+def test_alias_and_partial_acquisition_do_not_bypass_or_leak_leases(private_home, tmp_path):
+ store, available = tmp_path / "z-store", tmp_path / "a-store"
+ store.mkdir()
+ alias = tmp_path / "alias"
+ try:
+ alias.symlink_to(store, target_is_directory=True)
+ except OSError:
+ pytest.skip("Directory symlinks are not enabled for this account")
+ with process_access(tmp_path / "other environment", [alias]) as writer:
+ with pytest.raises(InstallationBusyError):
+ with data_access([available, store], updating=True):
+ pytest.fail("A symlink alias bypassed the writer lease")
+ with data_access([available]):
+ pass # Failed multi-store acquisition released its earlier leases.
+ crash_process(writer)
+ with data_access([store], updating=True):
+ pass
+
+
+def test_job_reservation_survives_process_exit_until_same_scope_is_recovered(private_home, tmp_path):
+ store, sibling = tmp_path / "sessions", tmp_path / "unrelated sessions"
+ job_id = str(uuid4())
+ with process_access(tmp_path / "update environment", [store], updating=True, job_id=job_id) as worker:
+ crash_process(worker)
+ # No process holds the leases now. The durable reservation still excludes
+ # overlapping readers/writers from other installations, but not unrelated data.
+ for path in (store, store / "chat.jsonl", store.parent):
+ with pytest.raises(InstallationBusyError, match="reserved"):
+ with data_access([path]):
+ pytest.fail("A runtime entered an interrupted maintenance scope")
+ with data_access([sibling]):
+ pass
+ with pytest.raises(InstallationBusyError, match="unfinished update"):
+ with data_access([store], updating=True, job_id=str(uuid4())):
+ pytest.fail("Another job took over the interrupted update")
+ with pytest.raises(InstallationBusyError, match="unfinished update"):
+ with data_access([sibling], updating=True, job_id=job_id):
+ pytest.fail("The same ID changed the approved data scope")
+ with data_access([store], updating=True, job_id=job_id) as recovered:
+ recovered.release_reservation()
+ with data_access([store]):
+ pass
+
+
[email protected]("legacy", [False, True])
+def test_profile_handoff_keeps_delivery_leased_without_expanding_old_grant(private_home, tmp_path, legacy):
+ selectors = dict(home=private_home, data_dir=tmp_path / "data",
+ config=tmp_path / "data/config.json", workspace=tmp_path / "workspace")
+ delivery = selectors["data_dir"] / "delivery"
+ scope = tuple(path for path in profile_data_paths(**selectors) if not legacy or path != delivery)
+ job_id, participant = str(uuid4()), "a" * 64
+ with data_access(scope, updating=True, job_id=job_id) as owner:
+ owner.reserve()
+ with ExitStack() as runtime:
+ with data_access(scope, job_id=job_id) as owner:
+ grant = owner.grant_startup(participant, scope)
+ runtime.enter_context(profile_data_access(**selectors, grant=grant))
+ # The old reservation is not enlarged to authorize initialization.
+ saved = json.loads(owner.reservation_path.read_text())
+ assert saved["grants"][participant]["roots"] == sorted(str(path.resolve()).casefold() for path in scope)
+ assert not delivery.exists()
+ owner.release_reservation()
+ # Once handoff ends, the running profile still owns the new store lease.
+ with pytest.raises(InstallationBusyError, match="data is in use"):
+ with data_access((delivery,), updating=True):
+ pytest.fail("A delivery store writer escaped the runtime lease")
+ with data_access((delivery,), updating=True):
+ pass
+
+
+def test_profile_handoff_cannot_defer_an_existing_store(private_home, tmp_path):
+ selectors = dict(home=private_home, data_dir=tmp_path / "data",
+ config=tmp_path / "data/config.json", workspace=tmp_path / "workspace")
+ scope = tuple(path for path in profile_data_paths(**selectors)
+ if path not in {selectors["data_dir"] / "delivery", selectors["data_dir"] / "auth"})
+ job_id = str(uuid4())
+ with data_access(scope, updating=True, job_id=job_id) as owner:
+ owner.reserve()
+ with data_access(scope, job_id=job_id) as handoff:
+ with pytest.raises(ValueError, match="exceeds the reviewed data scope"):
+ handoff.grant_profile_startup("a" * 64, **selectors)
+
+
+def test_verified_handoff_admits_only_granted_scope_until_explicit_completion(private_home, tmp_path):
+ store = tmp_path / "sessions"
+ runtime_scope = [store / "profile"]
+ job_id, participant = str(uuid4()), "a" * 64
+ with data_access([store], updating=True, job_id=job_id) as owner:
+ owner.reserve()
+ with data_access([store], job_id=job_id) as handoff:
+ grant = handoff.grant_startup(participant, runtime_scope)
+ assert grant.token not in handoff.reservation_path.read_text()
+ assert grant.token not in repr(grant)
+ with pytest.raises(ValueError, match="exceeds"):
+ handoff.grant_startup("b" * 64, [store.parent])
+ with pytest.raises(InstallationBusyError, match="scope"):
+ with data_access([store], grant=grant):
+ pytest.fail("A participant expanded its allowed data roots")
+ invalid = DataStartupGrant(job_id, participant, "0" * 64)
+ with pytest.raises(InstallationBusyError, match="scope"):
+ with data_access(runtime_scope, grant=invalid):
+ pytest.fail("A job ID and participant name bypassed the grant")
+ with process_access(tmp_path / "target environment", runtime_scope, grant=grant):
+ with pytest.raises(InstallationBusyError):
+ with data_access(runtime_scope, grant=grant):
+ pytest.fail("Two processes claimed one startup participant")
+ with pytest.raises(InstallationBusyError, match="still running"):
+ handoff.grant_startup(participant, runtime_scope)
+ with pytest.raises(InstallationBusyError, match="reserved"):
+ with data_access(runtime_scope):
+ pytest.fail("An ordinary startup entered maintenance")
+ # Only the lifecycle owner calls this after verifying the runtime;
+ # participant leases are shared, so completion does not deadlock.
+ handoff.release_reservation()
+ with data_access(runtime_scope):
+ pass
+ with pytest.raises(InstallationBusyError, match="no longer reserved"):
+ with data_access(runtime_scope, grant=grant):
+ pytest.fail("A completed startup grant was replayed")
+
+
+def test_crashed_handoff_keeps_fence_and_child_lease_until_recovery(private_home, tmp_path):
+ store = tmp_path / "sessions"
+ job_id, participant = str(uuid4()), "c" * 64
+ with data_access([store], updating=True, job_id=job_id) as owner:
+ owner.reserve()
+ coordinator = subprocess.Popen([
+ sys.executable, "-c", """
+import json, sys
+from dataclasses import asdict
+from nanobot.data_access import data_access
+with data_access([sys.argv[1]], job_id=sys.argv[2]) as handoff:
+ grant = handoff.grant_startup(sys.argv[3], [sys.argv[1]])
+ print(json.dumps(asdict(grant)), flush=True)
+ sys.stdin.read(1)
+""", str(store), job_id, participant,
+ ], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
+ try:
+ encoded = coordinator.stdout.readline()
+ assert encoded, coordinator.stderr.read()
+ grant = DataStartupGrant(**json.loads(encoded))
+ with process_access(tmp_path / "target environment", [store], grant=grant) as child:
+ crash_process(coordinator)
+ # The coordinator's OS leases are gone, but the child owns its own.
+ with pytest.raises(InstallationBusyError):
+ with data_access([store], updating=True, job_id=job_id):
+ pytest.fail("Repair raced an orphan startup still using data")
+ with pytest.raises(InstallationBusyError, match="reserved"):
+ with data_access([store]):
+ pytest.fail("Coordinator exit incorrectly lifted maintenance")
+ crash_process(child)
+ finally:
+ if coordinator.poll() is None:
+ crash_process(coordinator)
+ coordinator.communicate(timeout=10)
+ with data_access([store], job_id=job_id) as recovered:
+ replacement = recovered.grant_startup(participant, [store])
+ with pytest.raises(InstallationBusyError, match="scope"):
+ with data_access([store], grant=grant):
+ pytest.fail("An obsolete grant survived explicit reauthorization")
+ with data_access([store], grant=replacement) as startup:
+ with pytest.raises(ValueError, match="Only an update job"):
+ startup.release_reservation()
+ with pytest.raises(ValueError, match="Only an update job"):
+ startup.reserve()
+ # Exiting the recovered handoff still does not mean verification passed.
+ with data_access([store], updating=True, job_id=job_id) as repair:
+ repair.reserve() # New package mutation revokes all startup grants.
+ with pytest.raises(InstallationBusyError, match="scope"):
+ with data_access([store], grant=replacement):
+ pytest.fail("A grant from before repair authorized a new startup")
+ with data_access([store], updating=True, job_id=job_id) as repair:
+ repair.release_reservation()
diff --git a/tests/test_install_scripts.py b/tests/test_install_scripts.py
new file mode 100644
index 000000000..36face203
--- /dev/null
+++ b/tests/test_install_scripts.py
@@ -0,0 +1,834 @@
+"""Exercise the public installers against real, offline package managers.
+
+The tiny wheel reports its runtime identity; it is not the nanobot application.
+No gateway, model, user configuration or public package index is used by these tests.
+"""
+
+import base64
+import hashlib
+import io
+import json
+import os
+import platform
+import re
+import shlex
+import shutil
+import ssl
+import subprocess
+import sys
+import sysconfig
+import threading
+import tomllib
+import urllib.request
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from pathlib import Path
+from zipfile import ZipFile
+
+import pytest
+from packaging.tags import sys_tags
+
+from nanobot import releases
+from scripts.release_install_guide import (
+ bootstrap_commands,
+ install_command,
+ render_install_command,
+ verification_command,
+)
+
+SCRIPTS = Path(__file__).resolve().parents[1] / "scripts"
+WINDOWS = os.name == "nt"
+BASE_PYTHON = sys._base_executable
+
+
+def _wheel(directory, version, *, platform="any", package="nanobot-ai", extras=(), installer_receipt=False):
+ module = package.replace("-", "_") if package != "nanobot-ai" else "nanobot"
+ wheel_name = package.replace("-", "_")
+ metadata = f"{wheel_name}-{version}.dist-info"
+ files = {
+ "nanobot/__init__.py": f'__version__ = "{version}"\n',
+ "nanobot/__main__.py": """
+import json
+import sys
+import nanobot
+
+def main():
+ print("INSTALLER_PROBE " + json.dumps({
+ "version": nanobot.__version__, "package": nanobot.__file__,
+ "python": sys.executable, "prefix": sys.prefix,
+ "isolated": sys.flags.isolated, "args": sys.argv[1:],
+ }))
+
+if __name__ == "__main__":
+ main()
+""",
+ f"{metadata}/METADATA": f"Metadata-Version: 2.1\nName: nanobot-ai\nVersion: {version}\nRequires-Python: >=3.11\n",
+ f"{metadata}/WHEEL": "Wheel-Version: 1.0\nGenerator: installer-test\nRoot-Is-Purelib: true\nTag: py3-none-any\n",
+ f"{metadata}/entry_points.txt": "[console_scripts]\nnanobot = nanobot.__main__:main\n",
+ }
+ files = {name.replace("nanobot/", f"{module}/"): content for name, content in files.items()}
+ files[f"{module}/__main__.py"] = files[f"{module}/__main__.py"].replace("nanobot", module)
+ files[f"{metadata}/METADATA"] = files[f"{metadata}/METADATA"].replace("Name: nanobot-ai", f"Name: {package}")
+ files[f"{metadata}/METADATA"] += "".join(f"Provides-Extra: {extra}\n" for extra in extras)
+ files[f"{metadata}/WHEEL"] = files[f"{metadata}/WHEEL"].replace("py3-none-any", f"py3-none-{platform}")
+ files[f"{metadata}/entry_points.txt"] = f"[console_scripts]\n{module} = {module}.__main__:main\n"
+ if installer_receipt:
+ files["nanobot/installation_receipt.py"] = (SCRIPTS.parent / "nanobot/installation_receipt.py").read_text()
+ files["nanobot/utils/__init__.py"] = ""
+ files["nanobot/utils/atomic_file.py"] = (SCRIPTS.parent / "nanobot/utils/atomic_file.py").read_text()
+ record = []
+ path = directory / f"{wheel_name}-{version}-py3-none-{platform}.whl"
+ with ZipFile(path, "w") as wheel:
+ for name, content in files.items():
+ data = content.encode()
+ wheel.writestr(name, data)
+ digest = base64.urlsafe_b64encode(hashlib.sha256(data).digest()).rstrip(b"=").decode()
+ record.append(f"{name},sha256={digest},{len(data)}\n")
+ wheel.writestr(f"{metadata}/RECORD", "".join(record) + f"{metadata}/RECORD,,\n")
+ return path
+
+
+def _python(environment):
+ return environment / ("Scripts/python.exe" if WINDOWS else "bin/python")
+
+
+def _run(command, sandbox, *, check=True):
+ result = subprocess.run(command, cwd=sandbox["cwd"], env=sandbox["env"],
+ capture_output=True, text=True, encoding="utf-8", timeout=90)
+ if check:
+ assert result.returncode == 0, result.stdout + result.stderr
+ return result
+
+
+def _installer(sandbox, *args, check=True):
+ if WINDOWS:
+ shell = shutil.which("powershell")
+ if not shell:
+ pytest.skip("Windows PowerShell is required")
+ command = [shell, "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass",
+ "-File", str(SCRIPTS / "install.ps1")]
+ else:
+ command = ["/bin/sh", str(SCRIPTS / "install.sh")]
+ return _run([*command, *args], sandbox, check=check)
+
+
+def _identity(result):
+ reports = [json.loads(line.removeprefix("INSTALLER_PROBE "))
+ for line in result.stdout.splitlines() if line.startswith("INSTALLER_PROBE ")]
+ assert len(reports) == 1, result.stdout
+ return reports[0]
+
+
+def _expose(sandbox, name):
+ # Explicit overrides let local verification use disposable manager installations.
+ source = os.environ.get(f"NANOBOT_TEST_{name.upper()}") or shutil.which(name)
+ if not source:
+ pytest.skip(f"{name} is required for this real installer check")
+ destination = sandbox["bin"] / (f"{name}.exe" if WINDOWS else name)
+ if WINDOWS:
+ shutil.copy2(source, destination)
+ else:
+ destination.symlink_to(source)
+ return str(destination)
+
+
+def sandbox(tmp_path):
+ root = tmp_path.resolve() / "user's 数据 $safe"
+ root.mkdir()
+ command_bin = root / "commands"
+ command_bin.mkdir()
+ wheels = root / "wheels"
+ wheels.mkdir()
+ # A checkout and PYTHONPATH must not replace the package just installed.
+ checkout = root / "checkout"
+ (checkout / "nanobot").mkdir(parents=True)
+ (checkout / "nanobot/__init__.py").write_text('raise RuntimeError("wrong checkout imported")\n')
+ env = {key: value for key, value in os.environ.items()
+ if key.upper() in {"SYSTEMROOT", "WINDIR", "COMSPEC", "PATHEXT"}}
+ system_path = (str(Path(env["SYSTEMROOT"]) / "System32") if WINDOWS else "/usr/bin:/bin")
+ env.update({
+ "HOME": str(root), "USERPROFILE": str(root),
+ "PATH": str(command_bin) + os.pathsep + system_path,
+ "PYTHON": BASE_PYTHON, "PYTHONPATH": str(checkout), "PYTHONUTF8": "1",
+ "NANOBOT_SKIP_WIZARD": "1", "NANOBOT_VENV": str(root / "managed"),
+ "NANOBOT_BIN_DIR": str(root / "launchers"),
+ "XDG_CONFIG_HOME": str(root / "config"), "XDG_CACHE_HOME": str(root / "cache"),
+ "XDG_DATA_HOME": str(root / "data"), "APPDATA": str(root / "config"),
+ "LOCALAPPDATA": str(root / "data"), "TMPDIR": str(root), "TMP": str(root), "TEMP": str(root),
+ "UV_TOOL_DIR": str(root / "uv-tools"), "UV_TOOL_BIN_DIR": str(root / "uv-bin"),
+ "UV_CACHE_DIR": str(root / "uv-cache"), "UV_NO_CONFIG": "1", "UV_NO_INDEX": "1",
+ "UV_OFFLINE": "1", "UV_PYTHON_DOWNLOADS": "never", "UV_FIND_LINKS": wheels.as_uri(),
+ "PIPX_HOME": str(root / "pipx"), "PIPX_BIN_DIR": str(root / "pipx-bin"),
+ "PIPX_MAN_DIR": str(root / "man"), "PIPX_DEFAULT_BACKEND": "pip",
+ "PIPX_DISABLE_SHARED_LIBS_AUTO_UPGRADE": "1", "PIPX_DEFAULT_PYTHON": BASE_PYTHON,
+ "PIP_CONFIG_FILE": os.devnull, "PIP_NO_INDEX": "1", "PIP_FIND_LINKS": wheels.as_uri(),
+ "PIP_DISABLE_PIP_VERSION_CHECK": "1", "PIP_NO_INPUT": "1",
+ })
+ return {"root": root, "bin": command_bin, "wheels": wheels, "cwd": checkout, "env": env}
+
+
[email protected]("manager", ["uv", "pipx"])
+def test_installer_starts_and_upgrades_same_persistent_manager_environment(sandbox, manager):
+ executable = _expose(sandbox, manager)
+ _wheel(sandbox["wheels"], "0.0.1")
+ _run([executable, *(["tool"] if manager == "uv" else []), "install", "--python", BASE_PYTHON, "nanobot-ai"], sandbox)
+ prefix = (sandbox["root"] / "uv-tools/nanobot-ai" if manager == "uv"
+ else sandbox["root"] / "pipx/venvs/nanobot-ai")
+ for version in ("0.0.1", "0.0.2"):
+ if version == "0.0.2":
+ _wheel(sandbox["wheels"], version)
+ identity = _identity(_installer(sandbox))
+ assert identity["version"] == version
+ assert Path(identity["prefix"]).resolve() == prefix
+ assert Path(identity["package"]).resolve().is_relative_to(prefix)
+ assert Path(identity["python"]).absolute() == _python(prefix)
+ assert identity["isolated"] == 1
+ assert identity["args"] == ["--version"]
+ assert not (sandbox["root"] / "managed").exists()
+
+
+def test_rerunning_installer_preserves_uv_version_constraint(sandbox):
+ uv = _expose(sandbox, "uv")
+ _wheel(sandbox["wheels"], "0.0.1")
+ _wheel(sandbox["wheels"], "0.0.2")
+ _run([uv, "tool", "install", "--python", BASE_PYTHON, "nanobot-ai==0.0.1"], sandbox)
+ assert _identity(_installer(sandbox))["version"] == "0.0.1"
+ receipt = sandbox["root"] / "uv-tools/nanobot-ai/uv-receipt.toml"
+ assert "==0.0.1" in receipt.read_text(encoding="utf-8")
+
+
[email protected]("exact", [False, True], ids=["registry", "exact-wheel"])
[email protected]("custom", ["constraint", "pip-options"])
+def test_installer_never_discards_pipx_install_policy(sandbox, exact, custom):
+ pipx = _expose(sandbox, "pipx")
+ _wheel(sandbox["wheels"], "0.0.1")
+ requirement = "nanobot-ai>=0.0.1,<0.1" if custom == "constraint" else "nanobot-ai"
+ options = ["--pip-args=--no-deps"] if custom == "pip-options" else []
+ _run([pipx, "install", "--python", BASE_PYTHON, *options, requirement], sandbox)
+ prefix = sandbox["root"] / "pipx/venvs/nanobot-ai"
+ receipt = prefix / "pipx_metadata.json"
+ original = receipt.read_bytes()
+ if exact:
+ _, artifact = _preview_manifest(sandbox)
+ arguments = _wheel_arguments(sandbox, artifact)
+ else:
+ _wheel(sandbox["wheels"], "0.0.2")
+ arguments = []
+ result = _installer(sandbox, *arguments, check=False)
+ assert result.returncode != 0
+ assert "pipx installation settings" in result.stdout + result.stderr
+ assert receipt.read_bytes() == original
+ assert _verify_owner(sandbox, "pipx", prefix)["version"] == "0.0.1"
+ assert not (sandbox["root"] / "managed").exists()
+
+
+def test_fresh_default_records_dedicated_environment_even_with_uv_available(sandbox):
+ _expose(sandbox, "uv")
+ _wheel(sandbox["wheels"], "0.0.1", installer_receipt=True)
+ identity = _identity(_installer(sandbox))
+ prefix = sandbox["root"] / "managed"
+ assert Path(identity["prefix"]).resolve() == prefix
+ receipt = prefix / "nanobot-install.json"
+ original = receipt.read_bytes()
+ assert json.loads(original) == {"schema_version": 1, "owner": "nanobot-installer",
+ "environment": str(prefix), "extras": []}
+ _wheel(sandbox["wheels"], "0.0.2", installer_receipt=True)
+ assert _identity(_installer(sandbox))["version"] == "0.0.2"
+ assert receipt.read_bytes() == original
+ assert not (sandbox["root"] / "uv-tools/nanobot-ai").exists()
+
+
[email protected]("original", ["pipx", "managed"])
+def test_existing_owner_wins_when_uv_is_installed_later(sandbox, original):
+ if original == "pipx":
+ executable = _expose(sandbox, "pipx")
+ _wheel(sandbox["wheels"], "0.0.1")
+ if original == "pipx":
+ _run([executable, "install", "--python", BASE_PYTHON, "nanobot-ai"], sandbox)
+ before = _identity(_installer(sandbox))
+ _expose(sandbox, "uv")
+ _wheel(sandbox["wheels"], "0.0.2")
+ after = _identity(_installer(sandbox))
+ assert after["version"] == "0.0.2"
+ assert after["prefix"] == before["prefix"]
+ assert after["python"] == before["python"]
+ assert not (sandbox["root"] / "uv-tools/nanobot-ai").exists()
+
+
+def test_multiple_existing_installations_need_an_explicit_owner(sandbox):
+ uv, pipx = _expose(sandbox, "uv"), _expose(sandbox, "pipx")
+ _wheel(sandbox["wheels"], "0.0.1")
+ _run([uv, "tool", "install", "--python", BASE_PYTHON, "nanobot-ai"], sandbox)
+ _run([pipx, "install", "--python", BASE_PYTHON, "nanobot-ai"], sandbox)
+ _wheel(sandbox["wheels"], "0.0.2")
+ result = _installer(sandbox, check=False)
+ assert result.returncode != 0
+ assert "Multiple nanobot installations" in result.stdout + result.stderr
+ for prefix in (sandbox["root"] / "uv-tools/nanobot-ai", sandbox["root"] / "pipx/venvs/nanobot-ai"):
+ identity = _identity(_run([str(_python(prefix)), "-I", "-m", "nanobot", "--version"], sandbox))
+ assert identity["version"] == "0.0.1"
+
+
+def test_activated_manager_environment_is_not_updated_with_pip(sandbox):
+ executable = _expose(sandbox, "uv")
+ _wheel(sandbox["wheels"], "0.0.1")
+ _run([executable, "tool", "install", "--python", BASE_PYTHON, "nanobot-ai"], sandbox)
+ before = _identity(_installer(sandbox))
+ sandbox["env"]["PYTHON"] = before["python"]
+ _wheel(sandbox["wheels"], "0.0.2")
+ result = _installer(sandbox, check=False)
+ assert result.returncode != 0
+ assert "active Python belongs to uv or pipx" in result.stdout + result.stderr
+ assert _identity(_run([before["python"], "-I", "-m", "nanobot", "--version"], sandbox))["version"] == "0.0.1"
+
+
[email protected]("active", [True, False], ids=["active-venv", "managed-venv"])
+def test_python_install_uses_same_environment_and_quoted_launcher(sandbox, active):
+ _wheel(sandbox["wheels"], "0.0.1")
+ prefix = sandbox["root"] / ("active" if active else "managed")
+ if active:
+ _run([BASE_PYTHON, "-I", "-m", "venv", str(prefix)], sandbox)
+ sandbox["env"]["PYTHON"] = str(_python(prefix))
+ identity = _identity(_installer(sandbox))
+ assert Path(identity["prefix"]).resolve() == prefix
+ assert identity["isolated"] == 1
+ if not WINDOWS and not active:
+ wrapper = sandbox["root"] / "launchers/nanobot"
+ launched = _identity(_run([str(wrapper), "--version"], sandbox))
+ assert launched == identity
+
+
[email protected]("manager", ["uv", "pipx"])
+def test_failed_default_install_does_not_fall_through_to_available_manager(sandbox, manager):
+ _expose(sandbox, manager)
+ # Offline and no candidate: only the default dedicated environment is tried.
+ result = _installer(sandbox, check=False)
+ assert result.returncode != 0
+ assert (sandbox["root"] / "managed").exists()
+ assert not (sandbox["root"] / "uv-tools/nanobot-ai").exists()
+ assert not (sandbox["root"] / "pipx/venvs/nanobot-ai").exists()
+ assert "INSTALLER_PROBE" not in result.stdout
+ receipt = sandbox["root"] / "managed/nanobot-install.json"
+ selection = receipt.read_bytes()
+ _wheel(sandbox["wheels"], "0.0.1", installer_receipt=True)
+ retried = _identity(_installer(sandbox))
+ assert Path(retried["prefix"]).resolve() == sandbox["root"] / "managed"
+ assert receipt.read_bytes() == selection
+ assert json.loads(selection)["extras"] == []
+ assert not (sandbox["root"] / "uv-tools/nanobot-ai").exists()
+ assert not (sandbox["root"] / "pipx/venvs/nanobot-ai").exists()
+
+
+def test_dry_run_does_not_create_tool_environment(sandbox):
+ _expose(sandbox, "uv")
+ result = _installer(sandbox, "--dry-run")
+ assert "dedicated virtual environment" in result.stdout
+ assert not (sandbox["root"] / "uv-tools").exists()
+ assert "INSTALLER_PROBE" not in result.stdout
+
+
+def _preview_manifest(sandbox, *, damaged_hash=False, extras=()):
+ version = "0.0.2.dev1"
+ platform = next(tag.platform for tag in sys_tags()
+ if tag.platform in releases.PLATFORMS.values())
+ wheel = _wheel(sandbox["cwd"], version, platform=platform, extras=extras)
+ digest = "0" * 64 if damaged_hash else hashlib.sha256(wheel.read_bytes()).hexdigest()
+ artifacts = [releases.ReleaseArtifact(
+ filename=name, size=wheel.stat().st_size if name == wheel.name else 123,
+ sha256=digest if name == wheel.name else "c" * 64,
+ ) for name in sorted(releases.release_filenames(version))]
+ manifest = releases.ReleaseManifest(version=version, source_commit="a" * 40,
+ candidate_commit="b" * 40, requires_python=">=3.11",
+ artifacts=artifacts)
+ return manifest, next(item for item in artifacts if item.filename == wheel.name)
+
+
+def _owner_environment(sandbox, owner, *, existing):
+ _wheel(sandbox["wheels"], "0.0.1")
+ if owner == "pip":
+ prefix = sandbox["root"] / "ordinary-venv"
+ _run([BASE_PYTHON, "-I", "-m", "venv", str(prefix)], sandbox)
+ executable = str(_python(prefix))
+ if existing:
+ _run([executable, "-I", "-m", "pip", "install", "nanobot-ai"], sandbox)
+ else:
+ executable = _expose(sandbox, owner)
+ prefix = sandbox["root"] / ("uv-tools/nanobot-ai" if owner == "uv" else "pipx/venvs/nanobot-ai")
+ sandbox["env"]["UV_PYTHON"] = BASE_PYTHON
+ if existing:
+ _run([executable, *(["tool"] if owner == "uv" else []), "install", "--python", BASE_PYTHON, "nanobot-ai"], sandbox)
+ return executable, prefix
+
+
+def _verify_owner(sandbox, owner, prefix):
+ if owner == "pip":
+ return _identity(_run([str(_python(prefix)), "-I", "-m", "nanobot", "--version"], sandbox))
+ command = verification_command(owner, windows=WINDOWS)
+ shell = ["powershell", "-NoProfile", "-NonInteractive", "-Command"] if WINDOWS else ["/bin/sh", "-c"]
+ return _identity(_run([*shell, command], sandbox))
+
+
+def _run_guide_command(sandbox, command, python, *, check=True):
+ """Run the same multiline command users copy, including shell quoting."""
+ if WINDOWS:
+ value = str(python).replace("'", "''")
+ prelude = f"Set-Alias -Name python -Value '{value}'\n"
+ shell = ["powershell", "-NoProfile", "-NonInteractive", "-Command"]
+ else:
+ prelude = f'python() {{ {shlex.quote(str(python))} "$@"; }}\n'
+ shell = ["/bin/sh", "-c"]
+ return _run([*shell, prelude + render_install_command(command, windows=WINDOWS)], sandbox, check=check)
+
+
[email protected]("owner", ["uv", "pipx", "pip"])
[email protected]("existing", [False, True], ids=["fresh", "existing"])
+def test_generated_exact_preview_commands_use_persistent_owner(sandbox, owner, existing):
+ _, prefix = _owner_environment(sandbox, owner, existing=existing)
+ manifest, artifact = _preview_manifest(sandbox)
+ command = install_command(manifest, artifact, owner=owner, existing=existing)
+ _run_guide_command(sandbox, command, _python(prefix) if owner == "pip" else BASE_PYTHON)
+ identity = _verify_owner(sandbox, owner, prefix)
+ assert identity["version"] == manifest.version
+ assert Path(identity["prefix"]).resolve() == prefix
+ assert Path(identity["package"]).resolve().is_relative_to(prefix)
+ assert identity["isolated"] == 1
+
+
[email protected]("owner", ["uv", "pipx", "pip"])
+def test_generated_command_hash_failure_leaves_existing_version(sandbox, owner):
+ _, prefix = _owner_environment(sandbox, owner, existing=True)
+ manifest, artifact = _preview_manifest(sandbox, damaged_hash=True)
+ command = install_command(manifest, artifact, owner=owner, existing=True)
+ result = _run_guide_command(sandbox, command, _python(prefix) if owner == "pip" else BASE_PYTHON, check=False)
+ assert result.returncode != 0
+ assert "no package manager was started" in result.stderr
+ assert _verify_owner(sandbox, owner, prefix)["version"] == "0.0.1"
+
+
[email protected]("owner", ["uv", "pipx"])
+def test_exact_preview_does_not_silently_remove_manager_pin(sandbox, owner):
+ executable, prefix = _owner_environment(sandbox, owner, existing=False)
+ if owner == "uv":
+ _run([executable, "tool", "install", "nanobot-ai==0.0.1"], sandbox)
+ else:
+ _run([executable, "install", "--skip-maintenance", "nanobot-ai"], sandbox)
+ _run([executable, "pin", "nanobot-ai"], sandbox)
+ manifest, artifact = _preview_manifest(sandbox)
+ command = install_command(manifest, artifact, owner=owner, existing=True)
+ result = _run_guide_command(sandbox, command, BASE_PYTHON, check=False)
+ # uv rejects the constraint conflict; pipx successfully skips a pinned tool.
+ assert (result.returncode == 0) == (owner == "pipx")
+ assert _verify_owner(sandbox, owner, prefix)["version"] == "0.0.1"
+
+
+def test_exact_pipx_target_preserves_injected_package_and_records_new_spec(sandbox):
+ pipx, prefix = _owner_environment(sandbox, "pipx", existing=True)
+ _wheel(sandbox["wheels"], "1.0.0", package="fixture-helper")
+ _run([pipx, "inject", "--skip-maintenance", "nanobot-ai", "fixture-helper"], sandbox)
+ receipt = prefix / "pipx_metadata.json"
+ before = json.loads(receipt.read_text(encoding="utf-8"))
+ manifest, artifact = _preview_manifest(sandbox)
+ command = install_command(manifest, artifact, owner="pipx", existing=True)
+ _run_guide_command(sandbox, command, BASE_PYTHON)
+ after = json.loads(receipt.read_text(encoding="utf-8"))
+ assert after["injected_packages"] == before["injected_packages"]
+ assert after["source_interpreter"] == before["source_interpreter"]
+ assert after["main_package"]["package_or_url"] == f"nanobot-ai @ {(sandbox['cwd'] / artifact.filename).as_uri()}"
+ _run([str(_python(prefix)), "-I", "-c", "import fixture_helper"], sandbox)
+ assert _verify_owner(sandbox, "pipx", prefix)["version"] == manifest.version
+
+
+def _wheel_arguments(sandbox, artifact):
+ return ["-Wheel" if WINDOWS else "--wheel", str(sandbox["cwd"] / artifact.filename),
+ "-Sha256" if WINDOWS else "--sha256", artifact.sha256]
+
+
[email protected]("owner", ["uv", "pipx", "pip", "managed"])
[email protected]("existing", [False, True], ids=["fresh", "existing"])
+def test_public_installer_accepts_verified_exact_preview(sandbox, owner, existing):
+ if owner == "managed":
+ prefix = sandbox["root"] / "managed"
+ if existing:
+ _wheel(sandbox["wheels"], "0.0.1")
+ _installer(sandbox)
+ else:
+ executable, prefix = _owner_environment(sandbox, owner, existing=existing)
+ if owner == "pip":
+ sandbox["env"]["PYTHON"] = executable
+ elif not existing:
+ prefix = sandbox["root"] / "managed"
+ manifest, artifact = _preview_manifest(sandbox)
+ result = _installer(sandbox, *_wheel_arguments(sandbox, artifact))
+ identity = _identity(result)
+ assert identity["version"] == manifest.version
+ assert Path(identity["prefix"]).resolve() == prefix
+ assert Path(identity["python"]).absolute() == _python(prefix)
+ assert (sandbox["cwd"] / artifact.filename).is_file()
+
+
+def test_public_installer_rejects_damaged_wheel_before_environment_creation(sandbox):
+ _expose(sandbox, "uv")
+ _, artifact = _preview_manifest(sandbox, damaged_hash=True)
+ result = _installer(sandbox, *_wheel_arguments(sandbox, artifact), check=False)
+ assert result.returncode != 0
+ assert "SHA-256 mismatch" in result.stdout + result.stderr
+ assert not (sandbox["root"] / "uv-tools/nanobot-ai").exists()
+ assert not (sandbox["root"] / "managed").exists()
+
+
+def test_public_installer_does_not_report_pinned_skip_as_preview_success(sandbox):
+ pipx, prefix = _owner_environment(sandbox, "pipx", existing=True)
+ _run([pipx, "pin", "nanobot-ai"], sandbox)
+ _, artifact = _preview_manifest(sandbox)
+ result = _installer(sandbox, *_wheel_arguments(sandbox, artifact), check=False)
+ assert result.returncode != 0
+ assert "requested version was not installed" in result.stdout + result.stderr
+ assert "INSTALLER_PROBE" not in result.stdout
+ assert _verify_owner(sandbox, "pipx", prefix)["version"] == "0.0.1"
+
+
+def test_public_installer_wheel_dry_run_validates_but_does_not_install(sandbox):
+ _expose(sandbox, "uv")
+ manifest, artifact = _preview_manifest(sandbox)
+ result = _installer(sandbox, "--dry-run", *_wheel_arguments(sandbox, artifact))
+ assert f"verified wheel {manifest.version}" in result.stdout
+ assert not (sandbox["root"] / "uv-tools/nanobot-ai").exists()
+
+
+def test_public_installer_pipx_preview_preserves_requested_extras(sandbox):
+ pipx = _expose(sandbox, "pipx")
+ prefix = sandbox["root"] / "pipx/venvs/nanobot-ai"
+ _wheel(sandbox["wheels"], "0.0.1", extras=("feature",))
+ _run([pipx, "install", "--skip-maintenance", "nanobot-ai[feature]"], sandbox)
+ _, artifact = _preview_manifest(sandbox, extras=("feature",))
+ _installer(sandbox, *_wheel_arguments(sandbox, artifact))
+ record = json.loads((prefix / "pipx_metadata.json").read_text(encoding="utf-8"))
+ assert record["main_package"]["package_or_url"].startswith("nanobot-ai[feature] @ ")
+
+
+def test_public_installer_uv_preview_preserves_requested_extras(sandbox):
+ uv = _expose(sandbox, "uv")
+ prefix = sandbox["root"] / "uv-tools/nanobot-ai"
+ _wheel(sandbox["wheels"], "0.0.1", extras=("feature",))
+ _run([uv, "tool", "install", "--python", BASE_PYTHON, "nanobot-ai[feature]"], sandbox)
+ _, artifact = _preview_manifest(sandbox, extras=("feature",))
+ _installer(sandbox, *_wheel_arguments(sandbox, artifact))
+ record = tomllib.loads((prefix / "uv-receipt.toml").read_text(encoding="utf-8"))
+ assert any(item.get("extras") == ["feature"] for item in record["tool"]["requirements"])
+
+
+def test_public_installer_refuses_missing_previously_requested_pipx_extra(sandbox):
+ pipx = _expose(sandbox, "pipx")
+ prefix = sandbox["root"] / "pipx/venvs/nanobot-ai"
+ _wheel(sandbox["wheels"], "0.0.1", extras=("feature",))
+ _run([pipx, "install", "--skip-maintenance", "nanobot-ai[feature]"], sandbox)
+ _, artifact = _preview_manifest(sandbox)
+ result = _installer(sandbox, *_wheel_arguments(sandbox, artifact), check=False)
+ assert result.returncode != 0
+ assert "does not provide all existing pipx extras" in result.stdout + result.stderr
+ assert _verify_owner(sandbox, "pipx", prefix)["version"] == "0.0.1"
+
+
+def test_public_installer_incomplete_wheel_request_never_falls_back_to_pypi(sandbox):
+ _wheel(sandbox["wheels"], "0.0.1")
+ flag = "-Wheel" if WINDOWS else "--wheel"
+ result = _installer(sandbox, flag, "missing.whl", check=False)
+ assert result.returncode != 0
+ assert "supplied together" in result.stdout + result.stderr
+ assert not (sandbox["root"] / "managed").exists()
+
+
+def test_public_installer_wrong_platform_keeps_original_environment(sandbox):
+ python, prefix = _owner_environment(sandbox, "pip", existing=True)
+ sandbox["env"]["PYTHON"] = python
+ foreign = "macosx_13_0_arm64" if WINDOWS else "win_amd64"
+ wheel = _wheel(sandbox["cwd"], "0.0.2.dev1", platform=foreign)
+ artifact = releases.ReleaseArtifact(filename=wheel.name, size=wheel.stat().st_size,
+ sha256=hashlib.sha256(wheel.read_bytes()).hexdigest())
+ result = _installer(sandbox, *_wheel_arguments(sandbox, artifact), check=False)
+ assert result.returncode != 0
+ assert "retry this exact handoff" in result.stdout + result.stderr
+ assert "uv tool install --force" not in result.stdout + result.stderr
+ assert _verify_owner(sandbox, "pip", prefix)["version"] == "0.0.1"
+
+
+def _bootstrap_program(script):
+ source = (SCRIPTS / script).read_text(encoding="utf-8")
+ if script.endswith(".sh"):
+ match = re.search(r"wheel_identity=[^\n]*<<'PY'\n(.*?)\nPY\n", source, re.S)
+ assert match is not None
+ return match[1]
+ return source.split("$Verify = @'\n", 1)[1].split("\n'@", 1)[0]
+
+
+def published_release(tmp_path, monkeypatch):
+ version = "0.0.2.dev1"
+ base = f"{releases.RELEASE_DOWNLOAD}/v{version}/"
+ payloads = {}
+ artifacts = []
+ for name in sorted(releases.release_filenames(version)):
+ if name.endswith(".whl"):
+ tag = name.removeprefix(f"nanobot_ai-{version}-py3-none-").removesuffix(".whl")
+ body = _wheel(tmp_path, version, platform=tag).read_bytes()
+ else:
+ body = b"not downloaded by the installer"
+ payloads[base + name] = body
+ artifacts.append(releases.ReleaseArtifact(filename=name, size=len(body),
+ sha256=hashlib.sha256(body).hexdigest()))
+ manifest = releases.ReleaseManifest(version=version, source_commit="a" * 40,
+ candidate_commit="b" * 40, requires_python=">=3.11",
+ artifacts=artifacts)
+ payloads[base + "release-manifest.json"] = manifest.model_dump_json().encode()
+ requests = []
+
+ class Opener:
+ def open(self, request, *, timeout):
+ assert timeout == 20
+ requests.append(request.full_url)
+ return io.BytesIO(payloads[request.full_url])
+
+ monkeypatch.setattr(urllib.request, "build_opener", lambda *_: Opener())
+ cache = tmp_path / "download cache 数据"
+
+ def run(script, *, dry_run=False, manifest_hash=None):
+ digest = manifest_hash or hashlib.sha256(payloads[base + "release-manifest.json"]).hexdigest()
+ monkeypatch.setattr(sys, "argv", ["verify", "-", "-", "-", version, digest,
+ str(cache), "1" if dry_run else "0"])
+ namespace = {}
+ try:
+ exec(compile(_bootstrap_program(script), script, "exec"), namespace)
+ except SystemExit as exc:
+ if exc.code != 0:
+ raise
+ return namespace
+
+ return run, manifest, payloads, requests, cache
+
+
[email protected]("script", ["install.sh", "install.ps1"])
[email protected]("system,machine,expected", [
+ ("darwin", "arm64", "macosx_13_0_arm64"),
+ ("darwin", "x86_64", "macosx_13_0_x86_64"),
+ ("linux", "aarch64", "manylinux_2_17_aarch64"),
+ ("linux", "x86_64", "manylinux_2_17_x86_64"),
+ ("win32", "AMD64", "win_amd64"),
+])
+def test_bootstrap_downloads_only_target_wheel(published_release, monkeypatch, capsys, script, system, machine, expected):
+ run, manifest, payloads, requests, cache = published_release
+ monkeypatch.setattr(sys, "platform", system)
+ monkeypatch.setattr(platform, "machine", lambda: machine)
+ monkeypatch.setattr(platform, "mac_ver", lambda: ("15.0", ("", "", ""), machine))
+ monkeypatch.setattr(os, "confstr", lambda _: "glibc 2.17", raising=False)
+ monkeypatch.setattr(sysconfig, "get_platform", lambda: "win-amd64")
+ run(script)
+ filename = f"nanobot_ai-{manifest.version}-py3-none-{expected}.whl"
+ assert len(requests) == 2 and requests[-1].endswith("/" + filename)
+ files = list(cache.rglob("*.whl"))
+ assert len(files) == 1 and files[0].name == filename
+ assert files[0].read_bytes() == payloads[requests[-1]]
+ assert capsys.readouterr().out.strip() == f"nanobot-ai @ {files[0].as_uri()}|{manifest.version}"
+ run(script)
+ assert len(requests) == 3 and requests[-1].endswith("release-manifest.json")
+ assert not list(cache.rglob("*.part"))
+
+
[email protected]("script", ["install.sh", "install.ps1"])
+def test_bootstrap_dry_run_has_no_wheel_or_cache_writes(published_release, capsys, script):
+ run, manifest, _, requests, cache = published_release
+ namespace = run(script, dry_run=True)
+ assert len(requests) == 1 and not cache.exists()
+ assert f"|{manifest.version}" in capsys.readouterr().out
+ assert namespace["native_platform"]() in {tag.platform for tag in sys_tags()}
+
+
[email protected]("script", ["install.sh", "install.ps1"])
+def test_bootstrap_bad_manifest_hash_never_downloads_wheel(published_release, script):
+ run, _, _, requests, cache = published_release
+ with pytest.raises(SystemExit, match="manifest size or SHA-256"):
+ run(script, manifest_hash="0" * 64)
+ assert len(requests) == 1 and not cache.exists()
+
+
[email protected]("script", ["install.sh", "install.ps1"])
+def test_bootstrap_damaged_download_is_not_retained(published_release, script):
+ run, manifest, payloads, requests, cache = published_release
+ for artifact in manifest.artifacts:
+ if artifact.filename.endswith(".whl"):
+ payloads[manifest.artifact_url(artifact).split("#")[0]] = b"truncated"
+ with pytest.raises(SystemExit, match="wheel size or SHA-256"):
+ run(script)
+ assert len(requests) == 2
+ assert not list(cache.rglob("*.whl")) and not list(cache.rglob("*.part"))
+
+
[email protected]("libc", ["", "glibc 2.16"])
+def test_bootstrap_does_not_download_a_glibc_wheel_for_incompatible_linux(published_release, monkeypatch, libc):
+ run, _, _, requests, cache = published_release
+ monkeypatch.setattr(sys, "platform", "linux")
+ monkeypatch.setattr(os, "confstr", lambda _: libc, raising=False)
+ with pytest.raises(SystemExit, match="glibc 2.17"):
+ run("install.sh")
+ assert not requests and not cache.exists()
+
+
[email protected]("url", ["http://github.com/file", "https://example.com/file", "https://github.com:8443/file",
+ "https://user:[email protected]/file", "https://127.0.0.1/file"])
+def test_bootstrap_rejects_download_redirects_outside_project_hosts(published_release, url):
+ run, _, _, _, _ = published_release
+ namespace = run("install.sh", dry_run=True)
+ handler = namespace["ReleaseRedirect"]()
+ with pytest.raises(SystemExit, match="approved HTTPS hosts"):
+ handler.redirect_request(urllib.request.Request("https://github.com/file"), None, 302, "Found", {}, url)
+
+
+def release_https(published_release, tmp_path):
+ """Real HTTPS via a private CONNECT proxy; never contacts GitHub or other hosts."""
+ openssl = shutil.which("openssl")
+ if not openssl:
+ pytest.skip("OpenSSL is required for the isolated HTTPS installer check")
+ cert, key = tmp_path / "test-ca.pem", tmp_path / "test-ca-key.pem"
+ subprocess.run([openssl, "req", "-x509", "-newkey", "rsa:2048", "-nodes",
+ "-keyout", str(key), "-out", str(cert), "-days", "1", "-subj", "/CN=github.com",
+ "-addext", "subjectAltName=DNS:github.com,DNS:raw.githubusercontent.com"], check=True,
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=30)
+ context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
+ context.load_cert_chain(cert, key)
+ _, manifest, payloads, _, _ = published_release
+ requests = []
+
+ class Handler(BaseHTTPRequestHandler):
+ def do_CONNECT(self): # noqa: N802 -- stdlib protocol method
+ if self.path not in {"github.com:443", "raw.githubusercontent.com:443"}:
+ self.send_error(403)
+ return
+ self.send_response(200)
+ self.end_headers()
+ self.connection.settimeout(10)
+ self.connection = context.wrap_socket(self.connection, server_side=True)
+ self.rfile = self.connection.makefile("rb")
+ self.wfile = self.connection.makefile("wb")
+ self.handle_one_request()
+ self.close_connection = True
+
+ def do_GET(self): # noqa: N802 -- stdlib protocol method
+ url = "https://" + self.headers["Host"] + self.path
+ requests.append(url)
+ if url not in payloads:
+ self.send_error(404)
+ return
+ self.send_response(200)
+ self.send_header("Content-Length", str(len(payloads[url])))
+ self.end_headers()
+ self.wfile.write(payloads[url])
+ self.wfile.flush()
+
+ def log_message(self, *args):
+ pass
+
+ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ try:
+ digest = hashlib.sha256(payloads[f"{releases.RELEASE_DOWNLOAD}/v{manifest.version}/release-manifest.json"]).hexdigest()
+ yield manifest, digest, payloads, requests, {
+ "HTTPS_PROXY": f"http://127.0.0.1:{server.server_address[1]}",
+ "SSL_CERT_FILE": str(cert), "NO_PROXY": "",
+ "CURL_CA_BUNDLE": str(cert),
+ }
+ finally:
+ server.shutdown()
+ thread.join(timeout=10)
+ server.server_close()
+
+
+def _release_arguments(version, digest):
+ return ["-Release" if WINDOWS else "--release", version,
+ "-ManifestSha256" if WINDOWS else "--manifest-sha256", digest]
+
+
[email protected]("owner", ["uv", "pipx", "managed"])
[email protected]("existing", [False, True], ids=["fresh", "existing"])
+def test_public_installer_download_to_owner_upgrade_over_https(sandbox, release_https, owner, existing):
+ manifest, digest, _, requests, network = release_https
+ if owner == "managed":
+ prefix = sandbox["root"] / "managed"
+ if existing:
+ _wheel(sandbox["wheels"], "0.0.1")
+ _installer(sandbox)
+ else:
+ _, prefix = _owner_environment(sandbox, owner, existing=existing)
+ if not existing:
+ prefix = sandbox["root"] / "managed"
+ sandbox["env"].update(network)
+ result = _installer(sandbox, *_release_arguments(manifest.version, digest))
+ identity = _identity(result)
+ assert identity["version"] == manifest.version
+ assert Path(identity["prefix"]).resolve() == prefix
+ assert len(requests) == 2
+ cached = list((sandbox["root"] / ".nanobot/downloads/releases").rglob("*.whl"))
+ assert len(cached) == 1 and requests[-1].endswith(cached[0].name)
+
+
+def test_public_installer_release_dry_run_over_https_is_read_only(sandbox, release_https):
+ manifest, digest, _, requests, network = release_https
+ sandbox["env"].update(network)
+ result = _installer(sandbox, "--dry-run", *_release_arguments(manifest.version, digest))
+ assert "its wheel was not downloaded" in result.stdout
+ assert len(requests) == 1
+ assert not (sandbox["root"] / "managed").exists()
+ assert not (sandbox["root"] / ".nanobot/downloads/releases").exists()
+
+
+def test_public_installer_damaged_https_download_never_updates_existing_package(sandbox, release_https):
+ manifest, digest, payloads, requests, network = release_https
+ _, prefix = _owner_environment(sandbox, "uv", existing=True)
+ for artifact in manifest.artifacts:
+ if artifact.filename.endswith(".whl"):
+ payloads[manifest.artifact_url(artifact).split("#")[0]] = b"damaged download"
+ sandbox["env"].update(network)
+ result = _installer(sandbox, *_release_arguments(manifest.version, digest), check=False)
+ assert result.returncode != 0 and "wheel size or SHA-256 mismatch" in result.stdout + result.stderr
+ assert len(requests) == 2
+ assert _verify_owner(sandbox, "uv", prefix)["version"] == "0.0.1"
+ cache = sandbox["root"] / ".nanobot/downloads/releases"
+ assert not list(cache.rglob("*.whl")) and not list(cache.rglob("*.part"))
+
+
[email protected]("owner", ["uv", "pipx"])
+def test_release_bootstrap_preserves_explicit_manager_pin(sandbox, release_https, owner):
+ executable, prefix = _owner_environment(sandbox, owner, existing=False)
+ if owner == "uv":
+ _run([executable, "tool", "install", "nanobot-ai==0.0.1"], sandbox)
+ receipt = prefix / "uv-receipt.toml"
+ else:
+ _run([executable, "install", "--skip-maintenance", "nanobot-ai"], sandbox)
+ _run([executable, "pin", "nanobot-ai"], sandbox)
+ receipt = prefix / "pipx_metadata.json"
+ before = receipt.read_bytes()
+ manifest, digest, _, requests, network = release_https
+ sandbox["env"].update(network)
+ result = _installer(sandbox, *_release_arguments(manifest.version, digest), check=False)
+ assert result.returncode != 0
+ assert "INSTALLER_PROBE" not in result.stdout
+ assert len(requests) == 2 # Pin enforcement follows successful selection/download.
+ assert receipt.read_bytes() == before
+ assert _verify_owner(sandbox, owner, prefix)["version"] == "0.0.1"
+ assert not (sandbox["root"] / "managed").exists()
+
+
[email protected](WINDOWS, reason="Unix bootstrap command; Windows installer is tested separately")
+def test_generated_bootstrap_command_downloads_and_upgrades_original_owner(sandbox, release_https):
+ manifest, digest, payloads, requests, network = release_https
+ _expose(sandbox, "curl")
+ _, prefix = _owner_environment(sandbox, "uv", existing=True)
+ installer_url = f"https://raw.githubusercontent.com/HKUDS/nanobot/{manifest.candidate_commit}/scripts/install.sh"
+ payloads[installer_url] = (SCRIPTS / "install.sh").read_bytes()
+ sandbox["env"].update(network)
+ unix, _ = bootstrap_commands(manifest, digest)
+ identity = _identity(_run(["/bin/sh", "-c", unix], sandbox))
+ assert identity["version"] == manifest.version
+ assert Path(identity["prefix"]).resolve() == prefix
+ assert requests[0] == installer_url and len(requests) == 3
+ assert not list(sandbox["root"].glob("*/install.sh"))
diff --git a/tests/test_installation_lock.py b/tests/test_installation_lock.py
new file mode 100644
index 000000000..149d55698
--- /dev/null
+++ b/tests/test_installation_lock.py
@@ -0,0 +1,135 @@
+"""Real process leases, not PID files or mocked lock acquisition."""
+
+import subprocess
+import sys
+import time
+from contextlib import contextmanager
+from pathlib import Path
+
+import pytest
+
+from nanobot.installation_lock import (
+ InstallationBusyError,
+ installation_access,
+ installation_state_dir,
+)
+
+_CHILD = """
+import os, sys
+from pathlib import Path
+sys.path.insert(0, sys.argv[4])
+from nanobot.installation_lock import installation_access
+Path.home = classmethod(lambda cls: Path(sys.argv[1]))
+sys.prefix = sys.argv[2]
+with installation_access(updating=sys.argv[3] == 'update'):
+ print(os.getpid(), flush=True)
+ sys.stdin.read(1)
+"""
+
+
+@contextmanager
+def child_lease(home: Path, prefix: str, *, updating: bool = False):
+ # Windows venv python.exe is a redirector: killing/waiting for that launcher
+ # does not prove the actual lease holder exited. This stdlib-only probe runs
+ # the base interpreter directly and verifies that it is the process we own.
+ process = subprocess.Popen(
+ [sys._base_executable, "-I", "-S", "-c", _CHILD, str(home), prefix,
+ "update" if updating else "runtime", str(Path(__file__).resolve().parents[1])],
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
+ )
+ try:
+ assert process.stdout.readline().strip() == str(process.pid), process.stderr.read()
+ yield process
+ finally:
+ if process.poll() is None:
+ process.stdin.write("x")
+ process.stdin.flush()
+ process.communicate(timeout=10)
+
+
+def isolated_installation(tmp_path, monkeypatch):
+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path))
+ monkeypatch.setattr(sys, "prefix", str(tmp_path / "installation with spaces"))
+ return tmp_path
+
+
+def assert_update_lease_released():
+ # LockFileEx documents deferred kernel cleanup after process death/close.
+ # Poll the real lock only after the actual owner has exited; never mistake
+ # a launcher exiting for an owner exiting or weaken the live-owner checks.
+ deadline = time.monotonic() + (5 if sys.platform == "win32" else 0)
+ while True:
+ try:
+ with installation_access(updating=True):
+ return
+ except InstallationBusyError:
+ if time.monotonic() >= deadline:
+ raise
+ time.sleep(0.01)
+
+
+def test_multiple_runtimes_block_update_until_last_process_exits(isolated_installation):
+ with child_lease(isolated_installation, sys.prefix) as first:
+ with child_lease(isolated_installation, sys.prefix):
+ with installation_access():
+ pass # Shared leases do not prevent normal multi-profile use.
+ with pytest.raises(InstallationBusyError, match="Stop its nanobot gateways"):
+ with installation_access(updating=True):
+ pytest.fail("Update entered a busy installation")
+ first.kill()
+ first.wait(timeout=10)
+ with pytest.raises(InstallationBusyError):
+ with installation_access(updating=True):
+ pytest.fail("Another live runtime was ignored")
+ assert_update_lease_released()
+
+
+def test_update_blocks_startup_and_concurrent_update_and_crash_releases_lease(isolated_installation):
+ with child_lease(isolated_installation, sys.prefix, updating=True) as worker:
+ with pytest.raises(InstallationBusyError, match="being updated"):
+ with installation_access():
+ pytest.fail("Runtime entered an updating installation")
+ with pytest.raises(InstallationBusyError):
+ with installation_access(updating=True):
+ pytest.fail("Concurrent updater entered")
+ worker.kill()
+ worker.wait(timeout=10)
+ assert_update_lease_released()
+
+
+def test_other_installation_does_not_block_runtime(isolated_installation):
+ with child_lease(isolated_installation, sys.prefix + "-other", updating=True):
+ with installation_access():
+ pass
+
+
+def test_interrupted_installation_refuses_startup_but_allows_repair(isolated_installation):
+ pending = isolated_installation / ".nanobot/run" / f"update-{installation_state_dir().name[:16]}.pending"
+ pending.parent.mkdir(parents=True)
+ pending.write_text("An older updater was interrupted")
+ with pytest.raises(InstallationBusyError, match="previous update did not finish"):
+ with installation_access():
+ pytest.fail("Runtime used partially replaced files")
+ with installation_access(updating=True):
+ pass
+ with installation_access(allow_incomplete=True):
+ pass
+ with child_lease(isolated_installation, sys.prefix, updating=True):
+ with pytest.raises(InstallationBusyError, match="being updated"):
+ with installation_access(allow_incomplete=True):
+ pytest.fail("A diagnostic command raced the active installer")
+
+
+def test_aliases_share_installation_lock(isolated_installation, tmp_path):
+ environment = Path(sys.prefix)
+ environment.mkdir()
+ alias = tmp_path / "alias"
+ try:
+ alias.symlink_to(environment, target_is_directory=True)
+ except OSError:
+ pytest.skip("Directory symlinks are not enabled for this account")
+ with child_lease(isolated_installation, str(alias), updating=True):
+ with pytest.raises(InstallationBusyError):
+ with installation_access():
+ pytest.fail("Alias bypassed installation lease")
diff --git a/tests/test_installed_release_probe.py b/tests/test_installed_release_probe.py
new file mode 100644
index 000000000..76967ee20
--- /dev/null
+++ b/tests/test_installed_release_probe.py
@@ -0,0 +1,110 @@
+"""Protect the real release probe from accepting an incomplete built frontend."""
+
+import json
+import socket
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+from scripts.verify_installed_release import (
+ _wait_for_closed_listeners,
+ gateway_probe,
+ host_environment,
+ webui_assets,
+)
+
+
+def test_probe_waits_for_listener_teardown_after_redirector_exit(monkeypatch):
+ with socket.socket() as listener:
+ listener.bind(("127.0.0.1", 0))
+ listener.listen()
+ port = listener.getsockname()[1]
+ # A still-live listener cannot count as cleaned up.
+ with pytest.raises(ValueError, match="listener remained reachable"):
+ _wait_for_closed_listeners((port,), timeout=0)
+ # Model the kernel completing teardown after the first observation.
+ monkeypatch.setattr("scripts.verify_installed_release.time.sleep", lambda _: listener.close())
+ _wait_for_closed_listeners((port,))
+
+
+def test_isolation_retains_windows_cpu_identity_without_developer_paths():
+ environment = {"SYSTEMROOT": r"C:\Windows", "PROCESSOR_ARCHITECTURE": "AMD64",
+ "PROCESSOR_ARCHITEW6432": "AMD64", "PATH": r"C:\dev\bun",
+ "PYTHONPATH": r"C:\checkout", "NANOBOT_TUI_BIN": r"C:\old\tui.exe"}
+ expected = {key: environment[key] for key in (
+ "SYSTEMROOT", "PROCESSOR_ARCHITECTURE", "PROCESSOR_ARCHITEW6432",
+ )}
+ assert host_environment(environment) == expected
+ # The installer and installed-package probe apply this boundary separately.
+ assert host_environment(host_environment(environment)) == expected
+
+
+def frontend(tmp_path):
+ assets = tmp_path / "assets"
+ assets.mkdir()
+ for name in ("entry.js", "lazy.js", "style.css"):
+ (assets / name).write_text("compiled content", encoding="utf-8")
+ manifest = {
+ "index.html": {"file": "assets/entry.js", "css": ["assets/style.css"],
+ "dynamicImports": ["settings"]},
+ "settings": {"file": "assets/lazy.js", "imports": ["index.html"]},
+ }
+ (tmp_path / "index.html").write_text('<script src="/assets/entry.js"></script>')
+ (tmp_path / "asset-manifest.json").write_text(json.dumps(manifest))
+ return tmp_path
+
+
+def test_manifest_covers_lazy_assets_not_only_initial_html(frontend):
+ assert webui_assets(frontend) == {"assets/entry.js", "assets/lazy.js", "assets/style.css"}
+ (frontend / "assets/lazy.js").unlink()
+ with pytest.raises(ValueError, match="Missing or empty.*lazy.js"):
+ webui_assets(frontend)
+
+
+def test_missing_import_record_fails_even_if_entrypoint_exists(frontend):
+ path = frontend / "asset-manifest.json"
+ manifest = json.loads(path.read_text())
+ del manifest["settings"]
+ path.write_text(json.dumps(manifest))
+ with pytest.raises(ValueError, match="Missing WebUI manifest dependency"):
+ webui_assets(frontend)
+
+
+def test_stale_html_cannot_pass_against_an_unrelated_manifest(frontend):
+ (frontend / "index.html").write_text('<script src="/assets/old.js"></script>')
+ with pytest.raises(ValueError, match="HTML entrypoints"):
+ webui_assets(frontend)
+
+
[email protected]("options", [[], ["--gateway"]])
+def test_probe_requires_isolated_python_before_importing_source(tmp_path, options):
+ script = Path(__file__).resolve().parents[1] / "scripts/verify_installed_release.py"
+ report = tmp_path / "report.json"
+ result = subprocess.run(
+ [sys.executable, str(script), "--version", "0.3.6.dev1", "--commit", "a" * 40,
+ "--report", str(report), *options], capture_output=True, text=True, timeout=10,
+ )
+ assert result.returncode == 2
+ assert "python -I" in result.stderr
+ assert not report.exists()
+
+
+def test_gateway_probe_reports_failed_cli_start_and_reaps_its_child(tmp_path, monkeypatch, capsys):
+ popen = subprocess.Popen
+ children = []
+
+ def failed_cli(command, **kwargs):
+ # A missing runtime dependency makes the installed CLI exit before binding.
+ child = popen([command[0], "-I", "-c",
+ "print('candidate startup failed'); raise SystemExit(7)"], **kwargs)
+ children.append(child)
+ return child
+
+ monkeypatch.setattr(subprocess, "Popen", failed_cli)
+ with pytest.raises(ValueError, match="exited before readiness: 7"):
+ gateway_probe("0.3.6.dev1", tmp_path / "gateway")
+ assert len(children) == 1 and children[0].poll() == 7
+ assert "candidate startup failed" in capsys.readouterr().err
diff --git a/tests/test_installer_exec.py b/tests/test_installer_exec.py
new file mode 100644
index 000000000..0a8098bae
--- /dev/null
+++ b/tests/test_installer_exec.py
@@ -0,0 +1,108 @@
+"""A replacement installer program retains its own installation and store leases."""
+
+import os
+import selectors
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+from nanobot.data_access import data_access
+from nanobot.installation_lock import InstallationBusyError, installation_access
+
+pytestmark = pytest.mark.skipif(os.name != "posix", reason="POSIX exec handoff only")
+
+_PROGRAM = "import os,sys; print(os.getpid(), flush=True); sys.stdin.read(1)"
+_EXEC = """
+import os,sys
+from pathlib import Path
+from nanobot.data_access import data_access
+from nanobot.installation_lock import installation_access
+Path.home = classmethod(lambda cls: Path(sys.argv[1]))
+with installation_access(updating=True, environment=sys.argv[2]) as installation:
+ with data_access([sys.argv[3]], updating=True) as data:
+ with installation.inherit_for_exec(), data.inherit_for_exec():
+ os.execve(sys.executable, [sys.executable, '-I', '-c', sys.argv[4]], os.environ)
+"""
+
+
+def ready(process):
+ with selectors.DefaultSelector() as selector:
+ selector.register(process.stdout, selectors.EVENT_READ)
+ assert selector.select(timeout=10), "Installer did not become ready"
+ assert process.stdout.readline().strip() == str(process.pid)
+
+
+def finish(process):
+ if process.poll() is None:
+ process.kill()
+ process.communicate(timeout=10)
+
+
[email protected]("crash", [False, True])
+def test_exec_retains_both_leases_until_installer_exits(tmp_path, monkeypatch, crash):
+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path))
+ environment, store = tmp_path / "installation", tmp_path / "sessions"
+ process = subprocess.Popen(
+ [sys.executable, "-c", _EXEC, str(tmp_path), str(environment), str(store), _PROGRAM],
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
+ )
+ try:
+ ready(process) # Same PID; the program no longer imports nanobot or owns Python lease objects.
+ for updating in (False, True):
+ with pytest.raises(InstallationBusyError):
+ with installation_access(updating=updating, environment=environment):
+ pytest.fail("Exec lost the installation lease")
+ with pytest.raises(InstallationBusyError, match="data is in use"):
+ with data_access([store / "conversation.jsonl"]):
+ pytest.fail("Exec lost the overlapping store lease")
+ with data_access([tmp_path / "other sessions"]):
+ pass # A disjoint runtime remains usable.
+ if crash:
+ process.kill()
+ else:
+ process.stdin.write("x")
+ process.stdin.flush()
+ process.wait(timeout=10)
+ finally:
+ finish(process)
+ with installation_access(updating=True, environment=environment), data_access([store], updating=True):
+ pass # Actual installer exit, including a crash, releases all OS leases.
+
+
[email protected]("high_stdout_fd", [False, True])
+def test_failed_exec_does_not_leak_leases_to_later_children(tmp_path, monkeypatch, high_stdout_fd):
+ if high_stdout_fd:
+ import fcntl
+ import resource
+
+ if resource.getrlimit(resource.RLIMIT_NOFILE)[0] <= 1024:
+ pytest.skip("Process limit cannot reproduce a stdout FD outside select()'s range")
+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path))
+ environment, store = tmp_path / "installation", tmp_path / "sessions"
+ process = None
+ try:
+ with (installation_access(updating=True, environment=environment) as installation,
+ data_access([store], updating=True) as data):
+ with pytest.raises(FileNotFoundError):
+ with installation.inherit_for_exec(), data.inherit_for_exec():
+ os.execve(str(tmp_path / "missing-installer"), ["missing-installer"], os.environ)
+ # Deliberately allow inheritable FDs here. Restoration, not Popen's
+ # normal close_fds=True, must prevent this unrelated child retaining them.
+ process = subprocess.Popen(
+ [sys.executable, "-I", "-c", _PROGRAM], close_fds=False,
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
+ )
+ if high_stdout_fd:
+ # Full-suite CI can allocate pipes above select()'s FD_SETSIZE.
+ descriptor = fcntl.fcntl(process.stdout.fileno(), fcntl.F_DUPFD_CLOEXEC, 1024)
+ process.stdout.close()
+ process.stdout = os.fdopen(descriptor)
+ ready(process)
+ assert process.poll() is None
+ with installation_access(updating=True, environment=environment), data_access([store], updating=True):
+ pass
+ finally:
+ if process is not None:
+ finish(process)
diff --git a/tests/test_openai_api.py b/tests/test_openai_api.py
index b801d02f6..a3c202982 100644
--- a/tests/test_openai_api.py
+++ b/tests/test_openai_api.py
@@ -588,7 +588,8 @@ async def test_process_direct_accepts_media() -> None:
loop = AgentLoop.__new__(AgentLoop)
loop._session_locks = {}
- loop.runtime_event_publisher = RuntimeEventPublisher(MessageBus())
+ loop.bus = MessageBus()
+ loop.runtime_event_publisher = RuntimeEventPublisher(loop.bus)
captured_msg = None
diff --git a/tests/test_packaged_update_probe.py b/tests/test_packaged_update_probe.py
new file mode 100644
index 000000000..d6dea8141
--- /dev/null
+++ b/tests/test_packaged_update_probe.py
@@ -0,0 +1,189 @@
+"""Keep acceptance evidence honest: real target bytes and fail-closed fixtures."""
+
+import asyncio
+import csv
+import hashlib
+import io
+import json
+import subprocess
+import sys
+from pathlib import Path
+from zipfile import ZipFile, ZipInfo
+
+import httpx
+import pytest
+
+from nanobot.release_feed import ReleaseFeed
+from scripts.verify_packaged_update import (
+ assert_canonical_preserved,
+ assert_history_preserved,
+ canonical_records,
+ digest,
+ feed_records,
+ fixture_wheel,
+ replace_once,
+)
+
+
+def test_historical_projection_defaults_do_not_mask_history_loss():
+ # Real retained packages omit unknown timestamps and an inactive goal from
+ # their public projection, although the latter is already in their JSONL.
+ events = [{"event": "user_message", "projection_id": "input", "text": "Keep this"},
+ {"event": "turn_end", "projection_id": "complete"}]
+ before = {"events": events, "completed_turn_ids": ["turn"]}
+ projected = [{**events[0], "created_at_ms": 0},
+ {**events[1], "created_at_ms": 0, "goal_state": {"active": False}}]
+ after = {**before, "events": projected}
+ assert_history_preserved(before, after)
+ assert_history_preserved(after, after)
+ for change in ({"text": "Changed"}, {"projection_id": "changed"}, {"created_at_ms": 123}):
+ with pytest.raises(AssertionError):
+ assert_history_preserved(before, {**after, "events": [{**projected[0], **change}, projected[1]]})
+ with pytest.raises(AssertionError):
+ assert_history_preserved(before, {**after, "events": [projected[0], {**projected[1], "goal_state": {"active": True}}]})
+ with pytest.raises(AssertionError):
+ assert_history_preserved(before, {**after, "events": projected[:1]})
+ with pytest.raises(AssertionError):
+ assert_history_preserved(before, {**after, "completed_turn_ids": []})
+ with pytest.raises(AssertionError):
+ assert_history_preserved(after, before)
+
+
+def test_display_migration_allows_an_empty_owner_without_masking_context_loss(tmp_path):
+ from nanobot.session.display_history import HistoryFact, HistoryImport, HistoryKind
+ from nanobot.session.manager import Session
+ from nanobot.session.sqlite_store import SqliteSessionStore
+
+ store = SqliteSessionStore(tmp_path)
+ store.initialize(tmp_path)
+ session = Session(key="websocket:canonical-only")
+ session.add_message("user", "Keep this original context")
+ store.save(session)
+ before = canonical_records(store.path)
+ store.migrate_history("acceptance-import", lambda _: [HistoryImport(
+ key="websocket:display-only", facts=[HistoryFact(HistoryKind.ANSWER, {"text": "Display only"})],
+ )])
+ after = canonical_records(store.path)
+ assert_canonical_preserved(before, after)
+ assert_canonical_preserved(after, after)
+ # The real /api/sessions read allocates the newly imported owner's handle.
+ store.update_metadata("websocket:display-only", {"session_handle": "jeno"})
+ after = canonical_records(store.path)
+ assert_canonical_preserved(before, after)
+ with pytest.raises(AssertionError):
+ assert_canonical_preserved(before, {**after, "messages": []})
+ with pytest.raises(AssertionError):
+ assert_canonical_preserved(before, {**after, "sessions": after["sessions"][1:]})
+ store.update_metadata("websocket:display-only", {"unexpected": "context"})
+ with pytest.raises(AssertionError):
+ assert_canonical_preserved(before, canonical_records(store.path))
+
+
+def wheel(tmp_path, version, *, worker=b"# worker\n", fallback=b"# fallback\n"):
+ path = tmp_path / f"nanobot_ai-{version}-py3-none-manylinux_2_17_x86_64.whl"
+ with ZipFile(path, "w") as archive:
+ archive.writestr(f"nanobot_ai-{version}.dist-info/METADATA", f"Name: nanobot-ai\nVersion: {version}\n")
+ archive.writestr("nanobot/__init__.py", "# unchanged application\n")
+ archive.writestr("nanobot/release_feed.py", "transport=transport or PinnedDNSAsyncTransport(),\n")
+ archive.writestr("nanobot/update_worker.py", worker)
+ archive.writestr("nanobot/update_fallback.py", fallback)
+ binary = ZipInfo("nanobot/tui/bin/nanobot-tui")
+ binary.external_attr = 0o100755 << 16
+ archive.writestr(binary, b"native executable fixture")
+ return path
+
+
+def test_baseline_instrumentation_does_not_modify_the_target(tmp_path):
+ source = wheel(tmp_path, "0.3.6")
+ before = digest(source)
+ baseline = fixture_wheel(source, tmp_path / "baseline", "0.3.5", feed=tmp_path / "feed.json")
+ assert digest(source) == before
+ with ZipFile(source) as original, ZipFile(baseline) as copied:
+ assert copied.read("nanobot/__init__.py") == original.read("nanobot/__init__.py")
+ assert "nanobot/_acceptance_feed.py" not in original.namelist()
+ assert copied.getinfo("nanobot/tui/bin/nanobot-tui").external_attr == original.getinfo("nanobot/tui/bin/nanobot-tui").external_attr
+ records = csv.reader(io.StringIO(copied.read("nanobot_ai-0.3.5.dist-info/RECORD").decode()))
+ for name, checksum, size in records:
+ if checksum:
+ assert int(size) == len(copied.read(name))
+ assert checksum.startswith("sha256=")
+ with pytest.raises(FileExistsError):
+ fixture_wheel(source, tmp_path / "baseline", "0.3.5", feed=tmp_path / "feed.json")
+
+
[email protected]("version,channel", [("0.3.6", "stable"), ("0.3.6.dev42", "preview")])
+def test_local_feed_uses_the_real_resolver_and_exact_target_hash(tmp_path, monkeypatch, version, channel):
+ from unittest.mock import AsyncMock
+
+ # The packaged lifecycle fixture is deliberately not a public signed release.
+ monkeypatch.setattr(ReleaseFeed, "_authorize", AsyncMock())
+ from packaging.tags import Tag
+
+ candidate = wheel(tmp_path, version)
+ records = feed_records(candidate, "a" * 40)
+
+ def respond(request):
+ item = records[str(request.url)]
+ return httpx.Response(200, content=candidate.read_bytes() if "file" in item else json.dumps(item["json"]).encode())
+
+ async def check():
+ async with ReleaseFeed(tmp_path / "feed", transport=httpx.MockTransport(respond),
+ supported_tags=[Tag("py3", "none", "manylinux_2_17_x86_64")]) as feed:
+ target = await feed.latest(channel)
+ assert target.version == version
+ assert target.artifact.sha256 == hashlib.sha256(candidate.read_bytes()).hexdigest()
+ await feed.revalidate(target)
+ asyncio.run(check())
+
+
+def test_changed_fault_seam_is_not_silently_reported_as_fault_coverage():
+ with pytest.raises(ValueError, match="seam changed"):
+ replace_once(b"new worker", b"old worker", b"fault")
+ with pytest.raises(ValueError, match="seam changed"):
+ replace_once(b"old old", b"old", b"fault")
+
+
+def test_consecutive_feed_advances_generation_without_rewriting_a_release(tmp_path):
+ from nanobot.release_feed import CATALOGUE_URL
+ from nanobot.releases import ReleaseCatalogue
+
+ intermediate = wheel(tmp_path, "0.3.6.dev0")
+ target = wheel(tmp_path, "0.3.6.dev2")
+ previous = ReleaseCatalogue.model_validate(feed_records(intermediate, "a" * 40)[CATALOGUE_URL]["json"])
+ current = ReleaseCatalogue.model_validate(feed_records(target, "b" * 40, generation=2)[CATALOGUE_URL]["json"])
+ current.validate_successor(previous)
+ with pytest.raises(ValueError, match="newer generation"):
+ current.model_copy(update={"generation": 1}).validate_successor(previous)
+
+
[email protected]("scenario,marker", [
+ ("worker-exit", b"os._exit(91)"),
+ ("metadata-loss", b"os._exit(92)"),
+ ("backup-failure", b"Injected backup write failure"),
+ ("restore-interruption", b"Injected rename interruption"),
+])
+def test_windows_packaged_sources_keep_fault_injection_reachable(tmp_path, scenario, marker):
+ package = Path(__file__).resolve().parents[1] / "nanobot"
+ def windows_source(name):
+ return (package / name).read_bytes().replace(b"\r\n", b"\n").replace(b"\n", b"\r\n")
+ source = wheel(tmp_path, "0.3.6", worker=windows_source("update_worker.py"),
+ fallback=windows_source("update_fallback.py"))
+ before = digest(source)
+ baseline = fixture_wheel(source, tmp_path / "baseline", "0.3.5", feed=tmp_path / "feed.json", scenario=scenario)
+ with ZipFile(baseline) as archive:
+ name = "update_fallback.py" if scenario == "restore-interruption" else "update_worker.py"
+ content = archive.read("nanobot/" + name)
+ assert content.count(marker) == 1
+ if scenario != "restore-interruption":
+ assert repr(str(tmp_path / "injected-fault")).encode() in content
+ compile(content, name, "exec")
+ assert digest(source) == before
+
+
+def test_unisolated_probe_refuses_before_creating_output(tmp_path):
+ script = Path(__file__).resolve().parents[1] / "scripts/verify_packaged_update.py"
+ output = tmp_path / "must-not-exist"
+ result = subprocess.run([sys.executable, str(script), "--output", str(output)],
+ capture_output=True, text=True, timeout=10)
+ assert result.returncode == 2 and "python -I" in result.stderr
+ assert not output.exists()
diff --git a/tests/test_release_candidate.py b/tests/test_release_candidate.py
new file mode 100644
index 000000000..865cd7126
--- /dev/null
+++ b/tests/test_release_candidate.py
@@ -0,0 +1,127 @@
+"""Candidate preparation uses real isolated Git repositories, never a live install."""
+
+import subprocess
+import tomllib
+from types import SimpleNamespace
+
+import pytest
+
+from scripts.release_candidate import (
+ _candidate_identity,
+ _source_payload,
+ prepare_preview,
+ preview_version,
+)
+
+
+def git(root, *args):
+ return subprocess.run(["git", *args], cwd=root, check=True, capture_output=True,
+ text=True).stdout.strip()
+
+
+def source(tmp_path):
+ root = tmp_path / "source"
+ root.mkdir()
+ (root / "nanobot").mkdir()
+ (root / "pyproject.toml").write_text(
+ '[project]\nname = "nanobot-ai"\nversion = "0.3.5"\nrequires-python = ">=3.11"\n\n'
+ )
+ (root / "nanobot/__init__.py").write_text(
+ 'def _resolve_version():\n return _read_pyproject_version() or "0.3.5"\n\n'
+ )
+ git(root, "init", "-q")
+ git(root, "add", ".")
+ git(root, "-c", "user.name=Test", "-c", "[email protected]",
+ "-c", "commit.gpgsign=false", "commit", "-qm", "source")
+ return root, git(root, "rev-parse", "HEAD")
+
+
+def test_same_source_and_sequence_produce_same_candidate_without_mutating_source(tmp_path, source):
+ root, source_commit = source
+ before = (root / "pyproject.toml").read_bytes()
+ first = prepare_preview(root, tmp_path / "candidate-one", source_commit=source_commit,
+ base="0.3.6", sequence=42)
+ second = prepare_preview(root, tmp_path / "candidate-two", source_commit=source_commit,
+ base="0.3.6", sequence=42)
+ assert first == second
+ assert (root / "pyproject.toml").read_bytes() == before
+ assert git(root, "status", "--porcelain") == ""
+ assert git(tmp_path / "candidate-one", "rev-parse", "HEAD^") == source_commit
+ assert tomllib.loads((tmp_path / "candidate-one/pyproject.toml").read_text())["project"]["version"] == "0.3.6.dev42"
+ assert _candidate_identity(tmp_path / "candidate-one", source_commit) == (
+ "0.3.6.dev42", ">=3.11", first["candidate_commit"],
+ )
+
+
+def test_dirty_source_is_not_accidentally_included_in_candidate(tmp_path, source):
+ root, source_commit = source
+ (root / "secret.txt").write_text("local data")
+ (root / "nanobot/__init__.py").write_text("uncommitted work")
+ prepare_preview(root, tmp_path / "candidate", source_commit=source_commit, base="0.3.6", sequence=1)
+ assert not (tmp_path / "candidate/secret.txt").exists()
+ assert "0.3.6.dev1" in (tmp_path / "candidate/nanobot/__init__.py").read_text()
+ assert (root / "nanobot/__init__.py").read_text() == "uncommitted work"
+
+
+def test_refuses_existing_output_and_published_stable_base(tmp_path, source):
+ root, commit = source
+ with pytest.raises(ValueError, match="new directory"):
+ prepare_preview(root, root, source_commit=commit, base="0.3.6", sequence=1)
+ git(root, "tag", "v0.3.6")
+ with pytest.raises(ValueError, match="existing stable tag"):
+ prepare_preview(root, tmp_path / "candidate", source_commit=commit, base="0.3.6", sequence=1)
+ assert not (tmp_path / "candidate").exists()
+
+
+def test_arbitrary_ref_or_invalid_version_never_creates_candidate(tmp_path, source):
+ root, commit = source
+ with pytest.raises(ValueError, match="exact"):
+ prepare_preview(root, tmp_path / "candidate", source_commit="main", base="0.3.6", sequence=1)
+ with pytest.raises(ValueError):
+ prepare_preview(root, tmp_path / "candidate", source_commit=commit, base="0.3.6.dev1", sequence=2)
+ assert not (tmp_path / "candidate").exists()
+ with pytest.raises(ValueError):
+ preview_version("0.3.6", 0)
+
+
+def test_verification_rejects_changes_after_candidate_commit(tmp_path, source):
+ root, commit = source
+ target = tmp_path / "candidate"
+ prepare_preview(root, target, source_commit=commit, base="0.3.6", sequence=1)
+ with (target / "nanobot/__init__.py").open("a") as stream:
+ stream.write("# unchecked change\n")
+ with pytest.raises(ValueError, match="uncommitted"):
+ _candidate_identity(target, commit)
+ git(target, "add", ".")
+ git(target, "-c", "user.name=Test", "-c", "[email protected]",
+ "-c", "commit.gpgsign=false", "commit", "--amend", "--no-edit", "-q")
+ with pytest.raises(ValueError, match="beyond"):
+ _candidate_identity(target, commit)
+
+
+def test_candidate_verifies_bundled_documentation_against_its_tracked_source(source):
+ from hatch_build import WebUIBuildHook
+
+ root, _ = source
+ with (root / "pyproject.toml").open("a") as stream:
+ stream.write('[tool.hatch.build.targets.sdist]\nexclude = ["docs/plans/**"]\n')
+ (root / "docs/plans").mkdir(parents=True)
+ (root / "docs/README.md").write_text("Checked documentation", encoding="utf-8")
+ (root / "docs/plans/private.md").write_text("Not packaged", encoding="utf-8")
+ git(root, "add", ".")
+ hook = WebUIBuildHook(str(root), {}, None, {}, "", "wheel",
+ SimpleNamespace(display_info=lambda message: None))
+ hook.initialize("editable", {})
+ reference = "nanobot/skills/nanobot-document/references/README.md"
+ names = ["nanobot/__init__.py", "docs/README.md", reference]
+ prefix = "nanobot_ai-0.3.5/"
+ packaged = {prefix + name: (root / name).read_bytes() for name in names}
+ payload = _source_payload(root, packaged, prefix)
+ assert payload[reference] == (root / "docs/README.md").read_bytes()
+
+ # Both the shipped reference and the source used to rebuild the sdist must
+ # match the reviewed documentation, not merely match each other.
+ for name in (reference, "docs/README.md"):
+ with pytest.raises(ValueError, match="differs from the candidate"):
+ _source_payload(root, {**packaged, prefix + name: b"Unchecked instructions"}, prefix)
diff --git a/tests/test_release_feed.py b/tests/test_release_feed.py
new file mode 100644
index 000000000..ea21f5f64
--- /dev/null
+++ b/tests/test_release_feed.py
@@ -0,0 +1,291 @@
+"""Exact selection and staging through real HTTP parsing, without public mutations."""
+
+import hashlib
+import io
+import zipfile
+from unittest.mock import AsyncMock
+
+import httpx
+import pytest
+from packaging.tags import Tag
+
+from nanobot.release_feed import CATALOGUE_URL, PYPI_URL, ReleaseFeed, ReleaseFeedError
+from nanobot.releases import (
+ ReleaseArtifact,
+ ReleaseCatalogue,
+ ReleaseManifest,
+ ReleasePointer,
+ release_filenames,
+)
+
+PLATFORM = "macosx_13_0_arm64"
+
+
[email protected](autouse=True)
+def checksum_only_fixtures(monkeypatch):
+ # These synthetic packages exercise selection/download integrity, not
+ # publication authority. The real approval boundary is tested separately.
+ monkeypatch.setattr(ReleaseFeed, "_authorize", AsyncMock())
+
+
+def wheel_bytes(version):
+ buffer = io.BytesIO()
+ with zipfile.ZipFile(buffer, "w") as wheel:
+ wheel.writestr(f"nanobot_ai-{version}.dist-info/METADATA",
+ f"Metadata-Version: 2.1\nName: nanobot-ai\nVersion: {version}\n")
+ return buffer.getvalue()
+
+
+def pypi(version="0.3.5", data=None):
+ data = data or wheel_bytes(version)
+ return {
+ "info": {"name": "nanobot-ai", "version": version, "requires_python": ">=3.11"},
+ "urls": [{"filename": name, "size": len(data), "yanked": False,
+ "digests": {"sha256": hashlib.sha256(data).hexdigest()},
+ "url": f"https://files.pythonhosted.org/packages/test/{name}"}
+ for name in sorted(release_filenames(version)) if name.endswith((".whl", ".tar.gz"))],
+ }
+
+
+def preview(version="0.3.6.dev42"):
+ data = wheel_bytes(version)
+ manifest = ReleaseManifest(
+ version=version, source_commit="a" * 40, candidate_commit="b" * 40, requires_python=">=3.11",
+ artifacts=[ReleaseArtifact(filename=name, size=len(data), sha256=hashlib.sha256(data).hexdigest())
+ for name in sorted(release_filenames(version))],
+ )
+ payload = manifest.model_dump_json().encode()
+ pointer = ReleasePointer(version=version, candidate_commit=manifest.candidate_commit,
+ manifest_sha256=hashlib.sha256(payload).hexdigest())
+ return pointer, payload, data
+
+
+def feed(tmp_path, handler, *, platform=PLATFORM, python="3.11.4"):
+ return ReleaseFeed(tmp_path / "cache", transport=httpx.MockTransport(handler),
+ python_version=python, supported_tags=[Tag("py3", "none", platform)])
+
+
[email protected]("channel", ["stable", "preview"])
[email protected]("change", ["older", "changed_bytes", "reinstate", "removed_pointer"])
+async def test_new_catalogue_generation_cannot_rewrite_observed_release_history(tmp_path, change, channel):
+ pointer, _, _ = preview("0.3.6" if channel == "stable" else "0.3.6.dev42")
+ old = ReleaseCatalogue(generation=1, **{channel: pointer}, withdrawn={"0.3.6.dev40": "Broken startup"})
+ selected = old
+ async with feed(tmp_path, lambda _: httpx.Response(200, json=selected.model_dump(mode="json"))) as client:
+ assert await client.catalogue() == old
+ if change == "older":
+ older = preview("0.3.5" if channel == "stable" else "0.3.6.dev41")[0]
+ selected = old.model_copy(update={"generation": 2, channel: older})
+ elif change == "changed_bytes":
+ selected = old.model_copy(update={"generation": 2, channel: pointer.model_copy(update={"manifest_sha256": "f" * 64})})
+ elif change == "removed_pointer":
+ selected = old.model_copy(update={"generation": 2, channel: None})
+ else:
+ selected = old.model_copy(update={"generation": 2, "withdrawn": {}})
+ with pytest.raises(ReleaseFeedError):
+ await client.catalogue()
+ # A rejected response must not poison a later valid publication.
+ newer = preview("0.3.7" if channel == "stable" else "0.3.7.dev1")[0]
+ selected = old.model_copy(update={"generation": 2, channel: newer})
+ assert getattr(await client.catalogue(), channel) == newer
+
+
+async def test_stable_selects_and_revalidates_exact_target_not_new_latest(tmp_path):
+ requests = []
+
+ def handler(request):
+ requests.append(str(request.url))
+ assert request.headers.get("authorization") is None
+ assert str(request.url) in (f"{PYPI_URL}/json", f"{PYPI_URL}/0.3.5/json")
+ return httpx.Response(200, json=pypi())
+
+ async with feed(tmp_path, handler) as client:
+ target = await client.latest("stable")
+ assert target.artifact.filename.endswith(f"{PLATFORM}.whl")
+ await client.revalidate(target)
+ assert requests == [f"{PYPI_URL}/json", f"{PYPI_URL}/0.3.5/json"]
+
+
[email protected]("change", ["partial", "duplicate", "yanked", "prerelease", "other_host", "other_name"])
+async def test_bad_stable_metadata_never_becomes_an_offer(tmp_path, change):
+ metadata = pypi()
+ if change == "partial":
+ metadata["urls"].pop()
+ elif change == "duplicate":
+ metadata["urls"].append(metadata["urls"][0])
+ elif change == "yanked":
+ metadata["urls"][0]["yanked"] = True
+ elif change == "prerelease":
+ metadata = pypi("0.3.6.dev1")
+ elif change == "other_name":
+ metadata["info"]["name"] = "not-nanobot"
+ else:
+ for file in metadata["urls"]:
+ file["url"] = file["url"].replace("files.pythonhosted.org", "evil.example")
+ async with feed(tmp_path, lambda _: httpx.Response(200, json=metadata)) as client:
+ with pytest.raises((ReleaseFeedError, ValueError)):
+ await client.latest("stable")
+
+
[email protected]("platform,python", [("win_arm64", "3.11.4"), (PLATFORM, "3.10.0")])
+async def test_unsupported_runtime_has_no_source_build_fallback(tmp_path, platform, python):
+ async with feed(tmp_path, lambda _: httpx.Response(200, json=pypi()), platform=platform, python=python) as client:
+ with pytest.raises(ReleaseFeedError):
+ await client.latest("stable")
+
+
+async def test_changed_day_feed_does_not_change_an_already_approved_preview(tmp_path):
+ selected, manifest, _ = preview()
+ newer, _, _ = preview("0.3.6.dev43")
+ catalogue = ReleaseCatalogue(generation=1, preview=selected)
+
+ def handler(request):
+ if str(request.url) == CATALOGUE_URL:
+ return httpx.Response(200, content=catalogue.model_dump_json())
+ assert str(request.url) == selected.manifest_url
+ return httpx.Response(200, content=manifest)
+
+ async with feed(tmp_path, handler) as client:
+ target = await client.latest("preview")
+ catalogue = ReleaseCatalogue(generation=2, preview=newer)
+ await client.revalidate(target)
+ assert target.version == selected.version
+ catalogue = ReleaseCatalogue(generation=3, preview=newer, withdrawn={target.version: "Startup regression"})
+ with pytest.raises(ReleaseFeedError, match="withdrawn"):
+ await client.revalidate(target)
+
+
+async def test_cache_survives_new_process_etag_and_rejects_rollback_or_equivocation(tmp_path):
+ pointer, _, _ = preview()
+ catalogue = ReleaseCatalogue(generation=2, preview=pointer)
+ async with feed(tmp_path, lambda _: httpx.Response(200, content=catalogue.model_dump_json(), headers={"etag": '"v2"'})) as client:
+ await client.catalogue()
+
+ def unchanged(request):
+ assert request.headers["if-none-match"] == '"v2"'
+ return httpx.Response(304)
+
+ async with feed(tmp_path, unchanged) as client:
+ assert await client.catalogue() == catalogue
+ for changed in (ReleaseCatalogue(generation=1, preview=pointer), ReleaseCatalogue(generation=2)):
+ async with feed(tmp_path, lambda _: httpx.Response(200, content=changed.model_dump_json())) as client:
+ with pytest.raises(ReleaseFeedError, match="generation"):
+ await client.catalogue()
+ # A failed check cannot be converted into a successful cached result.
+ async with feed(tmp_path, lambda _: httpx.Response(503)) as client:
+ with pytest.raises(httpx.HTTPStatusError):
+ await client.catalogue()
+
+
+async def test_untrusted_redirect_and_oversized_metadata_are_rejected(tmp_path):
+ requests = []
+
+ def redirect(request):
+ requests.append(str(request.url))
+ return httpx.Response(302, headers={"location": "http://127.0.0.1/private"})
+
+ async with feed(tmp_path, redirect) as client:
+ with pytest.raises(ValueError, match="HTTPS"):
+ await client.latest("stable")
+ assert len(requests) == 1
+ async with feed(tmp_path, lambda _: httpx.Response(200, content=b"x" * (256 * 1024 + 1))) as client:
+ with pytest.raises(ReleaseFeedError, match="size limit"):
+ await client.catalogue()
+
+
+async def test_stages_actual_wheel_and_reuses_only_verified_bytes(tmp_path):
+ data = wheel_bytes("0.3.5")
+
+ def handler(request):
+ if request.url.host == "pypi.org":
+ return httpx.Response(200, json=pypi(data=data))
+ if request.url.host == "files.pythonhosted.org":
+ return httpx.Response(302, headers={"location": "https://release-assets.githubusercontent.com/wheel"})
+ assert request.url.host == "release-assets.githubusercontent.com"
+ return httpx.Response(200, content=data)
+
+ async with feed(tmp_path, handler) as client:
+ target = await client.latest("stable")
+ wheel = await client.download(target, tmp_path / "staging")
+ assert wheel.read_bytes() == data
+ assert await client.download(target, wheel.parent) == wheel
+ wheel.write_bytes(b"0" * len(data))
+ with pytest.raises(ReleaseFeedError, match="checksum"):
+ await client.download(target, wheel.parent)
+ assert wheel.read_bytes() != data # No clobber to hide the corrupt file.
+
+
+async def test_download_redirect_does_not_inherit_metadata_host_allowlist(tmp_path):
+ requests = []
+
+ def handler(request):
+ requests.append(str(request.url))
+ if request.url.host == "pypi.org":
+ return httpx.Response(200, json=pypi())
+ return httpx.Response(302, headers={"location": "https://raw.githubusercontent.com/private-wheel"})
+
+ async with feed(tmp_path, handler) as client:
+ target = await client.latest("stable")
+ with pytest.raises(ValueError, match="HTTPS"):
+ await client.download(target, tmp_path / "staging")
+ assert not any("raw.githubusercontent.com" in url for url in requests)
+ assert list((tmp_path / "staging").iterdir()) == []
+
+
+async def test_download_failure_cleans_partial_and_never_publishes_bad_wheel(tmp_path):
+ data = wheel_bytes("0.3.5")
+
+ def handler(request):
+ return (httpx.Response(200, json=pypi(data=data)) if request.url.host == "pypi.org"
+ else httpx.Response(200, content=data[:-1]))
+
+ async with feed(tmp_path, handler) as client:
+ target = await client.latest("stable")
+ with pytest.raises(ReleaseFeedError, match="size"):
+ await client.download(target, tmp_path / "staging")
+ assert list((tmp_path / "staging").iterdir()) == []
+
+
+async def test_preview_failure_never_falls_back_to_checkout_or_pypi(tmp_path):
+ requests = []
+
+ def absent(request):
+ requests.append(str(request.url))
+ return httpx.Response(404)
+
+ async with feed(tmp_path, absent) as client:
+ with pytest.raises(httpx.HTTPStatusError):
+ await client.latest("preview")
+ assert requests == [CATALOGUE_URL]
+
+
+async def test_pypi_yank_after_confirmation_blocks_download(tmp_path):
+ metadata = pypi()
+ async with feed(tmp_path, lambda _: httpx.Response(200, json=metadata)) as client:
+ target = await client.latest("stable")
+ metadata["urls"][0]["yanked"] = True
+ with pytest.raises(ReleaseFeedError, match="withdrawn"):
+ await client.download(target, tmp_path / "staging")
+ assert not (tmp_path / "staging").exists()
+
+
+async def test_corrupt_manifest_cannot_select_a_different_build(tmp_path):
+ pointer, manifest, _ = preview()
+ catalogue = ReleaseCatalogue(generation=1, preview=pointer)
+ async with feed(tmp_path, lambda request: httpx.Response(200, content=(
+ catalogue.model_dump_json().encode() if str(request.url) == CATALOGUE_URL else manifest + b"\n"
+ ))) as client:
+ with pytest.raises(ValueError, match="checksum"):
+ await client.latest("preview")
diff --git a/tests/test_release_install_guide.py b/tests/test_release_install_guide.py
new file mode 100644
index 000000000..a8a4587a5
--- /dev/null
+++ b/tests/test_release_install_guide.py
@@ -0,0 +1,76 @@
+"""The manual handoff binds commands to the verified version and platform bytes."""
+
+import hashlib
+import shlex
+
+import pytest
+
+from nanobot.releases import PLATFORMS, ReleaseArtifact, ReleaseManifest, release_filenames
+from scripts import release_candidate
+from scripts.release_install_guide import install_command, render_install_guide
+
+
+def manifest():
+ return ReleaseManifest(
+ version="0.4.0.dev123", source_commit="a" * 40, candidate_commit="b" * 40,
+ requires_python=">=3.11",
+ artifacts=[ReleaseArtifact(filename=name, size=123, sha256="c" * 64)
+ for name in sorted(release_filenames("0.4.0.dev123"))],
+ )
+
+
+def test_handoff_commands_bind_every_platform_to_its_exact_release(manifest):
+ guide = render_install_guide(manifest)
+ assert manifest.source_commit in guide
+ assert manifest.candidate_commit in guide
+ blocks = [block.split("\n", 1)[1].strip() for block in guide.split("```")[1::2]]
+ commands = [shlex.split(block) for block in blocks if block.startswith("python -I -c ")]
+ # PowerShell feeds the helper on stdin to avoid legacy native -c quoting.
+ commands += [["python", "-I", "-", None, *shlex.split(block.split("'@ | python -I - ", 1)[1])]
+ for block in blocks if block.startswith("@'\n")]
+ assert len(commands) == 5 * 3 * 2
+ for platform in PLATFORMS.values():
+ artifact = next(item for item in manifest.artifacts if item.filename.endswith(f"-{platform}.whl"))
+ assert manifest.artifact_url(artifact) in guide
+ expected = [artifact.filename, str(artifact.size), artifact.sha256]
+ assert sum(command[4:7] == expected for command in commands) == 6
+ assert all("--pre" not in command and "--force" not in command for command in commands)
+
+
+def test_handoff_cannot_generate_install_commands_for_source_or_foreign_artifact(manifest):
+ source = next(item for item in manifest.artifacts if item.filename.endswith(".tar.gz"))
+ with pytest.raises(ValueError, match="platform wheel"):
+ install_command(manifest, source, owner="pip", existing=False)
+ wheel = next(item for item in manifest.artifacts if item.filename.endswith(".whl"))
+ with pytest.raises(ValueError, match="does not belong"):
+ install_command(manifest, wheel.model_copy(update={"sha256": "d" * 64}), owner="uv", existing=True)
+
+
[email protected]("recognized", [True, False], ids=["current-installer", "older-installer"])
+def test_verified_handoff_only_offers_bootstrap_supported_by_candidate(tmp_path, monkeypatch, manifest, recognized):
+ root, generator, artifacts = (tmp_path / name for name in ("candidate", "generator", "artifacts"))
+ artifacts.mkdir()
+ for directory in (root, generator):
+ (directory / "scripts").mkdir(parents=True)
+ for name in ("install.sh", "install.ps1"):
+ contents = b"current implementation" if directory == generator or recognized else b"older implementation"
+ (directory / "scripts" / name).write_bytes(contents)
+ # Packaging is covered by the real archive test. Here the public writer must
+ # preserve the exact serialized manifest hash and inspect both candidate scripts.
+ payload = (manifest.model_dump_json(indent=2) + "\n").encode()
+ (artifacts / "release-manifest.json").write_bytes(payload)
+ monkeypatch.setattr(release_candidate, "ROOT", generator)
+ monkeypatch.setattr(release_candidate, "verify_candidate", lambda *args, **kwargs: manifest)
+ guide = tmp_path / "install.md"
+ release_candidate.write_install_guide(root, artifacts, guide, source_commit=manifest.source_commit)
+ text = guide.read_text()
+ assert ("## Automatic platform selection" in text) == recognized
+ if recognized:
+ digest = hashlib.sha256(payload).hexdigest()
+ assert f"--manifest-sha256 '{digest}'" in text
+ assert f"-ManifestSha256 '{digest}'" in text
+ for name in ("install.sh", "install.ps1"):
+ assert f"/{manifest.candidate_commit}/scripts/{name}" in text
+ assert "<summary>Manual platform and manager commands</summary>" in text
+ assert manifest.artifacts[0].sha256 in text # The explicit manual path remains available.
diff --git a/tests/test_release_trust.py b/tests/test_release_trust.py
new file mode 100644
index 000000000..8c0ba8e93
--- /dev/null
+++ b/tests/test_release_trust.py
@@ -0,0 +1,199 @@
+"""Publication authority is distinct from index/download integrity and recovery."""
+
+import hashlib
+import re
+from importlib.resources import as_file, files
+from pathlib import Path
+from unittest.mock import Mock
+
+import httpx
+import pytest
+import yaml
+from packaging.tags import Tag
+from sigstore.models import Bundle, TrustedRoot
+from sigstore.verify import Verifier
+from sigstore.verify.policy import Identity
+
+from nanobot import release_feed, release_trust
+from nanobot.release_feed import CATALOGUE_URL, PYPI_URL, ReleaseFeed, ReleaseFeedError
+from nanobot.releases import (
+ RELEASE_DOWNLOAD,
+ ReleaseArtifact,
+ ReleaseCatalogue,
+ ReleaseManifest,
+ ReleasePointer,
+ release_filenames,
+)
+from scripts.verify_release_approval import verify_manifest
+
+
+def crypto_verifier(monkeypatch):
+ # Deterministic offline test root from the pinned upstream distribution.
+ # Production must refresh its TUF trust root, not read a caller-selected root.
+ resource = files("sigstore._store").joinpath("https%3A%2F%2Ftuf-repo-cdn.sigstage.dev/trusted_root.json")
+ with as_file(resource) as path:
+ verifier = Verifier(trusted_root=TrustedRoot.from_file(str(path)))
+ monkeypatch.setattr(Verifier, "production", lambda: verifier)
+ return verifier
+
+
+def test_real_signature_is_valid_but_not_an_official_release_approval(crypto_verifier):
+ fixtures = Path(__file__).parent / "fixtures/sigstore"
+ payload = (fixtures / "bundle_v3.txt").read_bytes()
+ proof = (fixtures / "bundle_v3.txt.sigstore").read_bytes()
+ bundle = Bundle.from_json(proof)
+ identity = Identity(identity="[email protected]", issuer="https://github.com/login/oauth")
+ crypto_verifier.verify_artifact(payload, bundle, identity)
+ with pytest.raises(Exception):
+ crypto_verifier.verify_artifact(payload + b"modified", bundle, identity)
+ with pytest.raises(ValueError, match="official release approval"):
+ release_trust.verify_release_approval(payload, proof)
+
+
+def test_policy_is_fixed_to_manual_official_main_workflow(monkeypatch):
+ from datetime import datetime, timedelta, timezone
+
+ from cryptography import x509
+ from cryptography.hazmat.primitives import hashes
+ from cryptography.hazmat.primitives.asymmetric import ec
+ from cryptography.x509.oid import NameOID, ObjectIdentifier
+
+ seen = []
+ class Capture:
+ def verify_artifact(self, payload, bundle, policy):
+ seen.append(policy)
+ monkeypatch.setattr(Verifier, "production", lambda: Capture())
+ monkeypatch.setattr(Bundle, "from_json", lambda _: object())
+ release_trust.verify_release_approval(b"manifest", b"proof")
+ key = ec.generate_private_key(ec.SECP256R1())
+ name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "policy-only fixture")])
+ def certificate(identity, issuer, trigger):
+ builder = (x509.CertificateBuilder().subject_name(name).issuer_name(name)
+ .public_key(key.public_key()).serial_number(1)
+ .not_valid_before(datetime.now(timezone.utc) - timedelta(minutes=1))
+ .not_valid_after(datetime.now(timezone.utc) + timedelta(minutes=1))
+ .add_extension(x509.SubjectAlternativeName([x509.UniformResourceIdentifier(identity)]), False))
+ for oid, value in (("1", issuer), ("2", trigger)):
+ builder = builder.add_extension(x509.UnrecognizedExtension(
+ ObjectIdentifier("1.3.6.1.4.1.57264.1." + oid), value.encode()), False)
+ return builder.sign(key, hashes.SHA256())
+ expected = (release_trust.RELEASE_IDENTITY, release_trust.RELEASE_ISSUER, "workflow_dispatch")
+ seen[0].verify(certificate(*expected))
+ for changed in (
+ (expected[0].replace("HKUDS", "attacker"), expected[1], expected[2]),
+ (expected[0].replace("refs/heads/main", "refs/pull/1/merge"), expected[1], expected[2]),
+ (expected[0], "https://example.com", expected[2]),
+ (expected[0], expected[1], "pull_request_target"),
+ ):
+ with pytest.raises(Exception):
+ seen[0].verify(certificate(*changed))
+
+
[email protected]("failure", ["malformed", "unavailable", "oversized"])
+def test_failed_verification_has_no_checksum_only_fallback(monkeypatch, failure):
+ unavailable = Mock(side_effect=OSError("trust service unavailable"))
+ monkeypatch.setattr(Verifier, "production", unavailable)
+ proof = b"x" * (256 * 1024 + 1) if failure == "oversized" else b"invalid"
+ if failure == "unavailable":
+ proof = (Path(__file__).parent / "fixtures/sigstore/bundle_v3.txt.sigstore").read_bytes()
+ with pytest.raises(ValueError):
+ release_trust.verify_release_approval(b"manifest", proof)
+ assert unavailable.call_count == (1 if failure == "unavailable" else 0)
+
+
+def test_malformed_approval_is_rejected_without_contacting_trust_service(monkeypatch):
+ verifier = Mock()
+ monkeypatch.setattr(Verifier, "production", verifier)
+ with pytest.raises(ValueError, match="official release approval"):
+ release_trust.verify_release_approval(b"manifest", b"not a bundle")
+ verifier.assert_not_called()
+
+
+def release(version):
+ return ReleaseManifest(version=version, source_commit="a" * 40, candidate_commit="b" * 40,
+ requires_python=">=3.11", artifacts=[
+ ReleaseArtifact(filename=name, size=123, sha256="c" * 64) for name in sorted(release_filenames(version))
+ ])
+
+
[email protected]("channel", ["stable", "preview"])
[email protected]("change", ["valid", "missing", "forged", "wrong_package", "wrong_version"])
+async def test_download_and_handoff_require_approval_before_any_staging(tmp_path, monkeypatch, channel, change):
+ version = "0.3.6" if channel == "stable" else "0.3.7.dev1"
+ manifest = release(version)
+ payload = manifest.model_dump_json().encode()
+ pointer = ReleasePointer(version=version, candidate_commit=manifest.candidate_commit,
+ manifest_sha256=hashlib.sha256(payload).hexdigest())
+ catalogue = ReleaseCatalogue(generation=1, preview=pointer) if channel == "preview" else None
+ requests = []
+ base = f"{RELEASE_DOWNLOAD}/v{version}/release-manifest.json"
+ def respond(request):
+ url = str(request.url)
+ requests.append(url)
+ if url == CATALOGUE_URL:
+ return httpx.Response(200, content=catalogue.model_dump_json())
+ if url.startswith(PYPI_URL):
+ return httpx.Response(200, json={
+ "info": {"name": "nanobot-ai", "version": version, "requires_python": ">=3.11"},
+ "urls": [{"filename": item.filename, "size": item.size, "yanked": False,
+ "url": f"https://files.pythonhosted.org/packages/{item.filename}",
+ "digests": {"sha256": item.sha256}} for item in manifest.artifacts
+ if item.filename.endswith((".whl", ".tar.gz"))],
+ })
+ if url == base:
+ return httpx.Response(200, content=payload)
+ if url == base + ".sigstore.json":
+ return httpx.Response(404 if change == "missing" else 200, content=b"proof")
+ pytest.fail("Unapproved package download attempted")
+ # Only the crypto boundary is substituted for synthetic manifests; use the
+ # real feed, HTTP parsing, identity comparison and pre-staging admission.
+ verifier = Mock(side_effect=ValueError("forged approval") if change == "forged" else None)
+ monkeypatch.setattr(release_feed, "verify_release_approval", verifier)
+ async with ReleaseFeed(tmp_path / "cache", transport=httpx.MockTransport(respond),
+ supported_tags=[Tag("py3", "none", "win_amd64")]) as feed:
+ target = await feed.latest(channel)
+ if change == "wrong_package":
+ payload = payload.replace(b'"c' + b"c" * 63, b'"d' + b"d" * 63)
+ elif change == "wrong_version":
+ payload = release("0.4.0").model_dump_json().encode()
+ if change == "valid":
+ await feed.revalidate(target)
+ verifier.assert_called_once_with(payload, b"proof")
+ # A previous successful check is not a reusable authorization when
+ # the proof disappears or changes before handoff/retry.
+ verifier.side_effect = ValueError("approval revoked or replaced")
+ with pytest.raises(ValueError, match="revoked or replaced"):
+ await feed.revalidate(target)
+ assert verifier.call_count == 2
+ else:
+ with pytest.raises((ValueError, httpx.HTTPStatusError, ReleaseFeedError)):
+ await feed.download(target, tmp_path / "staging")
+ assert not (tmp_path / "staging").exists()
+
+
+def test_signing_handoff_requires_independently_approved_identity_and_digest(tmp_path):
+ manifest = release("0.3.7.dev1")
+ path = tmp_path / "release-manifest.json"
+ path.write_text(manifest.model_dump_json())
+ approved = dict(sha256=hashlib.sha256(path.read_bytes()).hexdigest(), version=manifest.version,
+ source_commit=manifest.source_commit, candidate_commit=manifest.candidate_commit)
+ assert verify_manifest(path, **approved) == manifest
+ for field in approved:
+ with pytest.raises(ValueError):
+ verify_manifest(path, **(approved | {field: "wrong"}))
+
+
+def test_approval_workflow_is_manual_gated_and_has_no_publication_permission():
+ workflow = Path(__file__).parents[1] / ".github/workflows/release-approve.yml"
+ definition = yaml.load(workflow.read_text(), Loader=yaml.BaseLoader)
+ assert set(definition["on"]) == {"workflow_dispatch"}
+ assert definition["permissions"] == {}
+ job = definition["jobs"]["approve"]
+ assert job["environment"] == "release-approval"
+ assert job["permissions"] == {"contents": "read", "id-token": "write"}
+ assert "github.ref == 'refs/heads/main'" in job["if"]
+ assert "vars.NANOBOT_RELEASE_SIGNING_ENABLED == 'true'" in job["if"]
+ for step in job["steps"]:
+ if "uses" in step:
+ assert re.fullmatch(r"[\w-]+/[\w-]+@[0-9a-f]{40}", step["uses"])
diff --git a/tests/test_releases.py b/tests/test_releases.py
new file mode 100644
index 000000000..dc5bd8809
--- /dev/null
+++ b/tests/test_releases.py
@@ -0,0 +1,125 @@
+"""Consumer contracts for trusted release metadata; no package installation here."""
+
+import hashlib
+import json
+
+import pytest
+from packaging.tags import Tag, mac_platforms
+from pydantic import ValidationError
+
+from nanobot.releases import (
+ ReleaseArtifact,
+ ReleaseCatalogue,
+ ReleaseManifest,
+ ReleasePointer,
+ release_filenames,
+)
+
+
+def manifest(version="0.3.6.dev42"):
+ return ReleaseManifest(
+ version=version, source_commit="a" * 40, candidate_commit="b" * 40,
+ requires_python=">=3.11",
+ artifacts=[ReleaseArtifact(filename=name, size=123, sha256="c" * 64)
+ for name in sorted(release_filenames(version))],
+ )
+
+
+def pointer(version):
+ release = manifest(version)
+ return ReleasePointer(version=version, candidate_commit=release.candidate_commit,
+ manifest_sha256=hashlib.sha256(release.model_dump_json().encode()).hexdigest())
+
+
+def test_preview_is_opt_in_and_subscribers_receive_the_final_release():
+ catalogue = ReleaseCatalogue(generation=10, stable=pointer("0.3.5"), preview=pointer("0.3.6.dev42"))
+ assert catalogue.latest("stable").version == "0.3.5"
+ assert catalogue.latest("preview").version == "0.3.6.dev42"
+ released = ReleaseCatalogue(generation=11, stable=pointer("0.3.6"), preview=catalogue.preview)
+ assert released.latest("preview").version == "0.3.6"
+
+
+def test_withdrawal_and_stale_catalogue_are_not_update_offers():
+ catalogue = ReleaseCatalogue(generation=10, stable=pointer("0.3.5"), preview=pointer("0.3.6.dev42"),
+ withdrawn={"0.3.6.dev42": "Broken startup"})
+ assert catalogue.latest("preview").version == "0.3.5"
+ with pytest.raises(ValueError, match="older"):
+ catalogue.latest("preview", minimum_generation=11)
+ assert ReleaseCatalogue(generation=10).latest("stable") is None
+
+
[email protected]("version", ["0.3.6.dev42", "0.3.6rc1", "0.3.6+local", "../main", "00.3.6"])
+def test_stable_catalogue_never_accepts_unreleased_or_noncanonical_targets(version):
+ with pytest.raises(ValueError):
+ ReleaseCatalogue.model_validate({
+ "generation": 1,
+ "stable": {"version": version, "candidate_commit": "a" * 40, "manifest_sha256": "b" * 64},
+ })
+
+
[email protected]("platform", [
+ "macosx_13_0_arm64", "macosx_13_0_x86_64", "manylinux_2_17_aarch64",
+ "manylinux_2_17_x86_64", "win_amd64",
+])
+def test_target_wheel_and_url_are_owned_by_the_manifest(platform):
+ release = manifest()
+ artifact = release.wheel_for(python_version="3.11.4", supported_tags=[Tag("py3", "none", platform)])
+ assert artifact.filename == f"nanobot_ai-0.3.6.dev42-py3-none-{platform}.whl"
+ assert release.artifact_url(artifact) == (
+ "https://github.com/HKUDS/nanobot/releases/download/v0.3.6.dev42/"
+ f"{artifact.filename}#sha256={'c' * 64}"
+ )
+
+
+def test_newer_macos_uses_compatible_minimum_platform_tag():
+ tags = [Tag("py3", "none", platform) for platform in mac_platforms((15, 0), "arm64")]
+ assert manifest().wheel_for(python_version="3.14.0", supported_tags=tags).filename.endswith(
+ "macosx_13_0_arm64.whl"
+ )
+
+
[email protected]("platform", ["musllinux_1_2_x86_64", "win_arm64"])
+def test_unsupported_platform_does_not_fall_back_to_source_build(platform):
+ with pytest.raises(ValueError, match="No compatible"):
+ manifest().wheel_for(python_version="3.11.4", supported_tags=[Tag("py3", "none", platform)])
+
+
+def test_python_requirement_checked_before_platform_selection():
+ with pytest.raises(ValueError, match="requires Python"):
+ manifest().wheel_for(python_version="3.10.0", supported_tags=[Tag("py3", "none", "win_amd64")])
+
+
+def test_downloaded_manifest_must_match_selected_bytes_and_identity():
+ release = manifest()
+ payload = release.model_dump_json().encode()
+ selected = pointer(release.version)
+ assert selected.verify_manifest(payload) == release
+ with pytest.raises(ValueError, match="checksum"):
+ selected.verify_manifest(payload + b"\n")
+ other_commit = selected.model_copy(update={"candidate_commit": "d" * 40})
+ with pytest.raises(ValueError, match="identity"):
+ other_commit.verify_manifest(payload)
+
+
[email protected]("change", ["missing", "duplicate", "mixed_version", "universal", "url"])
+def test_manifest_rejects_partial_mixed_or_redirected_uploads(change):
+ payload = manifest().model_dump(mode="json")
+ if change == "missing":
+ payload["artifacts"].pop()
+ elif change == "duplicate":
+ payload["artifacts"][-1] = payload["artifacts"][0]
+ elif change == "mixed_version":
+ payload["artifacts"][-1]["filename"] = "nanobot_ai-0.3.5.tar.gz"
+ elif change == "universal":
+ payload["artifacts"][-1]["filename"] = "nanobot_ai-0.3.6.dev42-py3-none-any.whl"
+ else:
+ payload["artifacts"][0]["url"] = "https://untrusted.example/installer.sh"
+ with pytest.raises(ValidationError):
+ ReleaseManifest.model_validate_json(json.dumps(payload))
+
+
+def test_catalogue_unknown_schema_and_blank_withdrawal_reason_fail_closed():
+ with pytest.raises(ValidationError):
+ ReleaseCatalogue.model_validate_json('{"schema_version":2,"generation":1}')
+ with pytest.raises(ValidationError, match="withdrawal reason"):
+ ReleaseCatalogue(generation=1, withdrawn={"0.3.6.dev42": " "})
diff --git a/tests/test_update.py b/tests/test_update.py
new file mode 100644
index 000000000..6e87a6595
--- /dev/null
+++ b/tests/test_update.py
@@ -0,0 +1,410 @@
+from __future__ import annotations
+
+import json
+import os
+import subprocess
+import sys
+from pathlib import Path
+from unittest.mock import Mock
+
+import pytest
+import typer
+from packaging.version import Version
+from typer.testing import CliRunner
+
+from nanobot import update
+from nanobot.cli.update import update as update_command
+from nanobot.installation_lock import installation_access, installation_id, pending_update_path
+from nanobot.optional_features import install_packages
+
+
+def git(root: Path, *args: str) -> str:
+ return subprocess.run(
+ ["git", "-C", str(root), *args], check=True, capture_output=True, text=True,
+ ).stdout.strip()
+
+
+def checkout(tmp_path, monkeypatch):
+ upstream = tmp_path / "upstream"
+ upstream.mkdir()
+ git(upstream, "init", "--initial-branch=main")
+ git(upstream, "config", "user.name", "Update test")
+ git(upstream, "config", "user.email", "[email protected]")
+ (upstream / "file").write_text("first", encoding="utf-8")
+ git(upstream, "add", ".")
+ git(upstream, "commit", "-m", "first")
+ root = tmp_path / "checkout"
+ git(tmp_path, "clone", str(upstream), str(root))
+ monkeypatch.setattr(update, "source_checkout", lambda: root)
+ return root, upstream
+
+
+def test_source_update_fast_forwards_current_branch(checkout):
+ root, upstream = checkout
+ (upstream / "file").write_text("second", encoding="utf-8")
+ git(upstream, "commit", "-am", "second")
+ assert update._prepare_source(lambda _: None) == root
+ assert git(root, "rev-parse", "HEAD") == git(upstream, "rev-parse", "HEAD")
+ assert git(root, "branch", "--show-current") == "main"
+
+
+def test_release_install_gets_a_managed_source_checkout(checkout, tmp_path, monkeypatch):
+ _, upstream = checkout
+ monkeypatch.setattr(update, "source_checkout", lambda: None)
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ monkeypatch.setattr(update, "_SOURCE_URL", str(upstream))
+ root = update._prepare_source(lambda _: None)
+ assert root == tmp_path / ".nanobot/src" / installation_id()[:16]
+ assert git(root, "rev-parse", "HEAD") == git(upstream, "rev-parse", "HEAD")
+ assert update._prepare_source(lambda _: None) == root
+
+
+def test_source_update_preserves_local_changes(checkout):
+ root, _ = checkout
+ (root / "file").write_text("my edits", encoding="utf-8")
+ before = git(root, "rev-parse", "HEAD")
+ with pytest.raises(update.UpdateError, match="local changes"):
+ update._prepare_source(lambda _: None)
+ assert (root / "file").read_text() == "my edits"
+ assert git(root, "rev-parse", "HEAD") == before
+
+
+def test_source_update_refuses_local_commits(checkout):
+ root, _ = checkout
+ git(root, "-c", "user.name=Test", "-c", "[email protected]",
+ "commit", "--allow-empty", "-m", "local")
+ before = git(root, "rev-parse", "HEAD")
+ with pytest.raises(update.UpdateError, match="cannot fast-forward"):
+ update._prepare_source(lambda _: None)
+ assert git(root, "rev-parse", "HEAD") == before
+
+
+def isolated_update(tmp_path, monkeypatch):
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ monkeypatch.delenv("RENDER", raising=False)
+ if Path("/.dockerenv").exists():
+ pytest.skip("Self-update intentionally refuses containers")
+ monkeypatch.setattr(update, "latest_release", lambda: "0.3.5")
+ monkeypatch.setattr(update, "__version__", "0.3.4")
+ monkeypatch.setattr(update, "_installed_version", lambda: Version(update.__version__))
+ monkeypatch.setattr(update, "update_blocked_reason", lambda **kwargs: "")
+ monkeypatch.setattr(update, "_checked", lambda *args, **kwargs: json.dumps(["0.3.5", "/env/nanobot/__init__.py"]))
+ install = Mock()
+ monkeypatch.setattr(update, "_install", install)
+ return install
+
+
+def test_release_update_replaces_same_version_editable_only(isolated_update, monkeypatch):
+ monkeypatch.setattr(update, "_is_editable", lambda: True)
+ result = update.update_installation(output=lambda _: None)
+ assert result == {"version": "0.3.5", "source": "pypi", "requires_restart": True}
+ assert isolated_update.call_args_list[0].args == (["nanobot-ai==0.3.5"],)
+ assert isolated_update.call_args_list[1].args == (
+ ["--force-reinstall", "--no-deps", "nanobot-ai==0.3.5"],
+ )
+
+
+def test_release_update_does_not_force_reinstall_wheel(isolated_update, monkeypatch):
+ monkeypatch.setattr(update, "_is_editable", lambda: False)
+ update.update_installation(output=lambda _: None)
+ isolated_update.assert_called_once_with(["nanobot-ai==0.3.5"], upgrade=True)
+
+
[email protected]("updating", [False, True], ids=["live-runtime", "another-updater"])
+def test_release_update_does_not_modify_an_in_use_installation(isolated_update, updating):
+ with installation_access(updating=updating):
+ with pytest.raises(update.UpdateError, match="installation is in use"):
+ update.update_installation(output=lambda _: None)
+ isolated_update.assert_not_called()
+ assert not update.incomplete_update()
+
+
+def test_update_verifies_in_fresh_interpreter(isolated_update, monkeypatch):
+ monkeypatch.setattr(update, "_is_editable", lambda: False)
+ checked = Mock(return_value=json.dumps(["0.3.4", "/env/nanobot/__init__.py"]))
+ monkeypatch.setattr(update, "_checked", checked)
+ with pytest.raises(update.UpdateError, match="expected 0.3.5"):
+ update.update_installation(output=lambda _: None)
+ assert checked.call_args_list[0].args[0][:3] == [sys.executable, "-I", "-c"]
+ assert checked.call_args_list[1].args[0][:2] == [sys.executable, "-c"]
+
+
[email protected]("has_uv", [False, True])
+def test_installer_bootstraps_only_when_pip_is_missing(monkeypatch, has_uv):
+ calls = []
+
+ def run(command, **kwargs):
+ calls.append(command)
+ if len(calls) == 1:
+ return subprocess.CompletedProcess(command, 1, "", "No module named pip")
+ return subprocess.CompletedProcess(command, 0, "", "")
+
+ monkeypatch.setattr("nanobot.optional_features.shutil.which", lambda _: "uv" if has_uv else None)
+ result = install_packages(["--force-reinstall", "--no-deps", "nanobot-ai==0.3.5"], "update", runner=run)
+ assert result.ok
+ if has_uv:
+ assert calls[1][:5] == ["uv", "pip", "install", "--python", sys.executable]
+ assert "--reinstall" in calls[1]
+ assert "--force-reinstall" not in calls[1]
+ assert "--no-deps" in calls[1]
+ else:
+ assert calls[1] == [sys.executable, "-m", "ensurepip", "--upgrade"]
+ assert calls[2] == calls[0]
+
+
+def test_installer_preserves_satisfied_dependencies():
+ runner = Mock(return_value=subprocess.CompletedProcess([], 0, "", ""))
+ assert install_packages(["nanobot-ai==0.3.5"], "update", upgrade=True, runner=runner).ok
+ command = runner.call_args.args[0]
+ assert command[:4] == [sys.executable, "-m", "pip", "install"]
+ assert command[command.index("--upgrade-strategy") + 1] == "only-if-needed"
+ assert "--force-reinstall" not in command
+
+
+def test_cli_check_is_read_only(monkeypatch):
+ monkeypatch.setattr(update, "latest_release", lambda: "9.0.0")
+ install = Mock()
+ monkeypatch.setattr(update, "update_installation", install)
+ app = typer.Typer()
+ app.command()(update_command)
+ result = CliRunner().invoke(app, ["--check"])
+ assert result.exit_code == 0
+ assert "Latest release: 9.0.0" in result.stdout
+ install.assert_not_called()
+
+
+def test_windows_launchers_are_replaced_without_overwriting_running_file(monkeypatch, tmp_path):
+ monkeypatch.setattr(sys, "platform", "win32")
+ monkeypatch.setattr(update.sysconfig, "get_path", lambda _: str(tmp_path))
+ launcher = tmp_path / "nanobot.exe"
+ launcher.write_bytes(b"old")
+ with update._release_windows_launchers():
+ assert not launcher.exists()
+ assert (tmp_path / ".nanobot.exe.update-backup").read_bytes() == b"old"
+ launcher.write_bytes(b"new")
+ assert launcher.read_bytes() == b"new"
+ assert not (tmp_path / ".nanobot.exe.update-backup").exists()
+
+
+def test_windows_launchers_are_restored_after_failed_or_noop_install(monkeypatch, tmp_path):
+ monkeypatch.setattr(sys, "platform", "win32")
+ monkeypatch.setattr(update.sysconfig, "get_path", lambda _: str(tmp_path))
+ launcher = tmp_path / "nanobot.exe"
+ launcher.write_bytes(b"old")
+ with pytest.raises(update.UpdateError):
+ with update._release_windows_launchers():
+ raise update.UpdateError("offline")
+ assert launcher.read_bytes() == b"old"
+
+
+def test_windows_recovers_launcher_left_by_interrupted_update(monkeypatch, tmp_path):
+ monkeypatch.setattr(sys, "platform", "win32")
+ monkeypatch.setattr(update.sysconfig, "get_path", lambda _: str(tmp_path))
+ (tmp_path / ".nanobot.exe.update-backup").write_bytes(b"old")
+ with update._release_windows_launchers():
+ pass
+ assert (tmp_path / "nanobot.exe").read_bytes() == b"old"
+
+
[email protected]("flag", ["--dev", "--update-dev"])
+def test_cli_dev_is_explicit(monkeypatch, flag):
+ install = Mock(return_value={"version": "0.3.5", "requires_restart": True})
+ monkeypatch.setattr(update, "update_installation", install)
+ app = typer.Typer()
+ app.command()(update_command)
+ assert CliRunner().invoke(app, [flag]).exit_code == 0
+ assert install.call_args.kwargs["dev"] is True
+
+
+def test_update_rejects_shadowed_restart_even_with_matching_metadata(isolated_update, monkeypatch):
+ monkeypatch.setattr(update, "_is_editable", lambda: False)
+ monkeypatch.setattr(update, "_checked", Mock(side_effect=[
+ json.dumps(["0.3.5", "/env/nanobot/__init__.py"]),
+ json.dumps(["0.3.5", "/checkout/nanobot/__init__.py"]),
+ ]))
+ with pytest.raises(update.UpdateError, match="restart would load a different") as error:
+ update.update_installation(output=lambda _: None)
+ assert error.value.needs_repair
+ assert update.incomplete_update()
+
+
+def test_source_release_switch_is_blocked_before_any_install(checkout, monkeypatch):
+ monkeypatch.setattr(sys, "prefix", "/test/venv")
+ monkeypatch.setattr(sys, "base_prefix", "/test/python")
+ assert "outside the checkout" in update.update_blocked_reason()
+ assert update.update_blocked_reason(dev=True) == ""
+
+
[email protected]("receipt,command", [
+ ("uv-receipt.toml", "uv tool upgrade"),
+ ("pipx_metadata.json", "pipx upgrade"),
+])
+def test_tool_manager_environment_is_not_overwritten(tmp_path, monkeypatch, receipt, command):
+ (tmp_path / receipt).write_text("owned by installer", encoding="utf-8")
+ monkeypatch.setattr(sys, "prefix", str(tmp_path))
+ assert command in update.update_blocked_reason()
+ assert command in update.update_blocked_reason(dev=True)
+
+
+def test_update_noop_does_not_install_or_require_restart(isolated_update, monkeypatch):
+ monkeypatch.setattr(update, "__version__", "0.3.5")
+ monkeypatch.setattr(update, "_is_editable", lambda: False)
+ assert not update.update_installation()["requires_restart"]
+ isolated_update.assert_not_called()
+ assert not update.incomplete_update()
+
+
+def test_preview_does_not_silently_downgrade_to_stable(isolated_update, monkeypatch):
+ monkeypatch.setattr(update, "__version__", "0.3.6.dev2026101001")
+ with pytest.raises(update.UpdateError, match="allow-downgrade"):
+ update.update_installation()
+ isolated_update.assert_not_called()
+ assert not update.incomplete_update()
+ monkeypatch.setattr(update, "_is_editable", lambda: False)
+ assert update.update_installation(allow_downgrade=True)["requires_restart"]
+ assert not update.incomplete_update()
+
+
+def test_failed_install_retains_marker_until_successful_retry(isolated_update, monkeypatch):
+ monkeypatch.setattr(update, "_is_editable", lambda: False)
+ isolated_update.side_effect = update.UpdateError("package install failed")
+ with pytest.raises(update.UpdateError, match="No automatic rollback") as error:
+ update.update_installation()
+ assert error.value.needs_repair
+ assert update.incomplete_update()
+ isolated_update.side_effect = None
+ update.update_installation()
+ assert not update.incomplete_update()
+
+
+def test_legacy_retry_cannot_replace_an_exact_worker_job(isolated_update):
+ marker = pending_update_path()
+ marker.parent.mkdir(parents=True)
+ marker.write_text('{"schema_version":2,"job_id":"an-exact-job","version":"0.3.5"}')
+ with pytest.raises(update.UpdateError, match="saved update job") as error:
+ update.update_installation()
+ assert error.value.needs_repair
+ isolated_update.assert_not_called()
+ assert marker.exists()
+
+
+def test_source_preflight_failure_does_not_mark_installation_modified(checkout, isolated_update, monkeypatch):
+ root, _ = checkout
+ (root / "file").write_text("my edits", encoding="utf-8")
+ monkeypatch.setattr(update, "ensure_bun", lambda **kwargs: "bun")
+ with pytest.raises(update.UpdateError, match="local changes") as error:
+ update.update_installation(dev=True)
+ assert not error.value.needs_repair
+ assert not update.incomplete_update()
+
+
+def test_real_python_restart_resolution_detects_cwd_shadowing(tmp_path, monkeypatch):
+ """Exercise real import lookup without installing or changing the user's env."""
+ import venv
+
+ env = tmp_path / "env"
+ venv.EnvBuilder(with_pip=False).create(env)
+ executable = env / ("Scripts/python.exe" if sys.platform == "win32" else "bin/python")
+ site = Path(subprocess.check_output([
+ str(executable), "-I", "-c", "import sysconfig; print(sysconfig.get_path('purelib'))",
+ ], text=True).strip())
+ package = site / "nanobot"
+ package.mkdir()
+ (package / "__init__.py").write_text("__version__ = '0.3.5'\n", encoding="utf-8")
+ checkout = tmp_path / "source"
+ (checkout / "nanobot").mkdir(parents=True)
+ # Matching metadata is the original bug: the old code can report a new version.
+ (checkout / "nanobot/__init__.py").write_text("__version__ = '0.3.5'\n", encoding="utf-8")
+ monkeypatch.setattr(sys, "executable", str(executable))
+ monkeypatch.chdir(checkout)
+ with pytest.raises(update.UpdateError, match="different nanobot package"):
+ update._verify_installation("0.3.5", "pypi")
+ monkeypatch.chdir(tmp_path)
+ monkeypatch.delenv("PYTHONPATH", raising=False)
+ update._verify_installation("0.3.5", "pypi")
+
+
+def installed_release(tmp_path, monkeypatch):
+ """Install a tiny local wheel with real pip, without touching the user's env."""
+ import venv
+ import zipfile
+
+ env = tmp_path / "env"
+ venv.EnvBuilder(with_pip=True).create(env)
+ executable = env / ("Scripts/python.exe" if sys.platform == "win32" else "bin/python")
+ wheels = tmp_path / "wheels"
+ wheels.mkdir()
+ files = {
+ "nanobot/__init__.py": "__version__ = '0.3.5'\n",
+ "nanobot/web/dist/index.html": "<html>bundled UI</html>",
+ "nanobot_ai-0.3.5.dist-info/METADATA": "Metadata-Version: 2.1\nName: nanobot-ai\nVersion: 0.3.5\n",
+ "nanobot_ai-0.3.5.dist-info/WHEEL": "Wheel-Version: 1.0\nRoot-Is-Purelib: true\nTag: py3-none-any\n",
+ }
+ record = "nanobot_ai-0.3.5.dist-info/RECORD"
+ files[record] = "".join(f"{name},,\n" for name in [*files, record])
+ with zipfile.ZipFile(wheels / "nanobot_ai-0.3.5-py3-none-any.whl", "w") as wheel:
+ for name, content in files.items():
+ wheel.writestr(name, content)
+ monkeypatch.setenv("PIP_NO_INDEX", "1")
+ monkeypatch.setenv("PIP_FIND_LINKS", str(wheels))
+ monkeypatch.setenv("PIP_DISABLE_PIP_VERSION_CHECK", "1")
+ monkeypatch.setenv("PIP_CONFIG_FILE", os.devnull)
+ monkeypatch.setenv("PIP_NO_CACHE_DIR", "1")
+ for name in ("PIP_TARGET", "PIP_PREFIX", "PIP_USER"):
+ monkeypatch.delenv(name, raising=False)
+ monkeypatch.delenv("PYTHONPATH", raising=False)
+ monkeypatch.chdir(tmp_path)
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ monkeypatch.setattr(sys, "executable", str(executable))
+ monkeypatch.setattr(sys, "prefix", str(env))
+ get_path = update.sysconfig.get_path
+ monkeypatch.setattr(update.sysconfig, "get_path", lambda name, *args, **kwargs: (
+ str(env / "Scripts") if name == "scripts" else get_path(name, *args, **kwargs)
+ ))
+ monkeypatch.setattr(update, "latest_release", lambda: "0.3.5")
+ monkeypatch.setattr(update, "__version__", "0.3.5")
+ monkeypatch.setattr(update, "update_blocked_reason", lambda **kwargs: "")
+ monkeypatch.setattr(update, "_is_editable", lambda: False)
+ update._install(["nanobot-ai==0.3.5"])
+ site = Path(subprocess.check_output([
+ str(executable), "-I", "-c", "import sysconfig; print(sysconfig.get_path('purelib'))",
+ ], text=True).strip())
+ return site / "nanobot/web/dist/index.html"
+
+
+def test_retry_restores_missing_same_version_package_files(installed_release):
+ """A terminated install can leave valid metadata but incomplete application files."""
+ asset = installed_release
+ asset.unlink()
+ update._mark_installing()
+
+ result = update.update_installation(output=lambda _: None)
+
+ assert asset.read_text() == "<html>bundled UI</html>"
+ assert result["requires_restart"]
+ assert not update.incomplete_update()
+
+
+def test_old_gateway_cannot_downgrade_a_newer_shared_installation(installed_release, monkeypatch):
+ # Another process has upgraded the shared environment since this gateway started.
+ monkeypatch.setattr(update, "__version__", "0.3.3")
+ monkeypatch.setattr(update, "latest_release", lambda: "0.3.4")
+ install = Mock(wraps=update._install)
+ monkeypatch.setattr(update, "_install", install)
+ with pytest.raises(update.UpdateError, match="allow-downgrade"):
+ update.update_installation(output=lambda _: None)
+ install.assert_not_called()
+ assert installed_release.is_file()
+ assert not update.incomplete_update()
+
+
+def test_old_gateway_requires_restart_after_external_update(installed_release, monkeypatch):
+ monkeypatch.setattr(update, "__version__", "0.3.4")
+ install = Mock()
+ monkeypatch.setattr(update, "_install", install)
+ result = update.update_installation(output=lambda _: None)
+ assert result["version"] == "0.3.5" and result["requires_restart"]
+ install.assert_not_called()
diff --git a/tests/test_update_backup.py b/tests/test_update_backup.py
new file mode 100644
index 000000000..cffedbaa0
--- /dev/null
+++ b/tests/test_update_backup.py
@@ -0,0 +1,204 @@
+"""Scoped snapshots preserve real data and never silently expand read authority."""
+
+import hashlib
+import json
+import os
+from pathlib import Path
+from types import SimpleNamespace
+from zipfile import ZipFile
+
+import pytest
+
+from nanobot import update_backup
+from nanobot.data_access import profile_data_paths
+from nanobot.update_backup import (
+ BackupSource,
+ ensure_backup,
+ unique_sources,
+ verify_backup,
+)
+
+
+def scoped_data(tmp_path):
+ home, data, workspace, job = (tmp_path / name for name in ("home", "config data", "user project", "job"))
+ for path in (home, data, workspace, job):
+ path.mkdir()
+ files = {
+ data / "custom.json": '{"credential":"private fixture"}',
+ data / "sessions/workspace/session.jsonl": '{"content":"original conversation"}\n',
+ data / "webui/transcript.jsonl": '{"content":"UI history"}\n',
+ data / "media/image.txt": "fixture attachment",
+ data / "auth/mcp.json": '{"fixture":"secret"}',
+ data / "cli-apps/installed.json": '{"apps":[]}',
+ workspace / "memory/history.jsonl": '{"memory":"original"}\n',
+ workspace / ".nanobot/workspace-id": "namespace",
+ workspace / "cron/jobs.json": '{"jobs":[]}',
+ workspace / "skills/custom/SKILL.md": "user skill",
+ home / "sessions/legacy.jsonl": "legacy conversation",
+ }
+ for path, content in files.items():
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_bytes(content.encode())
+ # Paths intentionally excluded: arbitrary project data and installed binaries.
+ for path in (workspace / "src/private.py", data / "bin/cua", data / "logs/runtime.log",
+ data / "cli-apps/venvs/application/binary"):
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text("not part of this backup")
+ paths = profile_data_paths(home=home, data_dir=data, config=data / "custom.json", workspace=workspace)
+ sources = unique_sources([BackupSource(str(path)) for path in paths])
+ return job, sources, files
+
+
+def test_complete_private_snapshot_contains_only_owned_stores_and_keeps_original(scoped_data):
+ job, sources, files = scoped_data
+ archive = ensure_backup(job, sources, "a" * 64, mutated=False)
+ with ZipFile(archive) as bundle:
+ manifest = json.loads(bundle.read("manifest.json"))
+ entries = {entry["path"]: entry for entry in manifest["entries"]}
+ assert {path for path, entry in entries.items() if entry["kind"] == "file"} == {str(path) for path in files}
+ for path, content in files.items():
+ entry = entries[str(path)]
+ actual = bundle.read(entry["member"])
+ assert actual == content.encode()
+ assert hashlib.sha256(actual).hexdigest() == entry["sha256"]
+ assert any(item["kind"] == "missing" for item in entries.values())
+ original = archive.read_bytes()
+ next(iter(files)).write_text("changed after installation or migration")
+ with pytest.raises(ValueError, match="before installation"):
+ ensure_backup(job, sources, "a" * 64, mutated=False)
+ assert ensure_backup(job, sources, "a" * 64, mutated=True) == archive
+ assert archive.read_bytes() == original
+ assert verify_backup(job, sources, "a" * 64) == archive
+ if os.name != "nt":
+ assert archive.stat().st_mode & 0o777 == 0o600
+ assert archive.parent.stat().st_mode & 0o777 == 0o700
+ assert (archive.parent / "receipt.json").stat().st_mode & 0o777 == 0o600
+ with pytest.raises(ValueError, match="different update"):
+ verify_backup(job, sources, "b" * 64)
+
+
[email protected](os.name == "nt", reason="Symlink creation requires separate Windows privileges")
+def test_backup_refuses_external_symlink_and_special_file(scoped_data, tmp_path):
+ job, sources, files = scoped_data
+ memory = next(path.parent for path in files if path.name == "history.jsonl")
+ external = tmp_path / "unrelated-private-file"
+ external.write_text("not authorized by the selected scope")
+ link = memory / "external"
+ link.symlink_to(external)
+ with pytest.raises(ValueError, match="symlink"):
+ ensure_backup(job, sources, "a" * 64, mutated=False)
+ assert not (job / "backup").exists()
+ link.unlink()
+ os.mkfifo(link)
+ with pytest.raises(ValueError, match="special file"):
+ ensure_backup(job, sources, "a" * 64, mutated=False)
+ assert not (job / "backup").exists()
+
+
+def test_backup_failure_keeps_incomplete_attempt_and_retries_without_false_completion(scoped_data, monkeypatch):
+ job, sources, files = scoped_data
+ original_inventory = update_backup._inventory
+ calls = 0
+
+ def change_during_copy(scope):
+ nonlocal calls
+ calls += 1
+ if calls == 2:
+ next(iter(files)).write_text("concurrent writer changed data")
+ return original_inventory(scope)
+
+ with monkeypatch.context() as patch:
+ patch.setattr(update_backup, "_inventory", change_during_copy)
+ with pytest.raises(ValueError, match="changed during backup"):
+ ensure_backup(job, sources, "a" * 64, mutated=False)
+ assert not (job / "backup").exists()
+ assert len(list(job.glob(".backup-*"))) == 1
+ archive = ensure_backup(job, sources, "a" * 64, mutated=False)
+ assert archive.exists()
+ assert len(list(job.glob(".backup-*"))) == 1 # Do not delete previous recovery material.
+ archive.write_bytes(archive.read_bytes() + b"corruption")
+ with pytest.raises(ValueError, match="missing or changed"):
+ ensure_backup(job, sources, "a" * 64, mutated=True)
+
+
+def test_no_space_and_missing_original_backup_block_before_snapshot(scoped_data, monkeypatch):
+ job, sources, _ = scoped_data
+ monkeypatch.setattr(update_backup.shutil, "disk_usage", lambda _: SimpleNamespace(free=0))
+ with pytest.raises(ValueError, match="Not enough space"):
+ ensure_backup(job, sources, "a" * 64, mutated=False)
+ assert not list(job.iterdir())
+ with pytest.raises(ValueError, match="already changed data"):
+ ensure_backup(job, sources, "a" * 64, mutated=True)
+
+
+def test_scheduled_delivery_is_backed_up_and_changes_block_program_rollback(tmp_path):
+ from nanobot.bus.delivery import DeliveryRequest
+ from nanobot.bus.events import OutboundMessage
+ from nanobot.channels.outbox import DeliveryOutbox
+
+ data, job = tmp_path / "data", tmp_path / "job"
+ job.mkdir()
+ outbox = DeliveryOutbox(data / "delivery/outbox.sqlite3")
+ message = OutboundMessage("whatsapp", "chat", "undelivered scheduled result",
+ delivery=DeliveryRequest("run", "whatsapp:chat", None))
+ outbox.record(message)
+ sources = unique_sources([BackupSource(str(path)) for path in profile_data_paths(
+ home=tmp_path / "home", data_dir=data, config=data / "config.json", workspace=tmp_path / "workspace",
+ )])
+ archive = ensure_backup(job, sources, "a" * 64, mutated=False)
+ with ZipFile(archive) as bundle:
+ entry = next(item for item in json.loads(bundle.read("manifest.json"))["entries"]
+ if item["path"] == str(outbox.path))
+ saved = bundle.read(entry["member"])
+ assert saved == outbox.path.read_bytes()
+ copied = tmp_path / "retained-outbox.sqlite3"
+ copied.write_bytes(saved)
+ assert DeliveryOutbox(copied).ready()[0].content == message.content
+ outbox.finish(message, "sent")
+ with pytest.raises(ValueError, match="changed"):
+ verify_backup(job, sources, "a" * 64, unchanged=True)
+ assert outbox.ready() == [] # Never replace the live store with the old backup.
+
+
+def test_scope_cannot_include_its_own_job(tmp_path):
+ job = tmp_path / "sessions/job"
+ job.mkdir(parents=True)
+ with pytest.raises(ValueError, match="job itself"):
+ ensure_backup(job, (BackupSource(str(tmp_path / "sessions")),), "a" * 64, mutated=False)
+
+
+async def test_scoped_backup_reopens_sqlite_history_after_runtime_drain(tmp_path):
+ from nanobot.session.manager import SessionManager
+
+ data, workspace, job = (tmp_path / name for name in ("data", "workspace", "job"))
+ job.mkdir()
+ manager = SessionManager(workspace, sessions_root=data / "sessions")
+ session = manager.get_or_create("cli:backup")
+ session.add_message("user", "original conversation")
+ manager.save(session)
+ await manager.state.aclose()
+
+ sources = unique_sources([BackupSource(str(path)) for path in profile_data_paths(
+ home=tmp_path / "home", data_dir=data, config=data / "config.json", workspace=workspace,
+ )])
+ archive = ensure_backup(job, sources, "a" * 64, mutated=False)
+ restored_root = tmp_path / "restored-sessions"
+ # Reopen the real database from the scoped archive, not a JSONL stand-in.
+ with ZipFile(archive) as bundle:
+ manifest = json.loads(bundle.read("manifest.json"))
+ for entry in manifest["entries"]:
+ source = Path(entry["path"])
+ if entry["kind"] != "file" or not source.is_relative_to(data / "sessions"):
+ continue
+ target = restored_root / source.relative_to(data / "sessions")
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_bytes(bundle.read(entry["member"]))
+ restored = SessionManager(workspace, sessions_root=restored_root)
+ try:
+ snapshot = restored.read_session_snapshot("cli:backup")
+ assert snapshot is not None
+ assert snapshot.messages[0]["content"] == "original conversation"
+ assert verify_backup(job, sources, "a" * 64, unchanged=True) == archive
+ finally:
+ await restored.state.aclose()
diff --git a/tests/test_update_channels.py b/tests/test_update_channels.py
new file mode 100644
index 000000000..c84834ad2
--- /dev/null
+++ b/tests/test_update_channels.py
@@ -0,0 +1,89 @@
+"""Subscription persistence and update ownership, without touching user installs."""
+
+import sys
+import time
+from pathlib import Path
+from uuid import uuid4
+
+import pytest
+
+from nanobot.config.home import get_selected_home_path, set_home_path
+from nanobot.installation_lock import file_access, installation_state_dir, pending_update_path
+from nanobot.update_channel import (
+ UpdateChannelRequest,
+ read_update_channel,
+ validate_channel_revision,
+)
+from nanobot.update_service import UpdateJobService
+from nanobot.update_worker import JobStatus, Phase
+
+
+def environment(tmp_path, monkeypatch):
+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path / "account"))
+ monkeypatch.setattr(sys, "prefix", str(tmp_path / "installation"))
+ return installation_state_dir()
+
+
+def change(channel, revision):
+ return UpdateJobService().change_channel(UpdateChannelRequest(channel=channel, revision=revision))
+
+
+def test_channel_is_installation_owned_persistent_and_revision_bound(environment, tmp_path, monkeypatch):
+ assert read_update_channel().channel == "stable"
+ assert not (environment / "channel.json").exists()
+ selected = change("preview", 0)
+ assert (selected.channel, selected.revision) == ("preview", 1)
+ # A second profile/process view retains the subscription, not a browser cache.
+ original_home = get_selected_home_path()
+ try:
+ set_home_path(tmp_path / "another-profile")
+ assert read_update_channel() == selected
+ finally:
+ set_home_path(original_home)
+ assert change("preview", 1) == selected
+ with pytest.raises(ValueError, match="another client"):
+ change("stable", 0)
+ assert change("stable", 1).revision == 2
+ with pytest.raises(ValueError, match="channel changed"):
+ validate_channel_revision(0, sys.prefix) # Stable → Preview → Stable is not the old consent.
+ monkeypatch.setattr(sys, "prefix", str(tmp_path / "other-installation"))
+ assert read_update_channel().revision == 0
+ assert not (environment / "jobs").exists(), "Changing channels must not create an installation job"
+
+
[email protected]("lock", ["channel.lock", "preparation-controller.lock"])
+def test_channel_change_does_not_race_an_active_preparer(environment, lock):
+ with file_access(environment / lock, exclusive=True), pytest.raises(BlockingIOError):
+ change("preview", 0)
+ assert read_update_channel().revision == 0
+ assert change("preview", 0).revision == 1
+
+
[email protected]("phase,mutation", [(Phase.PREPARING, False), (Phase.CHECKING, False),
+ (Phase.STOPPING, False), (Phase.FAILED, True),
+ (Phase.RESTART_FAILED, True)])
+def test_active_and_failed_mutation_jobs_require_recovery_before_switch(environment, phase, mutation):
+ identifier = str(uuid4())
+ directory = environment / "jobs" / identifier
+ directory.mkdir(parents=True)
+ JobStatus(identifier, phase, 1, mutation, "Private diagnostic", int(time.time())).save(directory)
+ before = (directory / "status.json").read_bytes()
+ with pytest.raises(ValueError, match="recover"):
+ change("preview", 0)
+ assert read_update_channel().revision == 0
+ assert (directory / "status.json").read_bytes() == before
+
+
+def test_incomplete_install_and_corrupt_preference_are_not_silently_reset(environment):
+ pending = pending_update_path()
+ pending.parent.mkdir(parents=True)
+ pending.write_text("interrupted")
+ with pytest.raises(ValueError, match="Recover"):
+ change("preview", 0)
+ pending.unlink()
+ (environment / "channel.json").write_text('{"channel":"unknown"}')
+ with pytest.raises(ValueError):
+ read_update_channel()
+ with pytest.raises(ValueError):
+ change("preview", 0)
diff --git a/tests/test_update_guidance.py b/tests/test_update_guidance.py
new file mode 100644
index 000000000..1de5dea37
--- /dev/null
+++ b/tests/test_update_guidance.py
@@ -0,0 +1,119 @@
+import shlex
+from pathlib import Path
+
+import pytest
+
+from nanobot import update_guidance
+from nanobot.update_guidance import installation_method, shell_command, update_guide
+from nanobot.update_manager import ManagerPolicy
+from nanobot.update_plan import InstallationSnapshot
+
+
+def installation(tmp_path, owner="venv", **policy):
+ environment = tmp_path / "tools" / "nanobot-ai" if owner == "uv" else tmp_path / "pipx" / "venvs" / "nanobot-ai-work"
+ return InstallationSnapshot(
+ environment=str(environment), python=str(environment / "bin" / "python"),
+ package_path=str(tmp_path / "checkout" / "nanobot" / "__init__.py"),
+ installed_version="0.3.6", running_version="0.3.6", running_package=str(tmp_path / "checkout" / "nanobot" / "__init__.py"),
+ owner=owner, records={}, manager=ManagerPolicy(
+ manager=owner, backend="uv" if owner == "uv" else "pip", extras=["matrix"], source="registry", **policy,
+ ) if owner in {"uv", "pipx"} else None,
+ )
+
+
[email protected]("owner", ["uv", "pipx"])
+def test_registry_commands_bind_manager_environment_and_preserve_suffix(tmp_path, monkeypatch, owner):
+ binary = str(tmp_path / "bin" / owner)
+ monkeypatch.setattr(update_guidance.shutil, "which", lambda _: binary)
+ snapshot = installation(tmp_path, owner)
+ guide = update_guide(snapshot, "0.3.7", extras=["matrix"])
+ assert guide.method == owner
+ assert guide.reason == "registry"
+ assert binary in guide.update_command
+ assert Path(snapshot.environment).name in guide.update_command
+ assert ("UV_TOOL_DIR" if owner == "uv" else "PIPX_HOME") in guide.update_command
+ assert guide.inspect_command and "list" in guide.inspect_command
+ assert snapshot.python in guide.verify_command
+ assert "--force" not in guide.update_command and "pip install" not in guide.update_command
+
+
[email protected]("policy", [{"pinned": True}, {"locked": True}, {"version_constraint": "<0.3.7"}])
[email protected]("owner", ["uv", "pipx"])
+def test_restricted_manager_has_inspection_but_no_update(tmp_path, monkeypatch, owner, policy):
+ monkeypatch.setattr(update_guidance.shutil, "which", lambda name: name)
+ guide = update_guide(installation(tmp_path, owner, **policy), "0.3.7", extras=[])
+ assert guide.reason == "policy" and guide.inspect_command and guide.update_command is None
+
+
[email protected]("policy", [{"version_constraint": ">=0.3.4,<0.4"}, {"custom_pip_args": True}])
+def test_pipx_in_range_target_still_requires_preserving_owner_options(tmp_path, monkeypatch, policy):
+ monkeypatch.setattr(update_guidance.shutil, "which", lambda name: name)
+ guide = update_guide(installation(tmp_path, "pipx", **policy), "0.3.7", extras=[])
+ assert guide.reason == "policy" and guide.update_command is None
+ assert guide.inspect_command and guide.verify_command
+
+
[email protected]("owner", ["uv", "pipx"])
+def test_preview_fixed_source_and_missing_manager_never_guess_upgrade(tmp_path, monkeypatch, owner):
+ monkeypatch.setattr(update_guidance.shutil, "which", lambda name: name)
+ snapshot = installation(tmp_path, owner)
+ assert update_guide(snapshot, "0.3.7.dev1", extras=[]).reason == "preview"
+ assert update_guide(snapshot, "0.3.7.dev1", extras=[]).update_command is None
+ snapshot = snapshot.model_copy(update={"manager": snapshot.manager.model_copy(update={"source": "artifact"})})
+ assert update_guide(snapshot, "0.3.7", extras=[]).update_command is None
+ monkeypatch.setattr(update_guidance.shutil, "which", lambda _: None)
+ assert update_guide(snapshot, "0.3.7", extras=[]).reason == "manager"
+
+
+def test_pip_requires_known_extras_and_uses_exact_interpreter(tmp_path):
+ snapshot = installation(tmp_path)
+ assert installation_method(snapshot) == "pip"
+ unknown = update_guide(snapshot, "0.3.7", extras=None)
+ assert unknown.reason == "extras" and unknown.update_command is None
+ assert "importlib.metadata" in unknown.inspect_command
+ assert "-m pip" not in unknown.inspect_command
+ known = update_guide(snapshot, "0.3.7", extras=["matrix"])
+ assert snapshot.python in known.update_command
+ assert "nanobot-ai[matrix]==0.3.7" in known.update_command
+ snapshot.records["nanobot-install.json"] = "a" * 64
+ assert installation_method(snapshot) == "managed"
+
+
[email protected]("owner", ["source", "container", "system"])
+def test_deployments_do_not_get_guessed_install_or_restart_commands(tmp_path, owner):
+ guide = update_guide(installation(tmp_path, owner), "0.3.7", extras=[])
+ assert guide.reason == owner and guide.update_command is None
+ if owner == "container":
+ assert guide.verify_command is None
+ if owner == "source":
+ assert "status" in guide.inspect_command and str(tmp_path / "checkout") in guide.inspect_command
+
+
+def test_source_guide_inspects_the_running_checkout_not_a_different_installed_package(tmp_path):
+ snapshot = installation(tmp_path, "source").model_copy(update={"package_path": str(tmp_path / "site-packages" / "nanobot" / "__init__.py")})
+ guide = update_guide(snapshot, "0.3.7", extras=[])
+ assert str(tmp_path / "checkout") in guide.inspect_command
+ assert "site-packages" not in guide.inspect_command
+
+
+def test_stale_review_and_non_upgrade_cannot_generate_install_commands(tmp_path):
+ snapshot = installation(tmp_path)
+ assert update_guide(snapshot, "0.3.7", extras=[], current=False).update_command is None
+ for target in ["0.3.6", "0.3.5"]:
+ assert update_guide(snapshot, target, extras=[]).update_command is None
+
+
+def test_updated_files_with_old_running_gateway_only_offer_restart_verification(tmp_path):
+ snapshot = installation(tmp_path).model_copy(update={"installed_version": "0.3.7"})
+ guide = update_guide(snapshot, "0.3.7", extras=[])
+ assert guide.reason == "restart" and guide.verify_command and guide.update_command is None
+
+
+def test_shell_rendering_quotes_paths_and_restores_powershell_environment():
+ args = ["/a b/$not-expanded/python", "-m", "pip", "show", "nanobot-ai"]
+ environment = ("PIPX_HOME", "/some one's/$directory")
+ assert shlex.split(shell_command(args, windows=False, environment=environment)) == ["env", "PIPX_HOME=/some one's/$directory", *args]
+ command = shell_command(args, windows=True, environment=environment)
+ assert "'/some one''s/$directory'" in command
+ assert "finally { $env:PIPX_HOME = $nanobotPrevious }" in command
+ assert "& '/a b/$not-expanded/python'" in command
diff --git a/tests/test_update_jobs.py b/tests/test_update_jobs.py
new file mode 100644
index 000000000..c874de48f
--- /dev/null
+++ b/tests/test_update_jobs.py
@@ -0,0 +1,2330 @@
+"""Real offline pip jobs in disposable venvs; no user installation is mutated."""
+
+import asyncio
+import base64
+import hashlib
+import json
+import os
+import shlex
+import signal
+import subprocess
+import sys
+import threading
+import time
+import venv
+from dataclasses import replace
+from pathlib import Path, PureWindowsPath
+from unittest.mock import AsyncMock
+from uuid import uuid4
+from zipfile import ZipFile
+
+import httpx
+import pytest
+from packaging.tags import sys_tags
+
+from nanobot.config.home import get_selected_home_path, set_home_path
+from nanobot.data_access import data_access
+from nanobot.gateway.runtime import GatewayInstance, GatewayRuntime
+from nanobot.installation_lock import (
+ InstallationBusyError,
+ file_access,
+ installation_access,
+ installation_state_dir,
+ pending_update_path,
+)
+from nanobot.process_runtime import process_is_running
+from nanobot.release_feed import CATALOGUE_URL, ReleaseFeed, ReleaseTarget
+from nanobot.releases import (
+ PLATFORMS,
+ ReleaseArtifact,
+ ReleaseCatalogue,
+ ReleaseManifest,
+ ReleasePointer,
+ release_filenames,
+)
+from nanobot.update_backup import BackupSource
+from nanobot.update_channel import UpdateChannelRequest, read_update_channel
+from nanobot.update_jobs import (
+ _recovery_command,
+ prepare_job,
+ retry_handoff,
+ settle_interrupted_preparation,
+ start_handoff,
+ start_job,
+)
+from nanobot.update_plan import InstallationSnapshot, UpdatePlan, UpdatePlans
+from nanobot.update_process import PreparationProcess, inspect_python_environment
+from nanobot.update_profiles import inspect_profiles, record_gateway_profile
+from nanobot.update_service import UpdateJobService
+from nanobot.update_worker import (
+ ExecutionConfirmation,
+ JobStatus,
+ Phase,
+ WorkerSpec,
+ cancel_job,
+ inspect_environment,
+ read_record,
+ write_record,
+)
+
+_RESTART_PROBE = """
+# Synthetic installed handoff for worker/lease routing, not gateway readiness.
+import time
+from pathlib import Path
+import nanobot
+from _nanobot_update.data_access import data_access
+from _nanobot_update.installation_lock import InstallationBusyError, installation_access, pending_update_path
+from _nanobot_update.update_worker import JobStatus, Phase, WorkerSpec, write_record
+
+def run_gateway(directory, participant):
+ raise AssertionError('This routing fixture must not launch a gateway')
+
+def run_restarts(directory):
+ spec = WorkerSpec.read(directory)
+ status = JobStatus.read(directory)
+ assert status.phase in {Phase.RESTARTING, Phase.RESTART_FAILED}
+ with installation_access(allow_incomplete=True):
+ try:
+ with installation_access(updating=True):
+ raise AssertionError('Runtime bridge has no shared installation lease')
+ except InstallationBusyError:
+ pass
+ with data_access((item.path for item in spec.backup_sources), job_id=spec.plan_id) as data:
+ write_record(directory / 'handoff-probe.json', {
+ 'version': nanobot.__version__, 'package': str(Path(nanobot.__file__).resolve()),
+ 'attempt': status.attempt, 'phase': status.phase.value,
+ })
+ if (directory / 'fail-restart').exists():
+ raise RuntimeError('Controlled handoff failure')
+ JobStatus(spec.plan_id, Phase.FINALIZING, status.attempt, True,
+ 'Synthetic routing complete; not real gateway evidence', int(time.time())).save(directory)
+ data.release_reservation()
+ pending_update_path().unlink()
+ JobStatus(spec.plan_id, Phase.SUCCEEDED, status.attempt, True,
+ 'Synthetic routing complete; not real gateway evidence', int(time.time())).save(directory)
+"""
+
+
+_HANDOFF_PROBE = """
+# Synthetic old-runtime preflight; release/stop contracts are tested separately.
+import time
+import traceback
+from _nanobot_update.installation_lock import InstallationBusyError, installation_access
+from _nanobot_update.update_worker import JobStatus, Phase, WorkerSpec, write_record
+
+def prepare_handoff(directory):
+ try:
+ _prepare_handoff(directory)
+ except Exception:
+ # Keep subprocess failures visible in CI without changing the real
+ # worker's deliberately sanitized output or capturing user data.
+ (directory / 'preflight-error.txt').write_text(traceback.format_exc())
+ raise
+
+def _prepare_handoff(directory):
+ spec = WorkerSpec.read(directory)
+ try:
+ with installation_access(updating=True):
+ raise AssertionError('Old runtime imported before taking its lease')
+ except InstallationBusyError:
+ pass
+ write_record(directory / 'preflight-entered.json', {'plan_id': spec.plan_id})
+ deadline = time.monotonic() + 20
+ while (directory / 'pause-preflight').exists() and time.monotonic() < deadline:
+ time.sleep(0.02)
+ if (directory / 'pause-preflight').exists():
+ raise RuntimeError('Timed out waiting for the test to release preflight')
+ if (directory / 'refuse-preflight').exists():
+ JobStatus(spec.plan_id, Phase.HANDOFF_FAILED, 0, False,
+ 'Controlled preflight refusal', int(time.time())).save(directory)
+ raise RuntimeError('Controlled preflight refusal')
+ JobStatus(spec.plan_id, Phase.STOPPING, 0, False,
+ 'Synthetic preflight complete', int(time.time())).save(directory)
+"""
+
+
+def wheel(directory, name, version, *, requires=(), platform="any", broken=False, restart=False, handoff=False,
+ extras=(), entrypoint=False, restart_contract=b'{"schema_version":1,"handoff_protocols":[1]}'):
+ package = name.replace("-", "_")
+ dist = f"{package}-{version}.dist-info"
+ files = {
+ f"{package if name != 'nanobot-ai' else 'nanobot'}/__init__.py": f"__version__ = '{version}'\n".encode(),
+ f"{dist}/METADATA": (f"Metadata-Version: 2.1\nName: {name}\nVersion: {version}\n"
+ + "".join(f"Provides-Extra: {extra}\n" for extra in extras)
+ + "".join(f"Requires-Dist: {requirement}\n" for requirement in requires)).encode(),
+ f"{dist}/WHEEL": f"Wheel-Version: 1.0\nRoot-Is-Purelib: true\nTag: py3-none-{platform}\n".encode(),
+ }
+ if name == "nanobot-ai":
+ if entrypoint:
+ files["nanobot/__init__.py"] += b"def main(): pass\n"
+ files[f"{dist}/entry_points.txt"] = b"[console_scripts]\nnanobot = nanobot:main\n"
+ if broken:
+ files["nanobot/__init__.py"] = b"raise RuntimeError('broken release fixture')\n"
+ files["nanobot/web/dist/index.html"] = f"verified UI {version}".encode()
+ files["nanobot/tui/bin/fixture"] = b"fixture, not a native execution claim"
+ if restart:
+ files["nanobot/update_restart.py"] = _RESTART_PROBE.encode()
+ if restart_contract is not None:
+ files["nanobot/update_contract.json"] = restart_contract
+ if handoff:
+ files["nanobot/update_handoff.py"] = _HANDOFF_PROBE.encode()
+ records = []
+ for filename, data in files.items():
+ digest = base64.urlsafe_b64encode(hashlib.sha256(data).digest()).rstrip(b"=").decode()
+ records.append(f"{filename},sha256={digest},{len(data)}")
+ files[f"{dist}/RECORD"] = ("\n".join(records) + f"\n{dist}/RECORD,,\n").encode()
+ path = directory / f"{package}-{version}-py3-none-{platform}.whl"
+ with ZipFile(path, "w") as archive:
+ for filename, data in files.items():
+ archive.writestr(filename, data)
+ return path
+
+
+def test_planning_probe_bootstraps_before_target_site(tmp_path, monkeypatch):
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.setenv("USERPROFILE", str(tmp_path))
+ result = inspect_python_environment(
+ sys.executable, str(Path(sys.prefix).resolve()), "print('protected inspection')",
+ )
+ assert result.returncode == 0, result.stderr
+ assert result.stdout.strip() == "protected inspection"
+
+
+def installation(tmp_path, monkeypatch, request):
+ # Synthetic local packages are not signed public releases. Approval refusal
+ # is covered through the real feed in test_release_trust.py.
+ monkeypatch.setattr(ReleaseFeed, "_authorize", AsyncMock())
+ state_home = tmp_path / "private home"
+ state_home.mkdir()
+ monkeypatch.setenv("HOME", str(state_home))
+ monkeypatch.setenv("USERPROFILE", str(state_home))
+ artifacts = tmp_path / "artifacts"
+ artifacts.mkdir()
+ environment = tmp_path / "venv with spaces"
+ venv.EnvBuilder(with_pip=True).create(environment)
+ python = str(environment / ("Scripts/python.exe" if os.name == "nt" else "bin/python"))
+ monkeypatch.setenv("PIP_CONFIG_FILE", os.devnull)
+ monkeypatch.setenv("PIP_NO_INDEX", "1")
+ monkeypatch.setenv("PIP_FIND_LINKS", str(artifacts))
+ for version in ("1.0.0", "2.0.0"):
+ wheel(artifacts, "fixture-update-dep", version)
+ mode = getattr(request, "param", False)
+ versions = ("0.3.4", "0.3.5")
+ restart_contract = b'{"schema_version":1,"handoff_protocols":[1]}'
+ if isinstance(mode, dict):
+ versions = mode.get("versions", versions)
+ restart_contract = mode.get("restart_contract", restart_contract)
+ mode = "handoff" if "restart_contract" in mode else False
+ previous_version, next_version = versions
+ previous = wheel(artifacts, "nanobot-ai", previous_version, requires=["fixture-update-dep==1.0.0"],
+ handoff=mode == "handoff")
+ subprocess.run([python, "-I", "-m", "pip", "install", "--disable-pip-version-check", str(previous)],
+ check=True, capture_output=True, timeout=60)
+ platform = next(tag.platform for tag in sys_tags() if tag.platform in PLATFORMS.values())
+ candidate = wheel(artifacts, "nanobot-ai", next_version, requires=["fixture-update-dep>=2.0.0"], platform=platform,
+ broken=mode is True,
+ restart=mode in ("restart", "handoff"),
+ restart_contract=restart_contract)
+ baseline = inspect_environment(python)
+ site = Path(subprocess.check_output([python, "-I", "-c", "import sysconfig; print(sysconfig.get_path('purelib'))"], text=True).strip())
+ snapshot = InstallationSnapshot(
+ environment=str(environment.resolve()), python=python, installed_version=previous_version, running_version=previous_version,
+ package_path=str(site / "nanobot/__init__.py"), running_package=str(site / "nanobot/__init__.py"),
+ owner="venv", records={"pyvenv.cfg": baseline.receipt_sha, **baseline.app_records},
+ )
+ profile, workspace = tmp_path / "gateway data", tmp_path / "user project"
+ (profile / "sessions").mkdir(parents=True)
+ workspace.mkdir()
+ (profile / "config.json").write_text('{"fixture":"private credential"}')
+ (profile / "sessions/chat.jsonl").write_text('{"content":"original conversation"}\n')
+ (workspace / "private-project.py").write_text("not nanobot state")
+ selected_home = get_selected_home_path()
+ try:
+ set_home_path(profile)
+ instance = GatewayInstance.resolve(config_path=profile / "config.json", workspace=str(workspace))
+ runtime = GatewayRuntime(paths=instance.paths)
+ # Synthetic package fixture, real runtime receipt lifetime. Full gateway
+ # registration is independently tested in test_update_profiles.py.
+ with monkeypatch.context() as patch:
+ patch.setattr(sys, "prefix", str(environment))
+ with runtime.foreground_instance(instance.start_options(port=18790)):
+ with record_gateway_profile(instance, runtime, data_dir=profile, workspace=workspace, port=18790):
+ pass
+ finally:
+ set_home_path(selected_home)
+ profiles = inspect_profiles(str(environment))
+ restart_profiles = []
+ if mode in ("restart", "handoff"):
+ # Synthetic process metadata selects the installed routing stub above;
+ # test_update_restart.py separately runs the actual background gateway.
+ receipt = profiles[0].receipt.model_copy(update={"launch_mode": "background"})
+ write_record(installation_state_dir(str(environment)) / "profiles" / f"{receipt.id}.json",
+ receipt.model_dump(mode="json"))
+ profiles = inspect_profiles(str(environment))
+ restart_profiles = [receipt.id]
+ target = ReleaseTarget.model_construct(version=next_version, source="pypi",
+ url=f"https://files.pythonhosted.org/packages/{candidate.name}",
+ artifact=ReleaseArtifact(filename=candidate.name, size=candidate.stat().st_size,
+ sha256=hashlib.sha256(candidate.read_bytes()).hexdigest()))
+ manifest = None
+ catalogue = None
+ if ".dev" in next_version:
+ manifest = ReleaseManifest(version=next_version, source_commit="a" * 40, candidate_commit="b" * 40,
+ requires_python=">=3.11",
+ artifacts=[target.artifact if name == candidate.name else ReleaseArtifact(
+ filename=name, size=1, sha256="b" * 64,
+ ) for name in release_filenames(next_version)])
+ pointer = ReleasePointer(version=next_version, candidate_commit=manifest.candidate_commit,
+ manifest_sha256=hashlib.sha256(manifest.model_dump_json().encode()).hexdigest())
+ catalogue = ReleaseCatalogue(generation=1, preview=pointer)
+ target = target.model_copy(update={"source": "github", "url": manifest.artifact_url(target.artifact).split("#")[0],
+ "pointer": pointer, "catalogue_generation": 1})
+ target = ReleaseTarget.model_validate(target.model_dump())
+ now = int(time.time())
+ plan = UpdatePlan(id=str(uuid4()), installation=snapshot, target=target, extras=[],
+ channel="preview" if manifest else "stable",
+ profiles=profiles, restart_profiles=restart_profiles,
+ created_at=now, expires_at=now + 900)
+ requests = []
+
+ def response(request):
+ requests.append(str(request.url))
+ if catalogue and request.url.host in {"github.com", "raw.githubusercontent.com"}:
+ if str(request.url) == CATALOGUE_URL:
+ return httpx.Response(200, json=catalogue.model_dump(mode="json"))
+ if request.url.path.endswith("release-manifest.json"):
+ return httpx.Response(200, content=manifest.model_dump_json().encode())
+ assert request.url.path.endswith(candidate.name)
+ return httpx.Response(200, content=candidate.read_bytes())
+ if request.url.host == "files.pythonhosted.org":
+ return httpx.Response(200, content=candidate.read_bytes())
+ assert request.url.path == f"/pypi/nanobot-ai/{next_version}/json", "execution re-resolved latest"
+ files = []
+ for filename in release_filenames(next_version):
+ if filename.endswith((".whl", ".tar.gz")):
+ selected = filename == candidate.name
+ files.append({"filename": filename, "size": target.artifact.size if selected else 1,
+ "url": f"https://files.pythonhosted.org/packages/{filename}", "yanked": False,
+ "digests": {"sha256": target.artifact.sha256 if selected else "a" * 64}})
+ return httpx.Response(200, json={"info": {"name": "nanobot-ai", "version": next_version, "requires_python": ">=3.11"}, "urls": files})
+
+ return plan, candidate, site, requests, httpx.MockTransport(response)
+
+
+def managed_installation(installation):
+ plan, candidate, site, requests, transport = installation
+ receipt = Path(plan.installation.environment) / "nanobot-install.json"
+ write_record(receipt, {"schema_version": 1, "owner": "nanobot-installer",
+ "environment": plan.installation.environment, "extras": []})
+ snapshot = plan.installation.model_copy(update={
+ "records": {**plan.installation.records, "nanobot-install.json": hashlib.sha256(receipt.read_bytes()).hexdigest()},
+ })
+ return plan.model_copy(update={"installation": snapshot}), candidate, site, requests, transport
+
+
[email protected]("cancel_feed_close", [False, True])
+async def test_confirmed_service_prepares_exact_offline_pip_job_without_installing(installation, monkeypatch, cancel_feed_close):
+ from nanobot import update_service
+
+ plan, _, _, requests, transport = installation
+ monkeypatch.setattr(sys, "prefix", plan.installation.environment)
+ root = installation_state_dir()
+ UpdatePlans(root / "plans").save(plan)
+ class PreparedFeed(ReleaseFeed):
+ def __init__(self, directory):
+ super().__init__(directory, transport=transport)
+
+ async def __aexit__(self, *args):
+ await super().__aexit__(*args)
+ if cancel_feed_close:
+ raise asyncio.CancelledError()
+
+ monkeypatch.setattr(update_service, "ReleaseFeed", PreparedFeed)
+ service = UpdateJobService()
+ acknowledged = service.prepare(plan.id)
+ assert acknowledged.recorded_phase == Phase.PREPARATION_REQUESTED
+ await service.close()
+ restored = UpdateJobService().prepare(plan.id)
+ assert restored.recorded_phase == Phase.READY
+ spec = WorkerSpec.read(root / "jobs" / plan.id)
+ spec.verify_inputs(root / "jobs" / plan.id)
+ assert spec.version == "0.3.5"
+ assert inspect_environment(plan.installation.python).app_version == "0.3.4"
+ assert requests == ["https://pypi.org/pypi/nanobot-ai/0.3.5/json"] * 2 + [plan.target.url]
+ assert not (root / "jobs" / plan.id / "approval.json").exists()
+ assert not (root / "stop.json").exists()
+
+
+async def wait_worker(process):
+ code = await asyncio.to_thread(process.wait, 40)
+ assert code == 0
+
+
+async def test_channel_switch_retires_real_staged_job_and_preserves_its_evidence(installation, monkeypatch, tmp_path):
+ plan, _, _, _, transport = installation
+ monkeypatch.setattr(sys, "prefix", plan.installation.environment)
+ async with ReleaseFeed(tmp_path / "feed", transport=transport) as feed:
+ directory = await prepare_job(plan, feed)
+ spec_bytes = (directory / "request.json").read_bytes()
+ with file_access(installation_state_dir() / "worker.lock", exclusive=True):
+ with pytest.raises(BlockingIOError):
+ UpdateJobService().change_channel(UpdateChannelRequest(channel="preview", revision=0))
+ assert read_update_channel().channel == "stable"
+ assert JobStatus.read(directory).phase == Phase.READY
+ changed = UpdateJobService().change_channel(UpdateChannelRequest(channel="preview", revision=0))
+ assert changed.revision == 1
+ assert JobStatus.read(directory).phase == Phase.CANCELLED
+ assert (directory / "request.json").read_bytes() == spec_bytes
+ with pytest.raises(ValueError):
+ await start_job(directory, feed)
+ assert inspect_environment(plan.installation.python).app_version == plan.installation.installed_version
+ assert not (directory / "approval.json").exists()
+ assert not pending_update_path().exists()
+
+
+async def test_old_plan_without_channel_revision_remains_readable_and_byte_identical(installation, tmp_path):
+ plan, _, _, _, transport = installation
+ directory = installation_state_dir(plan.installation.environment) / "jobs" / plan.id
+ directory.mkdir(parents=True)
+ old = plan.model_dump(mode="json")
+ old.pop("channel_revision")
+ write_record(directory / "plan.json", old)
+ original = (directory / "plan.json").read_bytes()
+ async with ReleaseFeed(tmp_path / "feed", transport=transport) as feed:
+ assert await prepare_job(plan, feed) == directory
+ assert await prepare_job(plan, feed) == directory
+ assert (directory / "plan.json").read_bytes() == original
+ WorkerSpec.read(directory).verify_inputs(directory)
+
+
[email protected]("installation", [{"versions": ("0.3.6", "0.3.7.dev42")},
+ {"versions": ("0.3.7.dev42", "0.3.7.dev43")},
+ {"versions": ("0.3.7.dev43", "0.3.7")}], indirect=True)
+async def test_real_channel_upgrade_installs_verified_bytes_and_keeps_user_data(installation, tmp_path):
+ plan, _, site, _, transport = installation
+ profile = Path(plan.profiles[0].receipt.home)
+ original = {path: path.read_bytes() for path in (profile / "config.json", profile / "sessions/chat.jsonl")}
+ async with ReleaseFeed(tmp_path / "feed", transport=transport) as feed:
+ directory = await prepare_job(plan, feed)
+ assert inspect_environment(plan.installation.python).app_version == plan.installation.installed_version
+ await wait_worker(await start_job(directory, feed))
+ assert JobStatus.read(directory).phase == Phase.INSTALLED
+ assert inspect_environment(plan.installation.python).app_version == plan.target.version
+ assert (site / "nanobot/web/dist/index.html").read_text() == f"verified UI {plan.target.version}"
+ assert all(path.read_bytes() == value for path, value in original.items())
+ assert not pending_update_path(plan.installation.environment).exists()
+
+
+def test_recovery_command_uses_base_python_and_exact_launcher_without_shell_home(monkeypatch, tmp_path):
+ import nanobot.update_jobs as jobs
+
+ python = "/opt/Python tools/user's python/bin/python3"
+ monkeypatch.setattr(jobs.sys, "_base_executable", python)
+ monkeypatch.setattr(jobs.platform, "system", lambda: "Linux")
+ state = tmp_path / "user's private home/.nanobot/updates/installation"
+ monkeypatch.setattr(jobs, "installation_state_dir", lambda: state)
+ job_id = str(uuid4())
+ assert shlex.split(_recovery_command(job_id)) == [
+ python, "-I", "-S", str(state.parent / "recover.py"), job_id, "--repair",
+ ]
+
+
+def test_recovery_command_quotes_windows_base_python_for_powershell(monkeypatch):
+ import nanobot.update_jobs as jobs
+
+ monkeypatch.setattr(jobs.sys, "_base_executable", r"C:\Python tools\user's Python\python.exe")
+ monkeypatch.setattr(jobs.platform, "system", lambda: "Windows")
+ monkeypatch.setattr(jobs, "installation_state_dir", lambda: PureWindowsPath(
+ r"C:\Users\user's private home\.nanobot\updates\installation"))
+ job_id = str(uuid4())
+ assert _recovery_command(job_id) == (
+ r"& 'C:\Python tools\user''s Python\python.exe' -I -S "
+ rf"'C:\Users\user''s private home\.nanobot\updates\recover.py' {job_id} --repair"
+ )
+
+
[email protected]("installation", [False, {"versions": ("0.3.6", "0.3.7.dev42")},
+ {"versions": ("0.3.7.dev42", "0.3.7")}], indirect=True)
+async def test_standalone_repair_survives_missing_dependency_and_expired_approval(installation, tmp_path):
+ plan, _, site, _, transport = installation
+ async with ReleaseFeed(tmp_path / "feed", transport=transport) as feed:
+ directory = await prepare_job(plan, feed)
+ pip_entry = site / "pip/__main__.py"
+ original = pip_entry.read_text()
+ # Real interrupted mutation: lose a dependency before pip completes.
+ pip_entry.write_text(
+ f"from pathlib import Path\nPath({str(site / 'fixture_update_dep/__init__.py')!r}).unlink()\n"
+ "raise SystemExit(99)\n")
+ process = await start_job(directory, feed)
+ assert await asyncio.to_thread(process.wait, 40) != 0
+ pip_entry.write_text(original)
+ status = JobStatus.read(directory)
+ assert status.mutation_started and status.attempt == 1
+ backup = (directory / "backup/data.zip").read_bytes()
+ approval = read_record(directory / "approval.json")
+ approval.update(created_at=int(time.time()) - 1800, expires_at=int(time.time()) - 900)
+ write_record(directory / "approval.json", approval)
+ launcher = directory.parents[2] / "recover.py"
+ command = [sys._base_executable, "-I", "-S", str(launcher), plan.id]
+ # The operator's ordinary terminal need not share the gateway's HOME.
+ # The copied recovery command must retain the original job and lock scope.
+ terminal_home = tmp_path / "operator home"
+ terminal_home.mkdir()
+ terminal_env = dict(os.environ, HOME=str(terminal_home), USERPROFILE=str(terminal_home))
+ viewed = await asyncio.to_thread(subprocess.run, command, env=terminal_env,
+ capture_output=True, text=True, timeout=40)
+ assert viewed.returncode == 0, viewed.stderr
+ assert "Inspection only" in viewed.stdout
+ assert JobStatus.read(directory) == status
+ # A still-running installation owner cannot be overridden by local repair.
+ with installation_access(environment=plan.installation.environment, allow_incomplete=True):
+ refused = await asyncio.to_thread(subprocess.run, [*command, "--repair", "--yes"],
+ env=terminal_env, capture_output=True, text=True, timeout=40)
+ assert refused.returncode != 0
+ assert JobStatus.read(directory) == status
+ repaired = await asyncio.to_thread(subprocess.run, [*command, "--repair", "--yes"],
+ env=terminal_env, capture_output=True, text=True, timeout=40)
+ assert repaired.returncode == 0, repaired.stdout + repaired.stderr
+ assert JobStatus.read(directory).phase == Phase.INSTALLED
+ assert JobStatus.read(directory).attempt == 2
+ assert inspect_environment(plan.installation.python).app_version == plan.target.version
+ assert (site / "fixture_update_dep/__init__.py").read_text() == "__version__ = '2.0.0'\n"
+ assert (directory / "backup/data.zip").read_bytes() == backup
+ assert not pending_update_path(plan.installation.environment).exists()
+ assert list(terminal_home.iterdir()) == []
+
+
+async def test_standalone_repair_cannot_turn_preparation_into_installation(installation, tmp_path):
+ plan, _, _, _, transport = installation
+ async with ReleaseFeed(tmp_path / "feed", transport=transport) as feed:
+ directory = await prepare_job(plan, feed)
+ result = await asyncio.to_thread(subprocess.run, [
+ sys._base_executable, "-I", "-S", str(directory.parents[2] / "recover.py"), plan.id, "--repair", "--yes",
+ ], capture_output=True, text=True, timeout=40)
+ assert result.returncode != 0
+ assert JobStatus.read(directory).phase == Phase.READY
+ assert not (directory / "approval.json").exists()
+ assert inspect_environment(plan.installation.python).app_version == "0.3.4"
+
+
+async def wait_for(predicate):
+ async with asyncio.timeout(40):
+ while not predicate():
+ await asyncio.sleep(0.02)
+
+
[email protected]("installation", [
+ {"restart_contract": None}, # An older target had the Python file but no startup contract.
+ {"restart_contract": b'{"schema_version":1,"handoff_protocols":[2]}'},
+ {"restart_contract": b'{"schema_version":1,"handoff_protocols":[true]}'},
+ {"restart_contract": b'{"schema_version":1,"handoff_protocols":['},
+], ids=["undeclared", "incompatible", "malformed", "truncated"], indirect=True)
+async def test_target_restart_contract_is_checked_before_preparation_commits(installation, tmp_path):
+ plan, _, _, _, transport = installation
+ async with ReleaseFeed(tmp_path / "feed", transport=transport) as feed:
+ with pytest.raises(ValueError, match="external update procedure"):
+ await prepare_job(plan, feed)
+ root = installation_state_dir(plan.installation.environment)
+ directory = root / "jobs" / plan.id
+ assert JobStatus.read(directory).phase == Phase.PREPARATION_FAILED
+ assert not (directory / "request.json").exists()
+ assert not (directory / "approval.json").exists()
+ assert not (directory / "preflight-entered.json").exists()
+ assert not (root / "stop.json").exists()
+ assert inspect_environment(plan.installation.python).app_version == "0.3.4"
+
+
[email protected]("installation", [{"restart_contract": None}], indirect=True)
+async def test_previously_staged_target_cannot_bypass_restart_contract(installation, tmp_path, monkeypatch):
+ from nanobot import update_jobs
+
+ plan, _, _, _, transport = installation
+ # Model a job committed by the older filename-only preparer. Execution must
+ # inspect the real staged wheel rather than trusting a saved READY phase.
+ with monkeypatch.context() as patch:
+ patch.setattr(update_jobs, "verify_target_handoff", lambda archive: None)
+ async with ReleaseFeed(tmp_path / "feed", transport=transport) as feed:
+ directory = await prepare_job(plan, feed)
+ before = JobStatus.read(directory)
+ assert before.phase == Phase.READY
+ with pytest.raises(ValueError, match="external update procedure"):
+ start_handoff(directory, once=True)
+ assert ExecutionConfirmation.read(directory) is None
+ assert not (directory / "handoff-approval.json").exists()
+ assert not (directory / "preflight-entered.json").exists()
+ assert JobStatus.read(directory) == before
+ assert inspect_environment(plan.installation.python).app_version == "0.3.4"
+
+
[email protected]("installation", [
+ "handoff", {"restart_contract": b'{"schema_version":1,"handoff_protocols":[2,1]}'},
+], ids=["current-contract", "future-with-current-support"], indirect=True)
[email protected]("refuse", [False, True])
+async def test_confirmed_handoff_is_consumed_once_even_after_failure(installation, tmp_path, refuse):
+ plan, _, _, _, transport = installation
+ async with ReleaseFeed(tmp_path / "feed", transport=transport) as feed:
+ directory = await prepare_job(plan, feed)
+ if refuse:
+ (directory / "refuse-preflight").touch()
+ process = start_handoff(directory, once=True)
+ assert process is not None
+ code = await asyncio.to_thread(process.wait, 40)
+ assert (code != 0) is refuse
+ confirmation = ExecutionConfirmation.read(directory)
+ assert confirmation is not None
+ before = JobStatus.read(directory)
+ assert before.phase == (Phase.HANDOFF_FAILED if refuse else Phase.SUCCEEDED)
+ assert inspect_environment(plan.installation.python).app_version == ("0.3.4" if refuse else "0.3.5")
+ (directory / "refuse-preflight").unlink(missing_ok=True)
+ assert start_handoff(directory, once=True) is None
+ assert ExecutionConfirmation.read(directory) == confirmation
+ spec = WorkerSpec.read(directory)
+ # A late duplicate process must not retry a failed shutdown, even though
+ # its original approval is still in its launch window.
+ replay = subprocess.run([spec.baseline.base_python, "-I", str(directory / "worker.pyz"),
+ "--confirmed-handoff", str(directory), confirmation.id], capture_output=True, timeout=10)
+ assert replay.returncode == 0, replay.stderr
+ assert JobStatus.read(directory) == before
+ assert not (directory / "approval.json").exists() if refuse else before.attempt == 1
+ if not refuse:
+ with pytest.raises(ValueError, match="unmodified"):
+ retry_handoff(directory, confirmation.id)
+ assert ExecutionConfirmation.read(directory) == confirmation
+
+
[email protected]("installation", ["handoff"], indirect=True)
+async def test_retry_consumes_one_failed_confirmation_and_rechecks_ownership_and_expiry(installation, tmp_path, monkeypatch):
+ from nanobot import update_jobs
+
+ plan, _, _, _, transport = installation
+ async with ReleaseFeed(tmp_path / "feed", transport=transport) as feed:
+ directory = await prepare_job(plan, feed)
+ refusal = directory / "refuse-preflight"
+ refusal.touch()
+ process = start_handoff(directory, once=True)
+ assert process is not None
+ assert await asyncio.to_thread(process.wait, 40) != 0
+ previous = ExecutionConfirmation.read(directory)
+ assert previous is not None
+ failed = JobStatus.read(directory)
+ assert failed.phase == Phase.HANDOFF_FAILED and not failed.mutation_started
+
+ root = installation_state_dir(plan.installation.environment)
+ with file_access(root / "worker.lock", exclusive=True):
+ with pytest.raises(BlockingIOError):
+ retry_handoff(directory, previous.id)
+ with monkeypatch.context() as patch:
+ patch.setattr(update_jobs.time, "time", lambda: plan.expires_at)
+ with pytest.raises(ValueError, match="expired"):
+ retry_handoff(directory, previous.id)
+ assert ExecutionConfirmation.read(directory) == previous
+ assert JobStatus.read(directory) == failed
+
+ refusal.unlink()
+ process = retry_handoff(directory, previous.id)
+ current = ExecutionConfirmation.read(directory)
+ assert current is not None and current.id != previous.id
+ assert current.request_sha256 == previous.request_sha256
+ assert current.expires_at <= plan.expires_at
+ assert retry_handoff(directory, previous.id) is None
+ await wait_worker(process)
+ completed = JobStatus.read(directory)
+ assert completed.phase == Phase.SUCCEEDED and completed.attempt == 1
+ assert inspect_environment(plan.installation.python).app_version == "0.3.5"
+ spec = WorkerSpec.read(directory)
+ late = subprocess.run([spec.baseline.base_python, "-I", str(directory / "worker.pyz"),
+ "--confirmed-handoff", str(directory), previous.id], capture_output=True, timeout=10)
+ assert late.returncode != 0
+ assert retry_handoff(directory, previous.id) is None
+ assert JobStatus.read(directory) == completed
+
+
[email protected]("installation", ["handoff"], indirect=True)
+async def test_settled_failed_handoff_rejects_delayed_worker_and_keeps_original_files(installation, tmp_path):
+ from nanobot.update_stop import settle_uncommitted_handoff
+
+ plan, _, _, _, transport = installation
+ async with ReleaseFeed(tmp_path / "feed", transport=transport) as feed:
+ directory = await prepare_job(plan, feed)
+ (directory / "refuse-preflight").touch()
+ process = start_handoff(directory, once=True)
+ assert process is not None and await asyncio.to_thread(process.wait, 40) != 0
+ confirmation = ExecutionConfirmation.read(directory)
+ assert confirmation is not None
+ before = (directory / "request.json").read_bytes()
+ settled = settle_uncommitted_handoff(directory)
+ assert settled.phase == Phase.CANCELLED and not settled.mutation_started
+ assert ExecutionConfirmation.read(directory) == confirmation
+ assert (directory / "request.json").read_bytes() == before
+ (directory / "refuse-preflight").unlink()
+ spec = WorkerSpec.read(directory)
+ late = await asyncio.to_thread(subprocess.run,
+ [spec.baseline.base_python, "-I", str(directory / "worker.pyz"),
+ "--confirmed-handoff", str(directory), confirmation.id], capture_output=True, timeout=10)
+ assert late.returncode == 0 # Already-claimed duplicate reads the cancelled journal.
+ assert JobStatus.read(directory) == settled
+ assert not (directory / "approval.json").exists()
+ with pytest.raises(ValueError, match="unmodified"):
+ retry_handoff(directory, confirmation.id)
+
+
[email protected]("installation", ["handoff"], indirect=True)
+async def test_confirmed_launch_failure_is_not_retry_authority(installation, tmp_path, monkeypatch):
+ from nanobot import update_jobs
+
+ plan, _, _, _, transport = installation
+ async with ReleaseFeed(tmp_path / "feed", transport=transport) as feed:
+ directory = await prepare_job(plan, feed)
+ launches = []
+
+ def failed_spawn(directory, spec, **kwargs):
+ launches.append(kwargs)
+ raise OSError("controlled launch failure")
+
+ monkeypatch.setattr(update_jobs, "_spawn_worker", failed_spawn)
+ with pytest.raises(OSError, match="controlled launch"):
+ start_handoff(directory, once=True)
+ confirmation = ExecutionConfirmation.read(directory)
+ assert confirmation is not None
+ assert JobStatus.read(directory).phase == Phase.HANDOFF_FAILED
+ assert start_handoff(directory, once=True) is None
+ assert launches == [{"handoff": True, "confirmation_id": confirmation.id}]
+ assert not (directory / "confirmation-claimed.json").exists()
+ assert not (directory / "approval.json").exists()
+ assert inspect_environment(plan.installation.python).app_version == "0.3.4"
+
+
[email protected]("installation", ["handoff"], indirect=True)
+async def test_late_launch_failure_cannot_overwrite_new_retry_confirmation(installation, tmp_path, monkeypatch):
+ from nanobot import update_jobs
+
+ plan, _, _, _, transport = installation
+ async with ReleaseFeed(tmp_path / "feed", transport=transport) as feed:
+ directory = await prepare_job(plan, feed)
+ launched = []
+
+ def spawn(path, spec, **kwargs):
+ launched.append(kwargs["confirmation_id"])
+ if len(launched) == 1:
+ # The first requester stalls before process creation. Another
+ # explicit confirmation recovers that gap before it reports failure.
+ retry_handoff(path, kwargs["confirmation_id"])
+ raise OSError("The superseded launcher failed late")
+ return None
+
+ monkeypatch.setattr(update_jobs, "_spawn_worker", spawn)
+ with pytest.raises(OSError, match="superseded"):
+ start_handoff(directory, once=True)
+ assert len(launched) == 2 and launched[0] != launched[1]
+ assert ExecutionConfirmation.read(directory).id == launched[1]
+ assert JobStatus.read(directory).phase == Phase.CHECKING
+ assert retry_handoff(directory, launched[0]) is None
+ assert len(launched) == 2
+
+
[email protected]("installation", ["handoff"], indirect=True)
+async def test_late_confirmed_children_cannot_use_replaced_approval(installation, tmp_path, monkeypatch):
+ from nanobot import update_jobs
+
+ plan, _, _, _, transport = installation
+ async with ReleaseFeed(tmp_path / "feed", transport=transport) as feed:
+ directory = await prepare_job(plan, feed)
+ # Park before process creation to model a delayed launcher deterministically.
+ monkeypatch.setattr(update_jobs, "_spawn_worker", lambda *args, **kwargs: None)
+ start_handoff(directory, once=True)
+ confirmation = ExecutionConfirmation.read(directory)
+ assert confirmation is not None
+ spec = WorkerSpec.read(directory)
+ replaced = read_record(directory / "handoff-approval.json")
+ replaced.pop("confirmation_id") # A later explicitly managed recovery approval.
+ write_record(directory / "handoff-approval.json", replaced)
+ write_record(directory / "approval.json", replaced)
+ before = JobStatus.read(directory)
+ for entry in ("--confirmed-handoff", "--prepare-handoff", "--install", "--restart"):
+ interpreter = spec.baseline.base_python if entry == "--confirmed-handoff" else spec.baseline.python
+ result = subprocess.run([interpreter, "-I", "-S", str(directory / "worker.pyz"),
+ entry, str(directory), confirmation.id], capture_output=True, timeout=10)
+ assert result.returncode != 0, entry
+ assert not (directory / "preflight-entered.json").exists()
+ assert not (directory / "confirmation-claimed.json").exists()
+ assert JobStatus.read(directory) == before
+ assert inspect_environment(plan.installation.python).app_version == "0.3.4"
+
+
[email protected]("installation", ["handoff"], indirect=True)
+async def test_detached_handoff_outlives_requester_and_installs_after_preflight_exits(installation, tmp_path):
+ """Real frozen worker/pip, synthetic preflight/restart: not a gateway E2E."""
+ plan, _, site, _, transport = installation
+ async with ReleaseFeed(tmp_path / "feed", transport=transport) as feed:
+ directory = await prepare_job(plan, feed)
+ pause = directory / "pause-preflight"
+ pause.touch()
+ launcher = (
+ f"import sys; sys.path.insert(0, {str(Path(__file__).resolve().parents[1])!r})\n"
+ "from pathlib import Path\nfrom nanobot.update_jobs import start_handoff\n"
+ f"start_handoff(Path({str(directory)!r}))\n"
+ )
+ subprocess.run([sys.executable, "-c", launcher], check=True, timeout=10,
+ stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
+ # The caller is gone. The old-runtime child is still alive with its own lease.
+ try:
+ await wait_for(lambda: (directory / "preflight-entered.json").exists())
+ assert JobStatus.read(directory).phase == Phase.CHECKING
+ assert not (directory / "approval.json").exists()
+ with pytest.raises(InstallationBusyError):
+ with installation_access(updating=True, environment=plan.installation.environment):
+ pytest.fail("Preflight released its environment before actual exit")
+ with pytest.raises(BlockingIOError):
+ start_handoff(directory)
+ assert inspect_environment(plan.installation.python).app_version == "0.3.4"
+ finally:
+ pause.unlink(missing_ok=True)
+ await wait_for(lambda: JobStatus.read(directory).phase in {
+ Phase.SUCCEEDED, Phase.HANDOFF_FAILED, Phase.FAILED, Phase.RESTART_FAILED,
+ })
+ state = JobStatus.read(directory)
+ error = directory / "preflight-error.txt"
+ assert state.phase == Phase.SUCCEEDED, (state, error.read_text() if error.exists() else "")
+ assert inspect_environment(plan.installation.python).app_version == "0.3.5"
+ assert read_record(directory / "handoff-probe.json")["package"] == str((site / "nanobot/__init__.py").resolve())
+ assert not (site / "nanobot/update_handoff.py").exists(), "Old preflight source was not replaced"
+
+
[email protected]("installation", ["handoff"], indirect=True)
+async def test_refused_handoff_never_approves_install_and_can_retry_exact_plan(installation, tmp_path):
+ plan, _, _, _, transport = installation
+ async with ReleaseFeed(tmp_path / "feed", transport=transport) as feed:
+ directory = await prepare_job(plan, feed)
+ refusal = directory / "refuse-preflight"
+ refusal.touch()
+ process = start_handoff(directory)
+ assert await asyncio.to_thread(process.wait, 40) != 0
+ state = JobStatus.read(directory)
+ assert state.phase == Phase.HANDOFF_FAILED and not state.mutation_started
+ assert state.message == "Controlled preflight refusal"
+ assert not (directory / "approval.json").exists()
+ assert not (directory / "backup").exists()
+ assert inspect_environment(plan.installation.python).app_version == "0.3.4"
+ refusal.unlink()
+ await wait_worker(start_handoff(directory))
+ assert JobStatus.read(directory).phase == Phase.SUCCEEDED
+
+
[email protected]("installation", ["handoff"], indirect=True)
+async def test_handoff_reports_writer_that_remains_after_preflight(installation, tmp_path):
+ plan, _, _, _, transport = installation
+ async with ReleaseFeed(tmp_path / "feed", transport=transport) as feed:
+ directory = await prepare_job(plan, feed)
+ # A separate cooperating client still owns this environment. Successful
+ # gateway/preflight exit must not silently leave the UI showing "stopping".
+ with installation_access(environment=plan.installation.environment):
+ process = start_handoff(directory)
+ assert await asyncio.to_thread(process.wait, 40) != 0
+ state = JobStatus.read(directory)
+ assert state.phase == Phase.HANDOFF_FAILED and not state.mutation_started
+ assert "exclusive access" in state.message
+ assert not (directory / "approval.json").exists()
+ assert inspect_environment(plan.installation.python).app_version == "0.3.4"
+ await wait_worker(start_handoff(directory))
+ assert JobStatus.read(directory).phase == Phase.SUCCEEDED
+ # Replaying the detached command cannot demote a completed transaction.
+ spec = WorkerSpec.read(directory)
+ replay = subprocess.run([spec.baseline.base_python, "-I", str(directory / "worker.pyz"),
+ "--handoff", str(directory)], capture_output=True, timeout=10)
+ assert replay.returncode != 0
+ assert JobStatus.read(directory).phase == Phase.SUCCEEDED
+
+
[email protected]("installation", ["handoff"], indirect=True)
+async def test_saved_handoff_requires_fresh_consent_before_importing_old_runtime(installation, tmp_path):
+ plan, _, _, _, transport = installation
+ async with ReleaseFeed(tmp_path / "feed", transport=transport) as feed:
+ directory = await prepare_job(plan, feed)
+ spec = WorkerSpec.read(directory)
+ command = [spec.baseline.python, "-I", "-S", str(directory / "worker.pyz"), "--prepare-handoff", str(directory)]
+ for expired in (False, True):
+ if expired:
+ now = int(time.time())
+ write_record(directory / "handoff-approval.json", {
+ "plan_id": plan.id, "request_sha256": hashlib.sha256((directory / "request.json").read_bytes()).hexdigest(),
+ "created_at": now - 1000, "expires_at": now - 100,
+ })
+ result = subprocess.run(command, capture_output=True, timeout=10)
+ assert result.returncode != 0
+ assert not (directory / "preflight-entered.json").exists()
+ assert not (directory / "approval.json").exists()
+ assert JobStatus.read(directory).phase == Phase.READY
+ assert inspect_environment(plan.installation.python).app_version == "0.3.4"
+
+
[email protected]("installation", ["handoff"], indirect=True)
+async def test_orphan_preflight_keeps_lease_and_cannot_approve_installation(installation, tmp_path):
+ plan, _, _, _, transport = installation
+ async with ReleaseFeed(tmp_path / "feed", transport=transport) as feed:
+ directory = await prepare_job(plan, feed)
+ pause = directory / "pause-preflight"
+ pause.touch()
+ process = start_handoff(directory, once=True)
+ confirmation = ExecutionConfirmation.read(directory)
+ assert confirmation is not None
+ try:
+ await wait_for(lambda: (directory / "preflight-entered.json").exists())
+ process.kill() # Only this test-owned coordinator, never the old runtime child.
+ await asyncio.to_thread(process.wait, 10)
+ with pytest.raises(BlockingIOError):
+ retry_handoff(directory, confirmation.id)
+ assert ExecutionConfirmation.read(directory) == confirmation
+ with pytest.raises(InstallationBusyError):
+ with installation_access(updating=True, environment=plan.installation.environment):
+ pytest.fail("Lost parent released the surviving child's lease")
+ assert not (directory / "approval.json").exists()
+ finally:
+ pause.unlink(missing_ok=True)
+ if process.poll() is None:
+ process.kill()
+ await asyncio.to_thread(process.wait, 10)
+
+ def child_exited():
+ try:
+ with installation_access(updating=True, environment=plan.installation.environment):
+ return True
+ except InstallationBusyError:
+ return False
+
+ await wait_for(child_exited)
+ assert not (directory / "approval.json").exists()
+ assert inspect_environment(plan.installation.python).app_version == "0.3.4"
+ await wait_worker(retry_handoff(directory, confirmation.id))
+ assert JobStatus.read(directory).phase == Phase.SUCCEEDED
+
+
[email protected]("refuse", [False, True, "unfinished"])
+async def test_old_runtime_preflight_revalidates_before_shutdown(installation, tmp_path, monkeypatch, refuse):
+ from nanobot import update_handoff
+
+ plan, _, _, requests, transport = installation
+ async with ReleaseFeed(tmp_path / "feed", transport=transport) as feed:
+ directory = await prepare_job(plan, feed)
+ events = []
+
+ class ObservedFeed(ReleaseFeed):
+ def __init__(self, cache_dir):
+ super().__init__(cache_dir, transport=transport)
+
+ async def revalidate(self, target):
+ events.append("revalidate")
+ assert target == plan.target
+ if refuse is True:
+ raise RuntimeError("private credential must not enter status")
+ await super().revalidate(target)
+
+ async def __aexit__(self, *_args):
+ await super().__aexit__()
+ events.append("closed")
+
+ async def stop(path):
+ assert path == directory
+ assert events == ["revalidate", "closed"]
+ assert JobStatus.read(directory).phase == Phase.STOPPING
+ assert not (directory / "approval.json").exists()
+ events.append("stop")
+
+ monkeypatch.setattr(update_handoff, "ReleaseFeed", ObservedFeed)
+ monkeypatch.setattr(update_handoff, "stop_reviewed_gateways", stop)
+ # This test exercises release/stop ordering in the test interpreter. Real
+ # frozen-child startup and lease ownership have separate native coverage.
+ baseline = WorkerSpec.read(directory).baseline
+ monkeypatch.setattr(update_handoff, "current_environment", lambda **kwargs: baseline)
+ JobStatus(plan.id, Phase.CHECKING, 0, False, "Testing preflight", int(time.time())).save(directory)
+ if refuse == "unfinished":
+ from nanobot.data_access import data_access
+
+ with data_access([tmp_path / "other-installation-data"], updating=True, job_id=str(uuid4())) as lease:
+ lease.reserve()
+ if refuse:
+ with pytest.raises(RuntimeError):
+ await asyncio.to_thread(update_handoff.prepare_handoff, directory)
+ assert events == ["revalidate", "closed"]
+ assert JobStatus.read(directory).phase == Phase.HANDOFF_FAILED
+ assert "private credential" not in (directory / "status.json").read_text()
+ else:
+ await asyncio.to_thread(update_handoff.prepare_handoff, directory)
+ assert events == ["revalidate", "closed", "stop"]
+ assert requests[-1].endswith("/pypi/nanobot-ai/0.3.5/json")
+ assert not (directory / "approval.json").exists()
+ assert inspect_environment(plan.installation.python).app_version == "0.3.4"
+
+
[email protected]("installation", ["restart"], indirect=True)
[email protected]("standalone", [False, True])
+async def test_installed_runtime_failure_repairs_handoff_without_reinstalling(installation, tmp_path, monkeypatch, standalone):
+ plan, _, site, requests, transport = installation
+ async with ReleaseFeed(tmp_path / "feed", transport=transport) as feed:
+ directory = await prepare_job(plan, feed)
+ failure = directory / "fail-restart"
+ failure.touch()
+ process = await start_job(directory, feed)
+ assert await asyncio.to_thread(process.wait, 40) != 0
+ status = JobStatus.read(directory)
+ assert status.phase == Phase.RESTART_FAILED and status.attempt == 1
+ assert status.mutation_started
+ probe = read_record(directory / "handoff-probe.json")
+ assert probe == {"version": "0.3.5", "package": str((site / "nanobot/__init__.py").resolve()),
+ "attempt": 1, "phase": "restarting"}
+ assert inspect_environment(plan.installation.python).app_version == "0.3.5"
+ backup = (directory / "backup/data.zip").read_bytes()
+ record = (site / "nanobot_ai-0.3.5.dist-info/RECORD").read_bytes()
+ with pytest.raises(InstallationBusyError):
+ with installation_access(environment=plan.installation.environment):
+ pytest.fail("Runtime failure released the installation fence")
+ with pytest.raises(InstallationBusyError):
+ with data_access([plan.profiles[0].receipt.config]):
+ pytest.fail("Runtime failure released the data reservation")
+
+ async def offline(*_args, **_kwargs):
+ pytest.fail("Already-installed handoff repair must not depend on a release feed")
+
+ monkeypatch.setattr(feed, "revalidate", offline)
+ requests.clear()
+ with pytest.raises(ValueError, match="explicit repair"):
+ await start_job(directory, feed)
+ failure.unlink()
+ if standalone:
+ approval = read_record(directory / "approval.json")
+ approval.update(created_at=int(time.time()) - 1800, expires_at=int(time.time()) - 900)
+ write_record(directory / "approval.json", approval)
+ result = await asyncio.to_thread(subprocess.run, [
+ sys._base_executable, "-I", "-S", str(directory.parents[2] / "recover.py"), plan.id, "--repair", "--yes",
+ ], capture_output=True, text=True, timeout=40)
+ assert result.returncode == 0, result.stdout + result.stderr
+ else:
+ await wait_worker(await start_job(directory, feed, repair=True))
+ assert not requests
+ assert JobStatus.read(directory).phase == Phase.SUCCEEDED
+ assert JobStatus.read(directory).attempt == 1
+ assert read_record(directory / "handoff-probe.json")["phase"] == "restart_failed"
+ assert (directory / "backup/data.zip").read_bytes() == backup
+ assert (site / "nanobot_ai-0.3.5.dist-info/RECORD").read_bytes() == record
+ with installation_access(environment=plan.installation.environment), data_access([plan.profiles[0].receipt.config]):
+ pass
+
+
+def test_update_record_size_is_bounded_before_replacement(tmp_path):
+ path = tmp_path / "record.json"
+ record = {"message": "配置实例"}
+ write_record(path, record)
+ original = path.read_bytes()
+ assert read_record(path, max_bytes=len(original)) == record
+ write_record(path, record, max_bytes=len(original))
+ with pytest.raises(ValueError, match="size limit"):
+ write_record(path, record, max_bytes=len(original) - 1)
+ assert path.read_bytes() == original
+ with pytest.raises(ValueError, match="size limit"):
+ read_record(path, max_bytes=len(original) - 1)
+
+
+async def test_expanded_profile_request_is_readable_by_the_standalone_worker(installation, tmp_path):
+ plan, _, _, _, transport = installation
+ async with ReleaseFeed(tmp_path / "feed", transport=transport) as feed:
+ directory = await prepare_job(plan, feed)
+ spec = WorkerSpec.read(directory)
+ # A multi-profile inventory expands into many explicit named stores. It may
+ # outgrow the journal limit even when the saved plan is comfortably bounded.
+ sources = tuple(BackupSource(str(tmp_path / f"profile-{i}" / ("nested-" * 16) / "sessions")) for i in range(8192))
+ expanded = replace(spec, backup_sources=sources)
+ expanded.save(directory)
+ assert (directory / "request.json").stat().st_size > 1024 * 1024
+ assert WorkerSpec.read(directory) == expanded
+ result = subprocess.run([spec.baseline.base_python, "-I", str(directory / "worker.pyz"), "--status", str(directory)],
+ capture_output=True, text=True, timeout=20)
+ assert result.returncode == 0, result.stderr
+ assert json.loads(result.stdout)["phase"] == "ready"
+ # Earlier saved requests had no backup contract. Reject them explicitly;
+ # their own immutable worker remains available for inspection/recovery.
+ spec.save(directory)
+ legacy = read_record(directory / "request.json")
+ legacy["schema_version"] = 1
+ legacy.pop("backup_sources")
+ write_record(directory / "request.json", legacy)
+ with pytest.raises(ValueError, match="Unsupported update worker request"):
+ WorkerSpec.read(directory)
+ assert inspect_environment(plan.installation.python).app_version == "0.3.4"
+
+
+async def test_real_job_stages_then_installs_exact_app_and_dependency(installation, monkeypatch, tmp_path):
+ plan, _, site, requests, transport = installation
+ async with ReleaseFeed(tmp_path / "feed", transport=transport) as feed:
+ directory = await prepare_job(plan, feed)
+ assert inspect_environment(plan.installation.python).app_version == "0.3.4"
+ assert not (directory / "approval.json").exists()
+ spec = WorkerSpec.read(directory)
+ # The detached archive may load the target runtime only after acquiring
+ # its installation lease. Its frozen helpers must remain separate from
+ # the real installed nanobot package, not supply an empty __init__.
+ probe_command = [
+ plan.installation.python, "-I", "-c", """
+import json, sys
+from pathlib import Path
+sys.path.insert(0, sys.argv[1])
+from _nanobot_update.installation_lock import installation_access
+from _nanobot_update.update_worker import JobStatus
+with installation_access():
+ import nanobot
+ print(json.dumps([nanobot.__version__, nanobot.__file__, JobStatus.read(Path(sys.argv[2])).phase.value]))
+""", str(directory / "worker.pyz"), str(directory),
+ ]
+ probe = subprocess.run(probe_command, check=True, capture_output=True, text=True, timeout=20)
+ loaded_version, loaded_path, phase = json.loads(probe.stdout)
+ assert loaded_version == "0.3.4" and phase == "ready"
+ assert Path(loaded_path).resolve() == (site / "nanobot/__init__.py").resolve()
+ assert {(item.name, item.version) for item in spec.wheels} == {
+ ("nanobot-ai", "0.3.5"), ("fixture-update-dep", "2.0.0"),
+ }
+ assert await prepare_job(plan, feed) == directory
+ # Installer configuration cannot redirect writes or the final dependency
+ # check into another interpreter (and an unprotected pip grandchild).
+ unintended = tmp_path / "not-the-approved-environment"
+ monkeypatch.setenv("PIP_TARGET", str(unintended))
+ monkeypatch.setenv("PIP_PYTHON", str(unintended / "python"))
+ await wait_worker(await start_job(directory, feed))
+ status = JobStatus.read(directory)
+ assert status.phase == Phase.INSTALLED and status.attempt == 1 and status.mutation_started
+ assert "not yet verified" in status.message
+ assert inspect_environment(plan.installation.python).app_version == "0.3.5"
+ probe = subprocess.run(probe_command, check=True, capture_output=True, text=True, timeout=20)
+ loaded_version, loaded_path, phase = json.loads(probe.stdout)
+ assert loaded_version == "0.3.5" and phase == "installed"
+ assert Path(loaded_path).resolve() == (site / "nanobot/__init__.py").resolve()
+ assert (site / "nanobot/web/dist/index.html").read_text() == "verified UI 0.3.5"
+ assert not unintended.exists()
+ with ZipFile(directory / "backup/data.zip") as archive:
+ entries = json.loads(archive.read("manifest.json"))["entries"]
+ configs = [item for item in entries if item["path"] == plan.profiles[0].receipt.config]
+ assert len(configs) == 1
+ assert archive.read(configs[0]["member"]) == b'{"fixture":"private credential"}'
+ assert not any(item["path"].endswith("private-project.py") for item in entries)
+ assert not pending_update_path(plan.installation.environment).exists()
+ # Recover the reachable crash gap between saving INSTALLED and clearing the
+ # startup fence. The completed job must verify/clear it, not install again.
+ write_record(pending_update_path(plan.installation.environment),
+ {"schema_version": 2, "job_id": plan.id, "version": "0.3.5"})
+ result = subprocess.run([spec.baseline.base_python, "-I", str(directory / "worker.pyz"), str(directory)],
+ capture_output=True, text=True, timeout=20)
+ assert result.returncode == 0, result.stderr
+ assert JobStatus.read(directory).attempt == 1
+ assert not pending_update_path(plan.installation.environment).exists()
+ assert requests and all("/0.3.5/" in url or "/packages/" in url for url in requests)
+
+
[email protected]("stage", ["site", "atexit"])
+async def test_planning_probe_retains_lease_after_caller_loss(installation, tmp_path, stage):
+ plan, _, site, _, _ = installation
+ ready, release = tmp_path / "planning-ready", tmp_path / "planning-continue"
+ caller_pid = tmp_path / "planning-caller-pid"
+ hook = site / "hold_planning_probe.py"
+ hook.write_text(
+ "import atexit,os,time\nfrom pathlib import Path\n"
+ "def hold():\n"
+ f" Path({str(ready)!r}).write_text(str(os.getpid()))\n"
+ " deadline=time.monotonic()+20\n"
+ f" while not Path({str(release)!r}).exists():\n"
+ " if time.monotonic()>deadline: raise SystemExit(99)\n"
+ " time.sleep(0.02)\n"
+ + ("atexit.register(hold)\n" if stage == "atexit" else "hold()\n")
+ )
+ pth = site / "hold_planning_probe.pth"
+ pth.write_text("import hold_planning_probe\n")
+ caller = (
+ "import os,sys\nfrom pathlib import Path\nfrom nanobot.update_plan import inspect_installation\n"
+ f"sys.prefix={plan.installation.environment!r}\n"
+ f"sys.executable={plan.installation.python!r}\n"
+ f"Path({str(caller_pid)!r}).write_text(str(os.getpid()))\n"
+ "inspect_installation()\n"
+ )
+ process = subprocess.Popen([sys.executable, "-c", caller], cwd=Path(__file__).resolve().parents[1],
+ stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, text=True)
+ try:
+ for _ in range(200):
+ if ready.exists():
+ break
+ if process.poll() is not None:
+ pytest.fail(process.communicate()[1])
+ await asyncio.sleep(0.025)
+ assert ready.exists()
+ child_pid = int(ready.read_text())
+ # Kill the actual caller, not a Windows venv redirector. The planning
+ # child must survive; killing the whole process tree would not prove it.
+ os.kill(int(caller_pid.read_text()), signal.SIGTERM)
+ process.wait(timeout=5)
+ assert process_is_running(child_pid)
+ with pytest.raises(InstallationBusyError):
+ with installation_access(updating=True, environment=plan.installation.environment):
+ pytest.fail("A live planning probe lost its lease with its caller")
+ finally:
+ release.touch()
+ if process.poll() is None:
+ process.wait(timeout=15)
+ if process.stderr is not None:
+ process.stderr.close()
+ for _ in range(400):
+ try:
+ with installation_access(updating=True, environment=plan.installation.environment):
+ break
+ except InstallationBusyError:
+ await asyncio.sleep(0.025)
+ else:
+ pytest.fail("The planning probe did not release its own lease")
+ pth.unlink()
+ hook.unlink()
+ # Planning neither installs nor leaves update authority/startup fences.
+ assert inspect_environment(plan.installation.python).app_version == "0.3.4"
+ assert not pending_update_path(plan.installation.environment).exists()
+ assert not (installation_state_dir(plan.installation.environment) / "jobs").exists()
+
+
+async def test_changed_artifact_or_owner_receipt_never_installs(installation, tmp_path):
+ plan, _, _, _, transport = installation
+ async with ReleaseFeed(tmp_path / "feed", transport=transport) as feed:
+ directory = await prepare_job(plan, feed)
+ app = directory / "wheels" / plan.target.artifact.filename
+ original = app.read_bytes()
+ app.write_bytes(original + b"changed")
+ with pytest.raises(ValueError, match="size"):
+ await start_job(directory, feed)
+ assert not pending_update_path(plan.installation.environment).exists()
+ app.write_bytes(original)
+ receipt = Path(plan.installation.environment) / "pyvenv.cfg"
+ receipt.write_text(receipt.read_text() + "\n# changed by another owner\n")
+ with pytest.raises(ValueError, match="ownership"):
+ await start_job(directory, feed)
+ assert inspect_environment(plan.installation.python).app_version == "0.3.4"
+
+
+async def test_stale_plan_is_rejected_before_staging(installation, tmp_path):
+ plan, _, _, requests, transport = installation
+ # A real environment change, not a hypothetical internal flag.
+ receipt = Path(plan.installation.environment) / "pyvenv.cfg"
+ receipt.write_text(receipt.read_text() + "\n# changed\n")
+ async with ReleaseFeed(tmp_path / "feed", transport=transport) as feed:
+ with pytest.raises(ValueError, match="changed since"):
+ await prepare_job(plan, feed)
+ assert not requests
+
+
+async def test_worker_survives_coordinator_loss_without_unlocking_live_pip(installation, tmp_path):
+ plan, _, site, _, transport = installation
+ async with ReleaseFeed(tmp_path / "feed", transport=transport) as feed:
+ directory = await prepare_job(plan, feed)
+ ready, release = tmp_path / "pip-ready", tmp_path / "pip-continue"
+ pip_entry = site / "pip/__main__.py"
+ original = pip_entry.read_text()
+ # Hold the real pip CLI immediately before it runs; only the disposable
+ # fixture's launcher is wrapped, and its original body still executes.
+ wrapper = (
+ f"from pathlib import Path\nimport os,time\nPath({str(ready)!r}).write_text(str(os.getpid()))\n"
+ f"deadline=time.monotonic()+20\nwhile not Path({str(release)!r}).exists():\n"
+ " if time.monotonic()>deadline: raise SystemExit(99)\n time.sleep(0.02)\n"
+ f"exec(compile({original!r}, __file__, 'exec'))\n"
+ )
+ pip_entry.write_text(wrapper)
+ process = await start_job(directory, feed)
+ try:
+ for _ in range(200):
+ if ready.exists():
+ break
+ assert process.poll() is None, JobStatus.read(directory)
+ await asyncio.sleep(0.025)
+ assert ready.exists()
+ process.kill()
+ process.wait(timeout=10)
+ assert JobStatus.read(directory).phase == Phase.INSTALLING
+ with pytest.raises(InstallationBusyError):
+ with installation_access(updating=True, environment=plan.installation.environment):
+ pytest.fail("Live pip lost its installation lease with the coordinator")
+ with pytest.raises(InstallationBusyError, match="data is in use"):
+ with data_access([Path(plan.profiles[0].receipt.data_dir) / "sessions"]):
+ pytest.fail("Live pip lost its data lease with the coordinator")
+ with pytest.raises(InstallationBusyError):
+ await start_job(directory, feed, repair=True)
+ finally:
+ release.touch()
+ if process.poll() is None:
+ process.wait(timeout=30)
+ # Wait for the actual pip lease to disappear, not just the dead parent's PID.
+ for _ in range(400):
+ try:
+ with installation_access(updating=True, environment=plan.installation.environment):
+ break
+ except InstallationBusyError:
+ await asyncio.sleep(0.025)
+ else:
+ pytest.fail("Pip did not release its lease")
+ assert inspect_environment(plan.installation.python).app_version == "0.3.5"
+ with pytest.raises(InstallationBusyError, match="reserved"):
+ with data_access([Path(plan.profiles[0].receipt.data_dir) / "sessions"]):
+ pytest.fail("Pip exit lifted the interrupted coordinator's data reservation")
+ backup = (directory / "backup/data.zip").read_bytes()
+ # A repair must retain the original data even if a migration or an
+ # operator changed the live profile after the interrupted installation.
+ Path(plan.profiles[0].receipt.config).write_text('{"fixture":"changed after install"}')
+ pip_entry.write_text(original)
+ retained = directory / "retained-original-backup"
+ (directory / "backup").rename(retained)
+ refused = await start_job(directory, feed, repair=True)
+ assert await asyncio.to_thread(refused.wait, 30) != 0
+ assert JobStatus.read(directory).mutation_started
+ assert JobStatus.read(directory).attempt == 1
+ assert "original pre-update backup is missing" in JobStatus.read(directory).message
+ assert not (directory / "backup").exists()
+ retained.rename(directory / "backup")
+ (site / "nanobot/web/dist/index.html").unlink()
+ with pytest.raises(ValueError, match="explicit repair"):
+ await start_job(directory, feed)
+ await wait_worker(await start_job(directory, feed, repair=True))
+ assert (directory / "backup/data.zip").read_bytes() == backup
+ assert JobStatus.read(directory).attempt == 2
+ assert JobStatus.read(directory).phase == Phase.INSTALLED
+ assert (site / "nanobot/web/dist/index.html").read_text() == "verified UI 0.3.5"
+ with data_access([Path(plan.profiles[0].receipt.data_dir) / "sessions"]):
+ pass # Successful repair releases both the live lease and persistent fence.
+
+
+async def test_other_installation_writer_refuses_job_before_approval_or_backup(installation, tmp_path):
+ plan, _, _, _, transport = installation
+ async with ReleaseFeed(tmp_path / "feed", transport=transport) as feed:
+ directory = await prepare_job(plan, feed)
+ # This test process uses a different Python environment from the pip job.
+ with data_access([Path(plan.profiles[0].receipt.workspace) / "sessions"]):
+ with pytest.raises(InstallationBusyError, match="data is in use"):
+ await start_job(directory, feed)
+ assert not (directory / "approval.json").exists()
+ assert not (directory / "backup").exists()
+ assert JobStatus.read(directory).phase == Phase.READY
+ assert inspect_environment(plan.installation.python).app_version == "0.3.4"
+ await wait_worker(await start_job(directory, feed))
+ assert JobStatus.read(directory).phase == Phase.INSTALLED
+
+
+async def test_cancel_interrupted_handoff_releases_data_without_installing(installation, tmp_path, monkeypatch):
+ from nanobot import update_jobs
+
+ plan, _, _, _, transport = installation
+ ready = tmp_path / "coordinator-ready"
+ original_popen = subprocess.Popen
+ wrapper = """
+import sys, time
+from pathlib import Path
+sys.path.insert(0, sys.argv[1])
+from _nanobot_update import update_worker
+original_run = update_worker.subprocess.run
+def run(command, *args, **kwargs):
+ if '--install' in command:
+ Path(sys.argv[3]).write_text('ready')
+ time.sleep(15)
+ raise RuntimeError('Handoff test deadline exceeded')
+ return original_run(command, *args, **kwargs)
+update_worker.subprocess.run = run
+update_worker.run_job(Path(sys.argv[2]))
+"""
+
+ def launch(command, **kwargs):
+ if len(command) == 5 and str(command[3]).endswith("worker.pyz"):
+ command = [command[0], "-I", "-S", "-c", wrapper, command[3], command[4], str(ready)]
+ return original_popen(command, **kwargs)
+
+ async with ReleaseFeed(tmp_path / "feed", transport=transport) as feed:
+ directory = await prepare_job(plan, feed)
+ monkeypatch.setattr(update_jobs.subprocess, "Popen", launch)
+ process = await start_job(directory, feed)
+ try:
+ for _ in range(200):
+ if ready.exists():
+ break
+ assert process.poll() is None, JobStatus.read(directory)
+ await asyncio.sleep(0.025)
+ assert ready.exists()
+ finally:
+ if process.poll() is None:
+ process.kill()
+ process.wait(timeout=10)
+ status = JobStatus.read(directory)
+ assert status.phase == Phase.BACKING_UP and not status.mutation_started
+ assert inspect_environment(plan.installation.python).app_version == "0.3.4"
+ store = Path(plan.profiles[0].receipt.data_dir) / "sessions"
+ with pytest.raises(InstallationBusyError, match="reserved"):
+ with data_access([store]):
+ pytest.fail("A dead coordinator lost its maintenance reservation")
+ cancel_job(directory)
+ assert JobStatus.read(directory).phase == Phase.CANCELLED
+ assert not pending_update_path(plan.installation.environment).exists()
+ with data_access([store]):
+ pass
+ with pytest.raises(ValueError, match="already finished"):
+ await start_job(directory, feed)
+
+
+async def test_prepared_worker_has_no_execution_authority(installation, tmp_path):
+ plan, _, _, _, transport = installation
+ async with ReleaseFeed(tmp_path / "feed", transport=transport) as feed:
+ with pytest.raises(ValueError, match="confirmed extras"):
+ await prepare_job(plan.model_copy(update={"id": str(uuid4()), "extras": ["not-provided"]}), feed)
+ directory = await prepare_job(plan, feed)
+ spec = WorkerSpec.read(directory)
+ result = subprocess.run([spec.baseline.base_python, "-I", str(directory / "worker.pyz"), str(directory)],
+ capture_output=True, timeout=20)
+ assert result.returncode != 0
+ assert inspect_environment(plan.installation.python).app_version == "0.3.4"
+ assert not pending_update_path(plan.installation.environment).exists()
+ assert JobStatus.read(directory).phase == Phase.FAILED
+ assert not JobStatus.read(directory).mutation_started
+ # A saved but expired approval cannot authorize a delayed launch.
+ now = int(time.time())
+ write_record(directory / "approval.json", {
+ "plan_id": plan.id, "request_sha256": hashlib.sha256((directory / "request.json").read_bytes()).hexdigest(),
+ "created_at": now - 1000, "expires_at": now - 100,
+ })
+ result = subprocess.run([spec.baseline.base_python, "-I", str(directory / "worker.pyz"), str(directory)],
+ capture_output=True, timeout=20)
+ assert result.returncode != 0
+ assert "expired" in JobStatus.read(directory).message
+ cancel_job(directory)
+ result = subprocess.run([spec.baseline.base_python, "-I", str(directory / "worker.pyz"), str(directory)],
+ capture_output=True, timeout=20)
+ assert result.returncode != 0
+ assert JobStatus.read(directory).phase == Phase.CANCELLED
+
+
[email protected](os.name == "nt", reason="Symlink creation requires separate Windows privileges")
[email protected]("standalone", [False, True])
+async def test_real_worker_refuses_installation_when_scoped_backup_fails(installation, tmp_path, standalone):
+ plan, _, _, _, transport = installation
+ async with ReleaseFeed(tmp_path / "feed", transport=transport) as feed:
+ directory = await prepare_job(plan, feed)
+ external = tmp_path / "external-secret"
+ external.write_text("outside the approved stores")
+ link = Path(plan.profiles[0].receipt.data_dir) / "sessions/external"
+ link.symlink_to(external)
+ process = await start_job(directory, feed)
+ assert await asyncio.to_thread(process.wait, 30) != 0
+ status = JobStatus.read(directory)
+ assert status.phase == Phase.FAILED and not status.mutation_started
+ assert "symlink" in status.message
+ assert inspect_environment(plan.installation.python).app_version == "0.3.4"
+ assert not pending_update_path(plan.installation.environment).exists()
+ assert not (directory / "backup").exists()
+ link.unlink()
+ if standalone:
+ approval = read_record(directory / "approval.json")
+ approval.update(created_at=int(time.time()) - 1800, expires_at=int(time.time()) - 900)
+ write_record(directory / "approval.json", approval)
+ result = await asyncio.to_thread(subprocess.run, [
+ sys._base_executable, "-I", "-S", str(directory.parents[2] / "recover.py"), plan.id, "--repair", "--yes",
+ ], capture_output=True, text=True, timeout=40)
+ assert result.returncode == 0, result.stdout + result.stderr
+ else:
+ await wait_worker(await start_job(directory, feed))
+ assert JobStatus.read(directory).phase == Phase.INSTALLED
+
+
[email protected]("installation", [True], indirect=True)
+async def test_broken_release_keeps_recovery_record_and_never_overwrites_an_external_upgrade(installation, tmp_path):
+ plan, candidate, _, _, transport = installation
+ async with ReleaseFeed(tmp_path / "feed", transport=transport) as feed:
+ directory = await prepare_job(plan, feed)
+ process = await start_job(directory, feed)
+ assert await asyncio.to_thread(process.wait, 40) != 0
+ state = JobStatus.read(directory)
+ assert state.phase == Phase.FAILED and state.mutation_started
+ assert "does not import" in state.message
+ assert pending_update_path(plan.installation.environment).exists()
+ spec = WorkerSpec.read(directory)
+ # The status command is usable even though importing nanobot now fails.
+ result = subprocess.run([spec.baseline.base_python, "-I", str(directory / "worker.pyz"), "--status", str(directory)],
+ capture_output=True, text=True, timeout=20)
+ assert result.returncode == 0
+ assert json.loads(result.stdout)["phase"] == "failed"
+ with pytest.raises(ValueError, match="not cancellation"):
+ cancel_job(directory)
+ newer = wheel(candidate.parent, "nanobot-ai", "0.3.6", requires=["fixture-update-dep>=2.0.0"])
+ subprocess.run([plan.installation.python, "-I", "-m", "pip", "install", "--disable-pip-version-check", str(newer)],
+ capture_output=True, check=True, timeout=30)
+ with pytest.raises(ValueError, match="cannot overwrite"):
+ await start_job(directory, feed, repair=True)
+ assert inspect_environment(plan.installation.python).app_version == "0.3.6"
+
+
+def test_program_copy_flushes_writable_handle_and_preserves_read_only_mode(tmp_path, monkeypatch):
+ from nanobot.update_fallback import _copy_program_file
+
+ source, destination = tmp_path / "license.txt", tmp_path / "copied-license.txt"
+ source.write_bytes(b"Installed package license\n")
+ source.chmod(0o444)
+ fsync = os.fsync
+ flushed = []
+ def sync_writable(descriptor):
+ # POSIX accepts fsync on read-only handles, but Windows rejects it.
+ # A zero-byte write verifies the cross-platform handle requirement.
+ os.write(descriptor, b"")
+ fsync(descriptor)
+ flushed.append(descriptor)
+ monkeypatch.setattr(os, "fsync", sync_writable)
+ assert _copy_program_file(str(source), str(destination)) == str(destination)
+ assert len(flushed) == 1
+ assert destination.read_bytes() == source.read_bytes()
+ assert destination.stat().st_mode == source.stat().st_mode
+ assert destination.stat().st_mtime_ns == source.stat().st_mtime_ns
+
+
[email protected]("installation", ["handoff"], indirect=True)
+async def test_job_recovery_capability_comes_from_its_saved_worker(managed_installation, tmp_path, monkeypatch):
+ from nanobot.update_jobs import read_update_job
+
+ plan, _, _, _, transport = managed_installation
+ async with ReleaseFeed(tmp_path / "feed", transport=transport) as feed:
+ directory = await prepare_job(plan, feed)
+ monkeypatch.setattr(sys, "prefix", plan.installation.environment)
+ assert read_update_job(plan.id).automatic_recovery is True
+ # Schema 4 jobs prepared by older releases did not opt into supervision.
+ # An eligible installation does not change those frozen jobs' capabilities.
+ request = read_record(directory / "request.json")
+ request.pop("automatic_recovery")
+ write_record(directory / "request.json", request)
+ assert read_update_job(plan.id).automatic_recovery is False
+ (directory / "worker.pyz").unlink()
+ assert read_update_job(plan.id).automatic_recovery is False, "Status must remain readable after damage"
+
+
[email protected]("installation", ["handoff"], indirect=True)
+async def test_stale_first_supervisor_cannot_take_new_confirmation(managed_installation, tmp_path, monkeypatch):
+ """Real frozen supervisor/worker/pip; synthetic preflight and restart bodies."""
+ from nanobot import update_jobs
+
+ plan, _, _, _, transport = managed_installation
+ async with ReleaseFeed(tmp_path / "feed", transport=transport) as feed:
+ directory = await prepare_job(plan, feed)
+ spec = WorkerSpec.read(directory)
+ assert spec.automatic_recovery
+ # Park both launchers before process creation, then schedule stale A first.
+ with monkeypatch.context() as patch:
+ patch.setattr(update_jobs, "_spawn_worker", lambda *args, **kwargs: None)
+ start_handoff(directory, once=True)
+ previous = ExecutionConfirmation.read(directory)
+ assert previous is not None
+ retry_handoff(directory, previous.id)
+ current = ExecutionConfirmation.read(directory)
+ assert current is not None and current.id != previous.id
+ before = JobStatus.read(directory)
+ approval = (directory / "handoff-approval.json").read_bytes()
+ command = [spec.baseline.base_python, "-I", "-S", str(directory / "worker.pyz"),
+ "--supervise", str(directory), "--confirmed-handoff", str(directory)]
+ stale = await asyncio.to_thread(subprocess.run, [*command, previous.id], capture_output=True, timeout=40)
+ assert not (directory / "supervision.json").exists(), stale.stderr.decode()
+ assert stale.returncode != 0
+ assert JobStatus.read(directory) == before
+ assert ExecutionConfirmation.read(directory) == current
+ assert (directory / "handoff-approval.json").read_bytes() == approval
+ assert not (directory / "confirmation-claimed.json").exists()
+ assert not (directory / "preflight-entered.json").exists()
+ assert not (directory / "approval.json").exists()
+ assert not (installation_state_dir(spec.baseline.environment) / "stop.json").exists()
+ # B retains its first supervision budget and completes the explicit retry.
+ try:
+ completed = await asyncio.to_thread(subprocess.run, [*command, current.id], capture_output=True, timeout=40)
+ except subprocess.TimeoutExpired:
+ # Identify the blocked phase without exposing the confirmation nonce or
+ # making a slow snapshot indistinguishable from a handoff deadlock.
+ status = JobStatus.read(directory)
+ progress = {"phase": status.phase.value, "attempt": status.attempt,
+ "mutation_started": status.mutation_started, "message": status.message,
+ "snapshot_complete": (directory / "program-backup.json").exists(),
+ "activation_complete": (directory / "activation.json").exists()}
+ pytest.fail(f"Confirmed supervisor exceeded 40s: {progress}", pytrace=False)
+ assert completed.returncode == 0, completed.stderr.decode()
+ assert read_record(directory / "supervision.json")["confirmation_id"] == current.id
+ assert JobStatus.read(directory).phase == Phase.SUCCEEDED
+ assert JobStatus.read(directory).attempt == 1
+ assert inspect_environment(plan.installation.python).app_version == plan.target.version
+ assert not pending_update_path(spec.baseline.environment).exists()
+ with file_access(installation_state_dir(spec.baseline.environment) / "supervisor.lock", exclusive=True):
+ pass
+
+
[email protected]("installation", ["handoff"], indirect=True)
[email protected]("restarting", [False, True])
+async def test_service_restore_keeps_confirmation_identity_after_expiry(managed_installation, tmp_path, monkeypatch, restarting):
+ from nanobot import update_jobs, update_worker
+ from nanobot.update_fallback import restore_service
+
+ plan, _, _, _, transport = managed_installation
+ async with ReleaseFeed(tmp_path / "feed", transport=transport) as feed:
+ directory = await prepare_job(plan, feed)
+ monkeypatch.setattr(update_jobs, "_spawn_worker", lambda *args, **kwargs: None)
+ start_handoff(directory, once=True)
+ previous = ExecutionConfirmation.read(directory)
+ assert previous is not None
+ retry_handoff(directory, previous.id)
+ current = ExecutionConfirmation.read(directory)
+ assert current is not None
+ # A long completion may outlive B's launch window, but never borrow its identity.
+ now = int(time.time())
+ current = replace(current, created_at=now - 1800, expires_at=now - 900)
+ current.save(directory)
+ approval = read_record(directory / "handoff-approval.json")
+ approval.update(created_at=current.created_at, expires_at=current.expires_at)
+ write_record(directory / "handoff-approval.json", approval)
+ if restarting:
+ write_record(directory / "restoration.json", {"plan_id": plan.id, "state": "restarting"})
+ JobStatus(plan.id, Phase.RESTART_FAILED, 0, False, "Interrupted original-service restart", now).save(directory)
+ before = JobStatus.read(directory)
+ restarts = []
+ monkeypatch.setattr(update_worker, "restart_runtime", lambda path, spec: restarts.append(path))
+ with pytest.raises(ValueError, match="replaced or revoked"):
+ restore_service(directory, confirmation_id=previous.id)
+ assert JobStatus.read(directory) == before
+ assert restarts == []
+ restore_service(directory, confirmation_id=current.id)
+ assert restarts == ([directory] if restarting else [])
+ assert JobStatus.read(directory).phase == (Phase.RESTART_FAILED if restarting else Phase.HANDOFF_FAILED)
+ assert inspect_environment(plan.installation.python).app_version == plan.installation.installed_version
+
+
[email protected]("installation", [True], indirect=True)
[email protected]("interrupted", [None, "rename", "journal", "metadata"])
+async def test_program_restore_after_real_broken_install_preserves_user_data(installation, tmp_path, monkeypatch, interrupted):
+ from nanobot.update_fallback import (
+ preserve_program,
+ require_unchanged_user_data,
+ restore_program,
+ )
+
+ plan, _, _, _, transport = installation
+ async with ReleaseFeed(tmp_path / "feed", transport=transport) as feed:
+ directory = await prepare_job(plan, feed)
+ spec = replace(WorkerSpec.read(directory), automatic_recovery=True)
+ # No service participants in this fixture: exercise actual package and
+ # dependency restoration separately from the packaged gateway E2E.
+ with installation_access(updating=True, environment=spec.baseline.environment):
+ preserve_program(directory, spec)
+ process = await start_job(directory, feed)
+ assert await asyncio.to_thread(process.wait, 40) != 0
+ assert JobStatus.read(directory).mutation_started
+ if interrupted == "metadata":
+ from nanobot.update_fallback import _inspect_metadata
+ from nanobot.update_worker import check_environment
+
+ # A killed installer can leave dist-info after removing METADATA.
+ # Same-target import probes fail, but restoring the saved program
+ # must not depend on importing or parsing the damaged package.
+ next(Path(spec.baseline.environment).rglob(f"nanobot_ai-{spec.version}.dist-info/METADATA")).unlink()
+ check_environment(spec, repairing=True, current=_inspect_metadata(spec))
+ config = Path(plan.profiles[0].receipt.config)
+ chat = Path(plan.profiles[0].receipt.data_dir) / "sessions/chat.jsonl"
+ before = config.read_bytes(), chat.read_bytes()
+ with (installation_access(updating=True, environment=spec.baseline.environment),
+ data_access((s.path for s in spec.backup_sources), updating=True, job_id=spec.plan_id)):
+ require_unchanged_user_data(directory, spec)
+ if interrupted in {"rename", "journal"}:
+ from nanobot import update_worker
+
+ rename = os.rename
+ publish = update_worker.write_record
+ def interrupt_switch(source, destination):
+ if Path(source).name == f".nanobot-original-{spec.plan_id}":
+ raise OSError("Injected interruption between program renames")
+ return rename(source, destination)
+ def interrupt_publish(path, value, **kwargs):
+ if path.name == "restoration.json" and value.get("state") == "restarting":
+ raise OSError("Injected interruption after program switch")
+ return publish(path, value, **kwargs)
+ with monkeypatch.context() as patch:
+ if interrupted == "rename":
+ patch.setattr(os, "rename", interrupt_switch)
+ else:
+ patch.setattr(update_worker, "write_record", interrupt_publish)
+ with pytest.raises(OSError, match="Injected interruption"):
+ restore_program(directory, spec)
+ assert Path(spec.baseline.environment).exists() is (interrupted == "journal")
+ assert read_record(directory / "restoration.json")["state"] == "restoring"
+ restore_program(directory, spec)
+ assert read_record(directory / "restoration.json")["state"] == "restarting"
+ restored = inspect_environment(plan.installation.python)
+ assert restored.app_version == spec.baseline.app_version
+ assert restored.versions == spec.baseline.versions
+ assert (config.read_bytes(), chat.read_bytes()) == before
+ # A new conversation write must never be replaced by the old backup.
+ chat.write_bytes(before[1] + b'{"content":"new message"}\n')
+ with pytest.raises(ValueError, match="User data changed"):
+ require_unchanged_user_data(directory, spec)
+ assert chat.read_bytes().endswith(b'{"content":"new message"}\n')
+
+
[email protected](("outcome", "confirmed"), [
+ ("repaired", False), ("restored", False), ("unsafe", False), ("restored", True),
+])
+async def test_supervisor_has_one_repair_budget_and_replays_transient_restore(installation, tmp_path, monkeypatch, outcome, confirmed):
+ from nanobot import update_fallback
+
+ plan, _, _, _, transport = installation
+ async with ReleaseFeed(tmp_path / "feed", transport=transport) as feed:
+ directory = await prepare_job(plan, feed)
+ spec = replace(WorkerSpec.read(directory), automatic_recovery=True,
+ restart_profiles=(plan.profiles[0].receipt.id,))
+ monkeypatch.setattr(WorkerSpec, "read", classmethod(lambda cls, directory: spec))
+ calls = []
+ restored = []
+ arguments = ["--handoff", str(directory)]
+ confirmation_id = uuid4().hex if confirmed else None
+ now = int(time.time())
+ if confirmation_id is not None:
+ digest = hashlib.sha256((directory / "request.json").read_bytes()).hexdigest()
+ ExecutionConfirmation(confirmation_id, plan.id, digest, now, now + 900).save(directory)
+ write_record(directory / "handoff-approval.json", {
+ "plan_id": plan.id, "request_sha256": digest, "confirmation_id": confirmation_id,
+ "created_at": now, "expires_at": now + 900,
+ })
+ arguments = ["--confirmed-handoff", str(directory), confirmation_id]
+ def child(command, **kwargs):
+ calls.append(command)
+ if len(calls) == 1:
+ if confirmed:
+ monkeypatch.setattr(update_fallback.time, "time", lambda: now + 901)
+ # Abrupt worker exit after admission leaves a non-terminal journal.
+ write_record(directory / "approval.json", {"admitted": True})
+ phase = Phase.INSTALLING
+ else:
+ assert command[-2:] == ["--recover", str(directory)]
+ phase = Phase.SUCCEEDED if outcome == "repaired" else Phase.FAILED
+ JobStatus(spec.plan_id, phase, len(calls), True, "Injected execution result", int(time.time())).save(directory)
+ return subprocess.CompletedProcess(command, 91 if len(calls) == 1 else 0)
+ def restore(path, *, confirmation_id=None):
+ assert confirmation_id == (ExecutionConfirmation.read(directory).id if confirmed else None)
+ restored.append(path)
+ if outcome == "unsafe":
+ raise ValueError("User data changed")
+ if len(restored) == 1:
+ raise OSError("Transient rename failure")
+ JobStatus(spec.plan_id, Phase.RESTORED, 2, True, "Restored", int(time.time())).save(directory)
+ monkeypatch.setattr(update_fallback.subprocess, "run", child)
+ monkeypatch.setattr(update_fallback, "restore_service", restore)
+ update_fallback.supervise(directory, arguments)
+ assert len(calls) == 2
+ assert len(restored) == {"repaired": 0, "restored": 2, "unsafe": 1}[outcome]
+ if outcome == "unsafe":
+ assert read_record(directory / "supervision.json")["state"] == "needs_attention"
+ update_fallback.supervise(directory, arguments)
+ assert len(calls) == 2, "A duplicate launch cannot acquire another recovery budget"
+
+
+async def test_service_restore_refuses_an_activated_candidate(installation, tmp_path):
+ from nanobot.update_fallback import restore_service
+
+ plan, _, _, _, transport = installation
+ async with ReleaseFeed(tmp_path / "feed", transport=transport) as feed:
+ directory = await prepare_job(plan, feed)
+ before = inspect_environment(plan.installation.python)
+ write_record(directory / "activation.json", {"plan_id": plan.id})
+ JobStatus(plan.id, Phase.RESTART_FAILED, 1, True, "Lost readiness after activation", int(time.time())).save(directory)
+ with pytest.raises(ValueError, match="activated"):
+ restore_service(directory)
+ assert inspect_environment(plan.installation.python) == before
+ assert not (directory / "restoration.json").exists()
+
+
+async def test_supervisor_finishes_refused_stop_without_waiting_for_live_gateway(installation, tmp_path, monkeypatch):
+ from nanobot import update_fallback
+
+ plan, _, _, _, transport = installation
+ async with ReleaseFeed(tmp_path / "feed", transport=transport) as feed:
+ directory = await prepare_job(plan, feed)
+ spec = replace(WorkerSpec.read(directory), automatic_recovery=True,
+ restart_profiles=(plan.profiles[0].receipt.id,))
+ monkeypatch.setattr(WorkerSpec, "read", classmethod(lambda cls, directory: spec))
+ def refused(command, **kwargs):
+ JobStatus(spec.plan_id, Phase.HANDOFF_FAILED, 0, False, "Gateway is busy", int(time.time())).save(directory)
+ write_record(installation_state_dir(spec.baseline.environment) / "stop.json",
+ {"plan_id": spec.plan_id, "phase": "abort"})
+ return subprocess.CompletedProcess(command, 1)
+ monkeypatch.setattr(update_fallback.subprocess, "run", refused)
+ def must_not_recover(*args, **kwargs):
+ raise AssertionError("A refused stop must not wait for or restore the still-running gateway")
+ monkeypatch.setattr(update_fallback, "restore_service", must_not_recover)
+ with installation_access(environment=spec.baseline.environment):
+ monkeypatch.setattr(update_fallback.time, "sleep", must_not_recover)
+ update_fallback.supervise(directory, ["--handoff", str(directory)])
+ assert JobStatus.read(directory).phase == Phase.HANDOFF_FAILED
+ assert not (directory / "approval.json").exists()
+
+
[email protected]("installation", ["restart"], indirect=True)
+async def test_service_restore_completes_reservation_after_interrupted_journal(installation, tmp_path, monkeypatch):
+ from nanobot import update_worker
+ from nanobot.update_fallback import restore_service
+
+ plan, _, _, _, transport = installation
+ async with ReleaseFeed(tmp_path / "feed", transport=transport) as feed:
+ directory = await prepare_job(plan, feed)
+ spec = WorkerSpec.read(directory)
+ root = installation_state_dir(spec.baseline.environment)
+ # Backup failed before mutation. Original program is intact; restoration
+ # wrote its journal but failed before reserving data and recording restart.
+ JobStatus(plan.id, Phase.FAILED, 0, False, "Backup failure", int(time.time())).save(directory)
+ write_record(directory / "handoff-approval.json", {
+ "plan_id": spec.plan_id, "request_sha256": hashlib.sha256((directory / "request.json").read_bytes()).hexdigest(),
+ "created_at": int(time.time()), "expires_at": int(time.time()) + 900,
+ })
+ write_record(root / "stop.json", {"plan_id": plan.id, "phase": "stopped"})
+ write_record(directory / "restoration.json", {"plan_id": plan.id, "state": "restarting"})
+ restarts = []
+ def restart(path, request):
+ assert JobStatus.read(path).phase == Phase.RESTARTING
+ assert read_record(pending_update_path(request.baseline.environment))["version"] == request.baseline.app_version
+ restarts.append(path)
+ monkeypatch.setattr(update_worker, "restart_runtime", restart)
+ restore_service(directory)
+ assert restarts == [directory]
+
+
[email protected]("stage", ["baseline", "dependencies", "final-probe"])
+async def test_cancelled_preparation_keeps_lease_until_native_work_exits(installation, monkeypatch, tmp_path, stage):
+ from nanobot import update_jobs
+
+ plan, _, _, _, transport = installation
+ entered, finish = threading.Event(), threading.Event()
+ target = "_prepare_transaction" if stage == "dependencies" else "inspect_environment"
+ original = getattr(update_jobs, target)
+ calls = 0
+
+ def held_preparation(*args, **kwargs):
+ nonlocal calls
+ calls += 1
+ if calls == (2 if stage == "final-probe" else 1):
+ entered.set()
+ assert finish.wait(20)
+ return original(*args, **kwargs)
+
+ monkeypatch.setattr(update_jobs, target, held_preparation)
+ directory = installation_state_dir(plan.installation.environment) / "jobs" / plan.id
+ async with ReleaseFeed(tmp_path / "feed", transport=transport) as feed:
+ preparing = asyncio.create_task(prepare_job(plan, feed))
+ try:
+ assert await asyncio.to_thread(entered.wait, 10)
+ assert JobStatus.read(directory).phase == Phase.PREPARING
+ assert UpdatePlan.model_validate_json((directory / "plan.json").read_bytes()) == plan
+ preparing.cancel()
+ await asyncio.sleep(0)
+ preparing.cancel() # A second shutdown must not release a native writer.
+ await asyncio.sleep(0)
+ assert not preparing.done()
+ assert JobStatus.read(directory).phase == Phase.PREPARING
+ with pytest.raises(InstallationBusyError):
+ with installation_access(updating=True, environment=plan.installation.environment):
+ pytest.fail("Native preparation lost its installation lease")
+ with pytest.raises(BlockingIOError):
+ await prepare_job(plan, feed)
+ finally:
+ finish.set()
+ with pytest.raises(asyncio.CancelledError):
+ await preparing
+ assert JobStatus.read(directory).phase == Phase.PREPARATION_FAILED
+ assert not (directory / "request.json").exists()
+ assert not (directory / "approval.json").exists()
+ directory = await prepare_job(plan, feed)
+ assert JobStatus.read(directory).phase == Phase.READY
+ assert inspect_environment(plan.installation.python).app_version == "0.3.4"
+
+
+async def test_failed_download_retains_private_exact_job_for_retry(installation, monkeypatch, tmp_path):
+ plan, _, _, _, transport = installation
+ directory = installation_state_dir(plan.installation.environment) / "jobs" / plan.id
+
+ async def unavailable(*args):
+ raise httpx.ConnectError("https://user:[email protected]")
+
+ async with ReleaseFeed(tmp_path / "feed", transport=transport) as feed:
+ with monkeypatch.context() as patch:
+ patch.setattr(feed, "download", unavailable)
+ with pytest.raises(httpx.ConnectError):
+ await prepare_job(plan, feed)
+ status = JobStatus.read(directory)
+ assert status.phase == Phase.PREPARATION_FAILED and not status.mutation_started
+ assert "secret" not in (directory / "status.json").read_text()
+ saved = (directory / "plan.json").read_bytes()
+ changed = plan.model_copy(update={"expires_at": plan.expires_at - 1})
+ with pytest.raises(ValueError, match="another reviewed plan"):
+ await prepare_job(changed, feed)
+ assert (directory / "plan.json").read_bytes() == saved
+ assert not (directory / "request.json").exists()
+ assert await prepare_job(plan, feed) == directory
+ assert JobStatus.read(directory).phase == Phase.READY
+ assert inspect_environment(plan.installation.python).app_version == "0.3.4"
+
+
+async def test_release_approval_refusal_preserves_original_installation(installation, tmp_path, monkeypatch):
+ plan, _, _, _, transport = installation
+ before = inspect_environment(plan.installation.python)
+ monkeypatch.setattr(ReleaseFeed, "_authorize", AsyncMock(side_effect=ValueError("Unapproved release")))
+ async with ReleaseFeed(tmp_path / "feed", transport=transport) as feed:
+ with pytest.raises(ValueError, match="Unapproved release"):
+ await prepare_job(plan, feed)
+ directory = installation_state_dir(plan.installation.environment) / "jobs" / plan.id
+ assert not (directory / "request.json").exists()
+ # The current-version recovery launcher may already be staged, but no
+ # verified request may authorize it to mutate the installation.
+ assert not (directory / "wheels").exists()
+ assert inspect_environment(plan.installation.python) == before
+
+
+def _preparer_script(plan: UpdatePlan, candidate: Path, cache: Path, hook: str) -> str:
+ source = Path(__file__).resolve().parents[1]
+ return f"""
+import asyncio, os, sys
+from pathlib import Path
+sys.path.insert(0, {str(source)!r})
+import httpx
+from nanobot import update_jobs, update_worker
+from nanobot.release_feed import ReleaseFeed
+from nanobot.update_plan import UpdatePlan
+from nanobot.releases import release_filenames
+async def private_fixture_approval(self, target):
+ # Unsigned lifecycle fixture; public publication authority is tested separately.
+ pass
+ReleaseFeed._authorize = private_fixture_approval
+plan = UpdatePlan.model_validate_json({plan.model_dump_json()!r})
+{hook}
+def response(request):
+ if request.url.host == 'files.pythonhosted.org':
+ return httpx.Response(200, content=Path({str(candidate)!r}).read_bytes())
+ assert request.url.path == '/pypi/nanobot-ai/0.3.5/json'
+ files = [dict(filename=name, size=plan.target.artifact.size if name == plan.target.artifact.filename else 1,
+ url='https://files.pythonhosted.org/packages/' + name, yanked=False,
+ digests=dict(sha256=plan.target.artifact.sha256 if name == plan.target.artifact.filename else 'a' * 64))
+ for name in release_filenames(plan.target.version) if name.endswith(('.whl', '.tar.gz'))]
+ return httpx.Response(200, json=dict(info=dict(name='nanobot-ai', version=plan.target.version,
+ requires_python='>=3.11'), urls=files))
+async def run():
+ async with ReleaseFeed(Path({str(cache)!r}), transport=httpx.MockTransport(response)) as feed:
+ await update_jobs.prepare_job(plan, feed)
+asyncio.run(run())
+"""
+
+
+async def test_abrupt_preparer_exit_does_not_authorize_staging_reuse(installation, tmp_path):
+ plan, candidate, _, _, transport = installation
+ directory = installation_state_dir(plan.installation.environment) / "jobs" / plan.id
+ script = _preparer_script(plan, candidate, tmp_path / "feed", "update_jobs._prepare_transaction = lambda *args: os._exit(0)")
+ process = await asyncio.to_thread(subprocess.run, [sys.executable, "-I", "-c", script],
+ capture_output=True, timeout=30)
+ assert process.returncode == 0, process.stderr.decode()
+ saved_status = (directory / "status.json").read_bytes()
+ assert JobStatus.read(directory).phase == Phase.PREPARING
+ async with ReleaseFeed(tmp_path / "retry-feed") as feed:
+ with pytest.raises(ValueError, match="previous preparation did not settle"):
+ await prepare_job(plan, feed)
+ assert (directory / "status.json").read_bytes() == saved_status
+ assert not (directory / "request.json").exists()
+ assert not (directory / "approval.json").exists()
+ assert inspect_environment(plan.installation.python).app_version == "0.3.4"
+ assert settle_interrupted_preparation(directory).phase == Phase.PREPARATION_FAILED
+ async with ReleaseFeed(tmp_path / "retry-feed", transport=transport) as feed:
+ assert await prepare_job(plan, feed) == directory
+ assert JobStatus.read(directory).phase == Phase.READY
+
+
[email protected]("stage", ["probe", "pip"])
+async def test_orphan_preparation_owns_lease_until_real_native_exit(installation, tmp_path, stage):
+ plan, candidate, _, _, transport = installation
+ root = installation_state_dir(plan.installation.environment)
+ directory = root / "jobs" / plan.id
+ ready, release = tmp_path / "native-ready", tmp_path / "native-release"
+ hold = (
+ "import os, time\nfrom pathlib import Path\n"
+ f"Path({str(ready)!r}).write_text(str(os.getpid()))\n"
+ "deadline=time.monotonic()+15\n"
+ f"while not Path({str(release)!r}).exists():\n"
+ " if time.monotonic()>deadline: raise RuntimeError('Native test wait expired')\n"
+ " time.sleep(0.01)\n"
+ )
+ if stage == "pip":
+ site = subprocess.check_output([plan.installation.python, "-I", "-c",
+ "import sysconfig; print(sysconfig.get_path('purelib'))"], text=True).strip()
+ launcher = Path(site) / "pip/__main__.py"
+ original = launcher.read_text()
+ launcher.write_text(hold + f"exec(compile({original!r}, __file__, 'exec'))\n")
+ hook = ""
+ else:
+ hook = f"update_worker._PROBE = {hold!r} + update_worker._PROBE"
+ script = _preparer_script(plan, candidate, tmp_path / "feed", hook)
+ parent = subprocess.Popen([sys.executable, "-I", "-c", script], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+ try:
+ async with asyncio.timeout(12):
+ while not ready.exists():
+ assert parent.poll() is None, "Preparer exited before its native command started"
+ await asyncio.sleep(0.01)
+ prior = PreparationProcess.load(directory.resolve())
+ parent.kill()
+ await asyncio.to_thread(parent.wait, 10)
+ # The runtime's Windows implementation uses a process handle, not signal 0.
+ assert GatewayRuntime().process_is_running(int(ready.read_text()))
+ with pytest.raises(InstallationBusyError):
+ with installation_access(updating=True, environment=plan.installation.environment):
+ pytest.fail("Parent death released a live preparation's runtime lease")
+ with pytest.raises(BlockingIOError):
+ settle_interrupted_preparation(directory)
+ async with ReleaseFeed(tmp_path / "other-feed", transport=transport) as feed:
+ with pytest.raises(BlockingIOError):
+ await prepare_job(plan.model_copy(update={"id": str(uuid4())}), feed)
+ assert not (directory / "request.json").exists()
+ assert JobStatus.read(directory).phase == Phase.PREPARING
+ finally:
+ release.touch()
+ if parent.poll() is None:
+ parent.kill()
+ await asyncio.to_thread(parent.wait, 10)
+ # Wait for the child's actual OS lease, not a stale PID or status file.
+ async with asyncio.timeout(15):
+ while True:
+ try:
+ with file_access(root / "prepare-native.lock", exclusive=True):
+ break
+ except BlockingIOError:
+ await asyncio.sleep(0.01)
+ if stage == "pip":
+ launcher.write_text(original)
+ if stage == "pip":
+ # Recovery itself can exit between revocation and saving the new phase.
+ # Re-entering it must finish the journal, not revive the old generation.
+ with file_access(root / "prepare.lock", exclusive=True), file_access(root / "prepare-native.lock", exclusive=True):
+ prior.close()
+ assert settle_interrupted_preparation(directory).phase == Phase.PREPARATION_FAILED
+ assert not (directory / "approval.json").exists()
+ # A child delayed before locking must not revive after a new generation starts.
+ marker = tmp_path / "late-child-must-not-run"
+ with file_access(root / "prepare.lock", exclusive=True), file_access(root / "prepare-native.lock", exclusive=True):
+ replacement = PreparationProcess.create(directory, plan.installation.environment)
+ result = await asyncio.to_thread(prior.run, plan.installation.python,
+ ["-c", f"from pathlib import Path; Path({str(marker)!r}).touch()"], timeout=15)
+ assert result.returncode != 0 and not marker.exists()
+ replacement.close()
+ async with ReleaseFeed(tmp_path / "retry-feed", transport=transport) as feed:
+ assert await prepare_job(plan, feed) == directory
+ assert JobStatus.read(directory).phase == Phase.READY
+ assert inspect_environment(plan.installation.python).app_version == "0.3.4"
+
+
[email protected](os.name != "posix", reason="Checks actual POSIX flock ownership during Python site startup")
+async def test_preparation_lease_covers_site_startup_and_exit_cleanup(installation, tmp_path):
+ plan, _, _, _, transport = installation
+ root = installation_state_dir(plan.installation.environment)
+ site = subprocess.check_output([plan.installation.python, "-I", "-c",
+ "import sysconfig; print(sysconfig.get_path('purelib'))"], text=True).strip()
+ hook = Path(site) / "preparation_lease_test.pth"
+ observed = tmp_path / "site-loaded-under-child-lease"
+ exited = tmp_path / "exit-cleanup-under-child-lease"
+ script = (
+ "import atexit, fcntl, os\nfrom pathlib import Path\n"
+ "def verify_lease():\n"
+ f" with open({str(root / 'prepare-native.lock')!r}, 'a+b') as lease:\n"
+ " try: fcntl.flock(lease, fcntl.LOCK_EX | fcntl.LOCK_NB)\n"
+ " except BlockingIOError: pass\n"
+ " else: os._exit(99)\n"
+ "verify_lease()\n"
+ f"Path({str(observed)!r}).touch()\n"
+ "def verify_exit():\n"
+ " verify_lease()\n"
+ f" Path({str(exited)!r}).touch()\n"
+ "atexit.register(verify_exit)\n"
+ )
+ hook.write_text(f"import builtins; builtins.exec({script!r}, {{}})\n")
+ try:
+ async with ReleaseFeed(tmp_path / "feed", transport=transport) as feed:
+ directory = await prepare_job(plan, feed)
+ assert JobStatus.read(directory).phase == Phase.READY
+ assert observed.exists(), "Site startup was skipped instead of protected"
+ assert exited.exists(), "Exit cleanup was skipped instead of protected"
+ finally:
+ hook.unlink()
+
+
[email protected](os.name != "posix", reason="Checks actual flock ownership in site and atexit hooks")
[email protected]("installation", ["handoff"], indirect=True)
[email protected]("refuse", [False, True])
+async def test_execution_leases_cover_site_and_atexit(installation, tmp_path, refuse):
+ """Real frozen children and pip; handoff/restart bodies are routing fixtures."""
+ plan, _, site, _, transport = installation
+ async with ReleaseFeed(tmp_path / "feed", transport=transport) as feed:
+ directory = await prepare_job(plan, feed)
+ root = installation_state_dir(plan.installation.environment)
+ leases = {
+ "--prepare-handoff": [str(root / "runtime.lock"), str(root / "handoff-child.lock")],
+ "--inspect": [str(root / "runtime.lock"), str(root.parent / "data-locks/maintenance.lock")],
+ "--install": [str(root / "runtime.lock"), str(root.parent / "data-locks/maintenance.lock")],
+ "--verify": [str(root / "runtime.lock"), str(root.parent / "data-locks/maintenance.lock")],
+ "--restart": [str(root / "runtime.lock")],
+ }
+ hook = site / "execution_lease_test.pth"
+ observed = tmp_path / "execution-hooks"
+ observed.mkdir()
+ script = (
+ "import atexit, fcntl, os, sys\nfrom pathlib import Path\n"
+ f"leases = {leases!r}\n"
+ "entry = sys.argv[1] if len(sys.argv) > 1 else ''\n"
+ "if entry in leases:\n"
+ " def verify(stage):\n"
+ " for path in leases[entry]:\n"
+ " with open(path, 'a+b') as lease:\n"
+ " try: fcntl.flock(lease, fcntl.LOCK_EX | fcntl.LOCK_NB)\n"
+ " except BlockingIOError: pass\n"
+ " else: os._exit(99)\n"
+ f" (Path({str(observed)!r}) / (entry + '.' + stage)).touch()\n"
+ " verify('site')\n"
+ " atexit.register(verify, 'atexit')\n"
+ )
+ hook.write_text(f"import builtins; builtins.exec({script!r}, {{}})\n")
+ if refuse:
+ (directory / "refuse-preflight").touch()
+ try:
+ process = start_handoff(directory, once=True)
+ assert process is not None
+ code = await asyncio.to_thread(process.wait, 40)
+ assert (code != 0) is refuse
+ assert JobStatus.read(directory).phase == (Phase.HANDOFF_FAILED if refuse else Phase.SUCCEEDED)
+ entries = ["--prepare-handoff"] if refuse else list(leases)
+ assert {path.name for path in observed.iterdir()} == {
+ entry + "." + stage for entry in entries for stage in ("site", "atexit")
+ }
+ # Exit cleanup completed and all process-owned leases really released.
+ with (installation_access(updating=True, environment=plan.installation.environment),
+ data_access((source.path for source in WorkerSpec.read(directory).backup_sources), updating=True),
+ file_access(root / "handoff-child.lock", exclusive=True)):
+ pass
+ finally:
+ hook.unlink()
+
+
[email protected]("stage", ["site", "atexit"])
+async def test_admission_probe_keeps_its_leases_after_caller_loss(installation, tmp_path, stage):
+ """Kill a disposable start_job caller, not the interpreter doing its probe."""
+ plan, _, site, _, transport = installation
+ async with ReleaseFeed(tmp_path / "feed", transport=transport) as feed:
+ directory = await prepare_job(plan, feed)
+ ready, release = tmp_path / "inspection-ready", tmp_path / "inspection-release"
+ hook = site / "inspection_lifetime_test.pth"
+ action = "hold()" if stage == "site" else "atexit.register(hold)"
+ script = (
+ "import atexit, os, sys, time\nfrom pathlib import Path\n"
+ "def hold():\n"
+ f" Path({str(ready)!r}).write_text(str(os.getpid()))\n"
+ " deadline = time.monotonic() + 20\n"
+ f" while not Path({str(release)!r}).exists():\n"
+ " if time.monotonic() > deadline: raise RuntimeError('Inspection wait expired')\n"
+ " time.sleep(0.01)\n"
+ f"if '--inspect' in sys.argv: {action}\n"
+ )
+ hook.write_text(f"import builtins; builtins.exec({script!r}, {{}})\n")
+ caller_pid = tmp_path / "caller-pid"
+ caller = (
+ "import os\nfrom pathlib import Path\n"
+ f"Path({str(caller_pid)!r}).write_text(str(os.getpid()))\n"
+ "import asyncio\n"
+ "from nanobot.update_jobs import start_job\n"
+ "class Feed:\n"
+ " async def revalidate(self, target): pass\n"
+ f"asyncio.run(start_job(Path({str(directory)!r}), Feed()))\n"
+ )
+ process = subprocess.Popen([sys.executable, "-c", caller], cwd=Path(__file__).parents[1],
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+ def kill_caller():
+ if process.poll() is None:
+ # Windows venv python.exe is a redirector. Kill the actual
+ # caller, not its launcher or the separately leased probe.
+ if caller_pid.exists():
+ os.kill(int(caller_pid.read_text()), signal.SIGTERM if os.name == "nt" else signal.SIGKILL)
+ else:
+ process.kill()
+ try:
+ async with asyncio.timeout(15):
+ while not ready.exists():
+ assert process.poll() is None
+ await asyncio.sleep(0.01)
+ assert int(caller_pid.read_text()) != int(ready.read_text())
+ kill_caller()
+ await asyncio.to_thread(process.wait, 10)
+ assert GatewayRuntime().process_is_running(int(ready.read_text()))
+ with pytest.raises(InstallationBusyError):
+ with installation_access(updating=True, environment=plan.installation.environment):
+ pytest.fail("The inspection lost its installation lease with its caller")
+ with pytest.raises(InstallationBusyError):
+ with data_access([Path(plan.profiles[0].receipt.data_dir) / "sessions"]):
+ pytest.fail("The inspection lost its data lease with its caller")
+ with pytest.raises(InstallationBusyError):
+ await start_job(directory, feed)
+ assert JobStatus.read(directory).phase == Phase.READY
+ assert not (directory / "approval.json").exists()
+ assert not pending_update_path(plan.installation.environment).exists()
+ finally:
+ release.touch()
+ kill_caller()
+ await asyncio.to_thread(process.wait, 10)
+ async with asyncio.timeout(20):
+ while True:
+ try:
+ with installation_access(updating=True, environment=plan.installation.environment):
+ break
+ except InstallationBusyError:
+ await asyncio.sleep(0.01)
+ hook.unlink()
+ await wait_worker(await start_job(directory, feed))
+ assert JobStatus.read(directory).phase == Phase.INSTALLED
+
+
[email protected]("stage", ["site", "dependencies", "atexit"])
+async def test_verification_keeps_its_leases_after_coordinator_loss(installation, tmp_path, stage):
+ """Pause actual site/pip/atexit in a disposable target, not a mocked subprocess."""
+ plan, _, site, _, transport = installation
+ ready, release = tmp_path / "verification-ready", tmp_path / "verification-release"
+ hook = site / "verification_lifetime_test.pth"
+ launcher = site / "pip/__main__.py"
+ original = launcher.read_text()
+ hold = (
+ "import os, time\nfrom pathlib import Path\n"
+ "def hold():\n"
+ f" Path({str(ready)!r}).write_text(str(os.getpid()))\n"
+ " deadline = time.monotonic() + 20\n"
+ f" while not Path({str(release)!r}).exists():\n"
+ " if time.monotonic() > deadline: raise RuntimeError('Verification wait expired')\n"
+ " time.sleep(0.01)\n"
+ )
+ async with ReleaseFeed(tmp_path / "feed", transport=transport) as feed:
+ directory = await prepare_job(plan, feed)
+ if stage == "dependencies":
+ launcher.write_text(hold + "import sys\nif sys.argv[1:] == ['check']: hold()\n"
+ + f"exec(compile({original!r}, __file__, 'exec'))\n")
+ else:
+ action = "hold()" if stage == "site" else "atexit.register(hold)"
+ script = hold + "import atexit, sys\n" + f"if '--verify' in sys.argv: {action}\n"
+ hook.write_text(f"import builtins; builtins.exec({script!r}, {{}})\n")
+ process = await start_job(directory, feed)
+ try:
+ async with asyncio.timeout(15):
+ while not ready.exists():
+ assert process.poll() is None, JobStatus.read(directory)
+ await asyncio.sleep(0.01)
+ assert JobStatus.read(directory).phase == Phase.VERIFYING
+ process.kill()
+ await asyncio.to_thread(process.wait, 10)
+ assert GatewayRuntime().process_is_running(int(ready.read_text()))
+ with pytest.raises(InstallationBusyError):
+ with installation_access(updating=True, environment=plan.installation.environment):
+ pytest.fail("A live verification lost its installation lease")
+ with pytest.raises(InstallationBusyError, match="data is in use"):
+ with data_access([Path(plan.profiles[0].receipt.data_dir) / "sessions"]):
+ pytest.fail("A live verification lost its data lease")
+ with pytest.raises(InstallationBusyError):
+ await start_job(directory, feed, repair=True)
+ assert JobStatus.read(directory).phase == Phase.VERIFYING
+ finally:
+ release.touch()
+ if process.poll() is None:
+ process.kill()
+ await asyncio.to_thread(process.wait, 10)
+ async with asyncio.timeout(20):
+ while True:
+ try:
+ with installation_access(updating=True, environment=plan.installation.environment):
+ break
+ except InstallationBusyError:
+ await asyncio.sleep(0.01)
+ hook.unlink(missing_ok=True)
+ launcher.write_text(original)
+ # The orphan does not announce success or release the durable fence.
+ assert JobStatus.read(directory).phase == Phase.VERIFYING
+ assert pending_update_path(plan.installation.environment).exists()
+ backup = (directory / "backup/data.zip").read_bytes()
+ await wait_worker(await start_job(directory, feed, repair=True))
+ assert JobStatus.read(directory).phase == Phase.INSTALLED
+ assert (directory / "backup/data.zip").read_bytes() == backup
+ assert not pending_update_path(plan.installation.environment).exists()
+
+
+async def test_verification_requires_its_own_completion_checkpoint(installation, tmp_path):
+ plan, _, site, _, transport = installation
+ async with ReleaseFeed(tmp_path / "feed", transport=transport) as feed:
+ directory = await prepare_job(plan, feed)
+ hook = site / "verification_exit_test.pth"
+ # A previously successful verification record cannot bless a new
+ # interpreter that exits 0 during site initialization.
+ write_record(directory / "verification.json", {"id": uuid4().hex})
+ hook.write_text("import sys; sys.exit(0) if '--verify' in sys.argv else None\n")
+ try:
+ process = await start_job(directory, feed)
+ assert await asyncio.to_thread(process.wait, 40) != 0
+ status = JobStatus.read(directory)
+ assert status.phase == Phase.FAILED and status.mutation_started
+ assert "verification did not finish" in status.message
+ assert pending_update_path(plan.installation.environment).exists()
+ finally:
+ hook.unlink()
+
+
+async def test_installed_cleanup_recovery_reverifies_without_reinstalling(installation, tmp_path, monkeypatch):
+ """Exit after the real result write, before its pending/data fences are removed."""
+ plan, _, site, _, transport = installation
+ original_popen = subprocess.Popen
+ wrapper = """
+import os, sys
+from pathlib import Path
+sys.path.insert(0, sys.argv[1])
+from _nanobot_update import update_worker
+original_save = update_worker.JobStatus.save
+def save(status, directory):
+ original_save(status, directory)
+ if status.phase == update_worker.Phase.INSTALLED:
+ os._exit(91)
+update_worker.JobStatus.save = save
+update_worker.run_job(Path(sys.argv[2]))
+"""
+
+ def launch(command, **kwargs):
+ if len(command) == 5 and str(command[3]).endswith("worker.pyz"):
+ command = [command[0], "-I", "-S", "-c", wrapper, command[3], command[4]]
+ return original_popen(command, **kwargs)
+
+ async with ReleaseFeed(tmp_path / "feed", transport=transport) as feed:
+ directory = await prepare_job(plan, feed)
+ with monkeypatch.context() as patch:
+ patch.setattr(subprocess, "Popen", launch)
+ process = await start_job(directory, feed)
+ assert await asyncio.to_thread(process.wait, 40) == 91
+ before = JobStatus.read(directory)
+ assert before.phase == Phase.INSTALLED and before.attempt == 1
+ pending = pending_update_path(plan.installation.environment)
+ assert pending.exists()
+ checkpoint = (directory / "verification.json").read_bytes()
+ record = site / "nanobot_ai-0.3.5.dist-info/RECORD"
+ record_time = record.stat().st_mtime_ns
+ backup = (directory / "backup/data.zip").read_bytes()
+ spec = WorkerSpec.read(directory)
+ recovery = subprocess.Popen([spec.baseline.base_python, "-I", str(directory / "worker.pyz"), str(directory)],
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+ await wait_worker(recovery)
+ assert JobStatus.read(directory) == before
+ assert (directory / "verification.json").read_bytes() != checkpoint
+ assert record.stat().st_mtime_ns == record_time
+ assert (directory / "backup/data.zip").read_bytes() == backup
+ assert not pending.exists()
+ with data_access([Path(plan.profiles[0].receipt.data_dir) / "sessions"]):
+ pass
diff --git a/tests/test_update_manager.py b/tests/test_update_manager.py
new file mode 100644
index 000000000..98e4f9751
--- /dev/null
+++ b/tests/test_update_manager.py
@@ -0,0 +1,123 @@
+"""Receipt fixtures match uv 0.11.16 and pipx 1.7.1/1.17.13 private-manager probes."""
+
+import hashlib
+import json
+
+import pytest
+
+from nanobot.update_manager import read_manager_policy
+
+
+def read(tmp_path, manager, data):
+ raw = data.encode() if isinstance(data, str) else json.dumps(data).encode()
+ path = tmp_path / ("uv-receipt.toml" if manager == "uv" else "pipx_metadata.json")
+ path.write_bytes(raw)
+ result = read_manager_policy(tmp_path, manager, hashlib.sha256(raw).hexdigest())
+ assert path.read_bytes() == raw, "Inspection must never rewrite the manager's receipt"
+ return result
+
+
+def pipx_record(**main):
+ return {"pipx_metadata_version": "0.12", "backend": "pip", "main_package": {
+ "package": "nanobot-ai", "package_or_url": "nanobot-ai[webui]>=0.3.4,<0.4", **main,
+ }, "injected_packages": {"fixture-plugin": {
+ "package": "fixture-plugin", "package_or_url": "fixture-plugin==1.0.0",
+ }}}
+
+
+def test_uv_intent_preserves_extras_constraints_and_injected_packages(tmp_path):
+ policy = read(tmp_path, "uv", '''[tool]
+requirements = [
+ { name = "nanobot-ai", extras = ["webui", "image_gen"], specifier = ">=0.3.4,<0.4" },
+ { name = "fixture-plugin", specifier = "==1.0.0" }
+]
+[tool.options]
+index-url = "https://private-user:[email protected]/simple"
+''')
+ assert policy.extras == ["image-gen", "webui"]
+ assert policy.injected_packages == ["fixture-plugin"]
+ assert policy.restriction("0.3.6.dev1") is None
+ assert "constraints" in policy.restriction("0.4.0")
+ assert "fixture-secret" not in policy.model_dump_json()
+
+
[email protected]("main,reason", [
+ ({"pinned": True}, "pinned"),
+ ({"lock_file": {"__type__": "Path", "__Path__": "/private/pylock.toml"}}, "lock file"),
+ ({"package_or_url": "nanobot-ai[webui]==0.3.4"}, "constraints"),
+ ({"package_or_url": "nanobot-ai[webui] @ git+https://example.invalid/nanobot.git"}, "manual review"),
+ ({"package_or_url": "/private/custom-source"}, "manual review"),
+])
+def test_pipx_pins_locks_and_nonregistry_sources_are_not_silently_replaced(tmp_path, main, reason):
+ policy = read(tmp_path, "pipx", pipx_record(**main))
+ assert reason in policy.restriction("0.3.5")
+ assert policy.injected_packages == ["fixture-plugin"]
+
+
+def test_pipx_named_wheel_preserves_extras_without_recording_credential_url(tmp_path):
+ policy = read(tmp_path, "pipx", pipx_record(
+ package_or_url="nanobot-ai[webui] @ https://private:[email protected]/nanobot.whl",
+ ))
+ assert policy.source == "artifact"
+ assert policy.extras == ["webui"]
+ assert policy.restriction("0.3.5") is None
+ assert "fixture-secret" not in policy.model_dump_json()
+
+
+def test_older_pipx_receipt_keeps_extras_and_pin_without_metadata_migration(tmp_path):
+ record = pipx_record(pinned=True, package_or_url="nanobot-ai[webui] @ file:///private/nanobot.whl")
+ record["pipx_metadata_version"] = "0.5"
+ del record["backend"] # pipx 1.7.1 only had the pip backend.
+ policy = read(tmp_path, "pipx", record)
+ assert policy.backend == "pip"
+ assert policy.extras == ["webui"]
+ assert policy.injected_packages == ["fixture-plugin"]
+ assert "pinned" in policy.restriction("0.3.5")
+
+
+ {"package_or_url": "nanobot-ai>=0.3.4,<0.4"},
+ {"package_or_url": "nanobot-ai", "pip_args": ["--index-url", "https://user:[email protected]/simple"]},
+])
+def test_pipx_generic_upgrade_cannot_discard_original_install_policy(tmp_path, main):
+ policy = read(tmp_path, "pipx", pipx_record(**main))
+ assert "generic pipx upgrade" in policy.restriction("0.3.5")
+ assert "fixture-secret" not in policy.model_dump_json()
+
+
+def test_changed_receipt_is_rejected_between_probe_and_read(tmp_path):
+ path = tmp_path / "pipx_metadata.json"
+ raw = json.dumps(pipx_record()).encode()
+ path.write_bytes(raw)
+ path.write_text(json.dumps(pipx_record(pinned=True)))
+ with pytest.raises(ValueError, match="Could not verify"):
+ read_manager_policy(tmp_path, "pipx", hashlib.sha256(raw).hexdigest())
+
+
[email protected]("change", [
+ {"pipx_metadata_version": "future-version"},
+ {"main_package": {"package": "other-package", "package_or_url": "other-package"}},
+ {"main_package": {"package": "nanobot-ai", "package_or_url": {"token": "fixture-secret"}}},
+])
+def test_unconfirmed_receipts_fail_without_leaking_parser_input(tmp_path, change):
+ with pytest.raises(ValueError, match="Could not verify") as failure:
+ read(tmp_path, "pipx", {**pipx_record(), **change})
+ assert "fixture-secret" not in str(failure.value)
+
+
+def test_uv_unknown_requirement_semantics_require_review(tmp_path):
+ policy = read(tmp_path, "uv", '''[tool]
+requirements = [{ name = "nanobot-ai", directory = "/private/checkout", editable = true }]
+''')
+ assert policy.source == "unrecognized"
+ assert "manual review" in policy.restriction("0.3.5")
+
+
+def test_uv_wheel_url_is_not_misrepresented_as_an_overridable_registry_requirement(tmp_path):
+ # A real uv tool upgrade retains this URL even when a newer wheel is passed.
+ # Refuse before shutdown instead of discovering an offline-cache miss afterwards.
+ policy = read(tmp_path, "uv", '''[tool]
+requirements = [{ name = "nanobot-ai", url = "https://example.invalid/nanobot_ai-0.3.5-py3-none-any.whl" }]
+''')
+ assert policy.source == "artifact"
+ assert "bound to a wheel URL" in policy.restriction("0.3.6")
diff --git a/tests/test_update_plan.py b/tests/test_update_plan.py
new file mode 100644
index 000000000..34e9c1170
--- /dev/null
+++ b/tests/test_update_plan.py
@@ -0,0 +1,257 @@
+import hashlib
+import json
+import subprocess
+import sys
+from pathlib import Path
+from unittest.mock import AsyncMock
+from uuid import uuid4
+
+import httpx
+import pytest
+import typer
+from packaging.tags import Tag
+from rich.text import Text
+from typer.testing import CliRunner
+
+from nanobot.cli.update import update as update_command
+from nanobot.installation_lock import InstallationBusyError, installation_access
+from nanobot.release_feed import ReleaseFeed, ReleaseTarget
+from nanobot.releases import ReleaseArtifact, release_filenames
+from nanobot.update_manager import ManagerPolicy
+from nanobot.update_plan import InstallationSnapshot, UpdatePlan, UpdatePlans, inspect_installation
+
+
+def installation(version="0.3.4", running=None, **changes):
+ return InstallationSnapshot(
+ environment="/test/venv", python="/test/venv/bin/python", installed_version=version,
+ package_path="/test/venv/lib/nanobot/__init__.py", running_version=running or version,
+ running_package="/test/venv/lib/nanobot/__init__.py", owner="venv", records=changes,
+ )
+
+
+def target():
+ name = "nanobot_ai-0.3.5-py3-none-win_amd64.whl"
+ return ReleaseTarget(version="0.3.5", source="pypi", url=f"https://files.pythonhosted.org/packages/{name}",
+ artifact=ReleaseArtifact(filename=name, size=123, sha256="a" * 64))
+
+
+def plan(snapshot=None):
+ return UpdatePlan(id=str(uuid4()), installation=snapshot or installation(), channel="stable",
+ target=target(), created_at=100, expires_at=1000)
+
+
[email protected]("installed,running,action", [
+ ("0.3.4", "0.3.4", "upgrade"), ("0.3.5", "0.3.5", "none"),
+ ("0.3.5", "0.3.4", "restart"), ("0.3.6.dev1", "0.3.6.dev1", "downgrade"),
+ ("0.3.4", "0.3.6.dev1", "downgrade"),
+])
+def test_action_reports_actual_installed_and_running_versions(installed, running, action):
+ assert plan(installation(installed, running)).action == action
+
+
+def test_saved_plan_survives_a_new_store_and_cannot_be_replaced(tmp_path):
+ original = plan()
+ store = UpdatePlans(tmp_path / "plans")
+ store.save(original)
+ assert UpdatePlans(store.directory).load(original.id) == original
+ assert store.save(original) == original
+ changed = original.model_copy(update={"expires_at": 999})
+ with pytest.raises(ValueError, match="cannot be replaced"):
+ store.save(changed)
+ if sys.platform != "win32":
+ assert (store.directory / f"{original.id}.json").stat().st_mode & 0o777 == 0o600
+
+
+def test_plan_expiry_environment_and_owner_receipt_are_binding():
+ original = plan()
+ original.validate_for(installation(), now=999)
+ with pytest.raises(ValueError, match="expired"):
+ original.validate_for(installation(), now=1000)
+ with pytest.raises(ValueError, match="Installation changed"):
+ original.validate_for(installation("0.3.5"), now=200)
+ with pytest.raises(ValueError, match="Installation changed"):
+ original.validate_for(installation(**{"uv-receipt.toml": "b" * 64}), now=200)
+ other = installation().model_copy(update={"environment": "/other/venv"})
+ with pytest.raises(ValueError, match="Installation changed"):
+ original.validate_for(other, now=200)
+
+
+def test_plan_id_cannot_escape_private_directory(tmp_path):
+ with pytest.raises(ValueError):
+ UpdatePlans(tmp_path).load("../../config")
+
+
+async def test_prepare_and_revalidate_cross_the_same_feed_interface_without_installer(tmp_path, monkeypatch):
+ monkeypatch.setattr(ReleaseFeed, "_authorize", AsyncMock())
+ requests = []
+
+ def handler(request):
+ requests.append(str(request.url))
+ return httpx.Response(200, json={
+ "info": {"name": "nanobot-ai", "version": "0.3.5", "requires_python": ">=3.11"},
+ "urls": [{"filename": name, "size": 123, "digests": {"sha256": "a" * 64},
+ "url": f"https://files.pythonhosted.org/packages/{name}", "yanked": False}
+ for name in release_filenames("0.3.5") if name.endswith((".whl", ".tar.gz"))],
+ })
+
+ async with ReleaseFeed(tmp_path / "cache", transport=httpx.MockTransport(handler),
+ supported_tags=[Tag("py3", "none", "win_amd64")]) as feed:
+ store = UpdatePlans(tmp_path / "plans")
+ saved = await store.prepare(installation(), "stable", feed, now=100)
+ assert saved.target == target()
+ assert await store.revalidate(saved.id, installation(), feed, now=101) == saved
+ assert requests == ["https://pypi.org/pypi/nanobot-ai/json", "https://pypi.org/pypi/nanobot-ai/0.3.5/json"]
+
+
+def test_probe_reads_fresh_interpreter_and_owner_receipt(tmp_path, monkeypatch):
+ import venv
+
+ from nanobot import update_plan, update_process
+
+ account = tmp_path / "private account"
+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: account))
+ monkeypatch.setattr(update_process, "_INSPECTION_BOOTSTRAP", (
+ "from pathlib import Path\n"
+ f"Path.home = classmethod(lambda cls: Path({str(account)!r}))\n"
+ ) + update_process._INSPECTION_BOOTSTRAP)
+
+ root = tmp_path / "env with spaces"
+ venv.EnvBuilder(with_pip=False).create(root)
+ executable = root / ("Scripts/python.exe" if sys.platform == "win32" else "bin/python")
+ site = Path(subprocess.check_output([str(executable), "-I", "-c",
+ "import sysconfig; print(sysconfig.get_path('purelib'))"], text=True).strip())
+ (site / "nanobot").mkdir()
+ (site / "nanobot/__init__.py").write_text("__version__='0.3.5'\n")
+ dist = site / "nanobot_ai-0.3.5.dist-info"
+ dist.mkdir()
+ (dist / "METADATA").write_text("Metadata-Version: 2.1\nName: nanobot-ai\nVersion: 0.3.5\n")
+ receipt = {"pipx_metadata_version": "0.12", "main_package": {
+ "package": "nanobot-ai", "package_or_url": "nanobot-ai[webui]", "pinned": False,
+ }}
+ (root / "pipx_metadata.json").write_text(json.dumps(receipt))
+ monkeypatch.setattr(sys, "prefix", str(root))
+ monkeypatch.setattr(sys, "executable", str(executable))
+ monkeypatch.setattr(update_plan.nanobot, "__version__", "0.3.4")
+ monkeypatch.setattr(update_plan.nanobot, "__file__", str(site / "nanobot/__init__.py"))
+ monkeypatch.delenv("RENDER", raising=False)
+ snapshot = inspect_installation()
+ assert snapshot.installed_version == "0.3.5"
+ assert snapshot.running_version == "0.3.4"
+ assert snapshot.owner == ("container" if Path("/.dockerenv").exists() else "pipx")
+ assert snapshot.records["pipx_metadata.json"] == hashlib.sha256((root / "pipx_metadata.json").read_bytes()).hexdigest()
+ if snapshot.owner == "pipx":
+ assert snapshot.manager.extras == ["webui"]
+ before = snapshot.fingerprint
+ receipt["main_package"]["pinned"] = True
+ (root / "pipx_metadata.json").write_text(json.dumps(receipt))
+ assert inspect_installation().fingerprint != before
+
+
[email protected]("manager", ["uv", "pipx"])
+async def test_managed_plan_preserves_extras_and_reports_owner_constraints(tmp_path, manager):
+ policy = ManagerPolicy(manager=manager, backend="uv" if manager == "uv" else "pip",
+ source="registry", extras=["webui"], version_constraint="<0.3.5")
+ snapshot = installation().model_copy(update={"owner": manager, "manager": policy})
+
+ class Feed:
+ async def latest(self, channel):
+ assert channel == "stable"
+ return target()
+
+ saved = await UpdatePlans(tmp_path).prepare(snapshot, "stable", Feed(), now=100)
+ assert saved.extras == ["webui"]
+ assert saved.action == "upgrade"
+ assert "constraints" in saved.owner_restriction
+ assert UpdatePlans(tmp_path).load(saved.id) == saved
+ changed = saved.model_dump()
+ changed["extras"] = []
+ with pytest.raises(ValueError, match="recorded extras"):
+ UpdatePlan.model_validate(changed)
+
+
+def test_cli_plan_is_available_and_never_starts_install(monkeypatch):
+ from nanobot import update, update_plan
+
+ async def preview(channel):
+ assert channel is None # The planner owns the saved installation subscription.
+ return plan()
+
+ monkeypatch.setattr(update_plan, "preview_release_update", preview)
+ monkeypatch.setattr(update, "update_installation", lambda **kwargs: pytest.fail("plan invoked installer"))
+ app = typer.Typer()
+ app.command()(update_command)
+ result = CliRunner().invoke(app, ["--plan"])
+ assert result.exit_code == 0, result.output
+ output = json.loads(result.stdout)
+ assert output["target"]["version"] == "0.3.5"
+ assert output["action"] == "upgrade"
+
+
[email protected]("channel", ["stable", "preview"])
+def test_cli_channel_inspection_cannot_silently_run_stable_update(monkeypatch, channel):
+ from nanobot import update
+
+ monkeypatch.setattr(update, "update_installation", lambda **kwargs: pytest.fail("unexpected installer"))
+ app = typer.Typer()
+ app.command()(update_command)
+ result = CliRunner().invoke(app, ["--channel", channel])
+ assert result.exit_code != 0
+ assert "requires --plan" in Text.from_ansi(result.output).plain
+
+
[email protected]("retry", [False, True])
+def test_saved_job_cli_uses_scoped_status_and_explicit_handoff_only(tmp_path, monkeypatch, retry):
+ from nanobot import update, update_jobs
+ from nanobot.update_jobs import UpdateJobView
+ from nanobot.update_worker import Phase
+
+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path))
+ monkeypatch.setattr(sys, "prefix", str(tmp_path / "environment"))
+ identifier, confirmation = str(uuid4()), uuid4().hex
+ job = UpdateJobView(id=identifier, installation_id="a" * 64, host="test", previous_version="0.3.4",
+ target_version="0.3.5", channel="stable", recorded_phase=Phase.HANDOFF_FAILED,
+ attempt=0, mutation_started=False, updated_at=100, execution_confirmation_id=confirmation)
+ calls = []
+
+ def saved(plan_id):
+ assert plan_id == identifier
+ return job
+
+ def handoff(directory, previous):
+ assert directory.name == identifier and previous == confirmation
+ with pytest.raises(InstallationBusyError):
+ with installation_access(updating=True):
+ pytest.fail("Recovery controller released its runtime too early")
+ calls.append(identifier)
+
+ monkeypatch.setattr(update_jobs, "read_update_job", saved)
+ monkeypatch.setattr(update_jobs, "retry_handoff", handoff)
+ monkeypatch.setattr(update, "update_installation", lambda **kwargs: pytest.fail("Unexpected legacy installer"))
+ app = typer.Typer()
+ app.command()(update_command)
+ arguments = ["--job", identifier]
+ if retry:
+ arguments += ["--retry-handoff", "--previous-confirmation", confirmation, "--confirm-restart"]
+ result = CliRunner().invoke(app, arguments)
+ assert result.exit_code == 0, result.output
+ assert json.loads(result.stdout) == job.model_dump(mode="json")
+ assert calls == ([identifier] if retry else [])
+
+
[email protected]("arguments", [
+ ["--retry-handoff"], ["--job", "id", "--confirm-restart"],
+ ["--job", "id", "--retry-handoff", "--confirm-restart"],
+ ["--job", "id", "--previous-confirmation", "confirmation"],
+ ["--job", "id", "--retry-handoff", "--previous-confirmation", "confirmation"],
+ ["--job", "id", "--check"], ["--job", "id", "--dev"], ["--job", "id", "--plan"],
+ ["--job", "id", "--channel", "preview"], ["--job", "id", "--allow-downgrade"],
+])
+def test_saved_job_cli_rejects_ambiguous_recovery_flags(monkeypatch, arguments):
+ from nanobot.cli import update
+
+ monkeypatch.setattr(update, "_saved_job", lambda *args: pytest.fail("Ambiguous recovery was executed"))
+ app = typer.Typer()
+ app.command()(update_command)
+ assert CliRunner().invoke(app, arguments).exit_code != 0
diff --git a/tests/test_update_profiles.py b/tests/test_update_profiles.py
new file mode 100644
index 000000000..be7afb497
--- /dev/null
+++ b/tests/test_update_profiles.py
@@ -0,0 +1,503 @@
+"""Real gateway runtime identities in isolated profile and installation directories."""
+
+import json
+import os
+import signal
+import socket
+import subprocess
+import sys
+import time
+from contextlib import contextmanager, nullcontext
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import pytest
+
+from nanobot.data_access import data_access
+from nanobot.installation_lock import (
+ InstallationBusyError,
+ installation_access,
+ installation_state_dir,
+ pending_update_path,
+)
+from nanobot.release_feed import ReleaseTarget
+from nanobot.releases import ReleaseArtifact
+from nanobot.update_plan import InstallationSnapshot, UpdatePlans, describe_plan
+from nanobot.update_profiles import (
+ inspect_profiles,
+ require_stopped_profiles,
+ verify_restarted_profile,
+)
+
+_CHILD = """
+import os, sys
+from pathlib import Path
+from nanobot.config.home import set_home_path
+from nanobot.gateway.runtime import GatewayInstance, GatewayRuntime
+from nanobot.installation_lock import installation_access
+from nanobot.update_profiles import record_gateway_profile
+
+profile, environment, marker, workspace = map(Path, sys.argv[1:])
+sys.prefix = str(environment)
+set_home_path(profile)
+instance = GatewayInstance.resolve(config_path=profile / 'config.json')
+runtime = GatewayRuntime(paths=instance.paths)
+with installation_access(), runtime.foreground_instance(instance.start_options(port=18790)):
+ with record_gateway_profile(instance, runtime, data_dir=profile, workspace=workspace, port=18790):
+ marker.write_text(str(os.getpid()))
+ sys.stdin.read(1)
+"""
+
+
+def private_home(tmp_path, monkeypatch):
+ root = tmp_path / "private home"
+ root.mkdir()
+ monkeypatch.setenv("HOME", str(root))
+ monkeypatch.setenv("USERPROFILE", str(root))
+ return root
+
+
+@contextmanager
+def gateway(profile, environment, *, workspace=None):
+ profile.mkdir(parents=True, exist_ok=True)
+ (profile / "config.json").write_text('{"credential":"must-not-be-in-receipt"}')
+ marker = profile / "started"
+ marker.unlink(missing_ok=True)
+ process = subprocess.Popen([sys.executable, "-c", _CHILD, str(profile), str(environment), str(marker),
+ str(workspace or profile / "user project")],
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
+ try:
+ deadline = time.monotonic() + 8
+ while not marker.exists():
+ if process.poll() is not None:
+ pytest.fail(process.stderr.read())
+ assert time.monotonic() < deadline, "Runtime registration did not start"
+ time.sleep(0.02)
+ yield process
+ finally:
+ if process.poll() is None:
+ process.stdin.write("x")
+ process.stdin.flush()
+ process.communicate(timeout=10)
+
+
+def test_inventory_retains_profiles_after_shutdown_and_crash(private_home, tmp_path):
+ environment = tmp_path / "environment"
+ with gateway(tmp_path / "profile one", environment):
+ with gateway(tmp_path / "profile two", environment) as second:
+ observed = inspect_profiles(str(environment))
+ assert len(observed) == 2
+ assert {item.state for item in observed} == {"running"}
+ # Windows venv python.exe is a redirector, not the runtime owner.
+ first_pid = int((tmp_path / "profile one/started").read_text())
+ second_pid = int((tmp_path / "profile two/started").read_text())
+ assert {item.receipt.pid for item in observed} == {first_pid, second_pid}
+ assert {item.receipt.config for item in observed} == {
+ str(tmp_path / "profile one/config.json"), str(tmp_path / "profile two/config.json"),
+ }
+ assert all(item.receipt.launch_mode == "foreground" for item in observed)
+ encoded = "".join(path.read_text() for path in (installation_state_dir(environment) / "profiles").glob("*.json"))
+ assert "must-not-be-in-receipt" not in encoded
+ os.kill(second_pid, signal.SIGTERM if os.name == "nt" else signal.SIGKILL)
+ second.wait(timeout=5)
+ assert sorted(item.state for item in inspect_profiles(str(environment))) == ["running", "stopped"]
+ observed = inspect_profiles(str(environment))
+ assert len(observed) == 2 and all(item.state == "stopped" for item in observed)
+ assert inspect_profiles(str(tmp_path / "another environment")) == []
+ if os.name != "nt":
+ for path in (installation_state_dir(environment) / "profiles").glob("*.json"):
+ assert path.stat().st_mode & 0o777 == 0o600
+
+
+def test_profile_reused_by_another_installation_is_not_reported_idle(private_home, tmp_path):
+ profile, first_env, other_env = (tmp_path / name for name in ("profile", "first", "other"))
+ with gateway(profile, first_env):
+ assert inspect_profiles(str(first_env))[0].state == "running"
+ reviewed = inspect_profiles(str(first_env))
+ with pytest.raises(ValueError, match="still in use"):
+ require_stopped_profiles(reviewed, str(first_env))
+ require_stopped_profiles(reviewed, str(first_env))
+ with gateway(profile, other_env):
+ assert inspect_profiles(str(first_env))[0].state == "unconfirmed"
+ assert inspect_profiles(str(other_env))[0].state == "running"
+ with pytest.raises(ValueError, match="unconfirmed"):
+ require_stopped_profiles(reviewed, str(first_env))
+ assert inspect_profiles(str(first_env))[0].state == "stopped"
+ with gateway(profile, first_env):
+ with pytest.raises(ValueError, match="profiles changed"):
+ require_stopped_profiles(reviewed, str(first_env))
+
+
+def test_missing_process_identity_cannot_become_pid_only_confirmation(private_home, tmp_path):
+ environment = tmp_path / "environment"
+ with gateway(tmp_path / "profile", environment):
+ observed = inspect_profiles(str(environment))[0]
+ path = installation_state_dir(environment) / "profiles" / f"{observed.receipt.id}.json"
+ payload = json.loads(path.read_text())
+ payload["process_identity"] = None
+ path.write_text(json.dumps(payload))
+ assert inspect_profiles(str(environment))[0].state == "unconfirmed"
+ payload["environment"] = str(tmp_path / "foreign environment")
+ path.write_text(json.dumps(payload))
+ with pytest.raises(ValueError, match="different installation"):
+ inspect_profiles(str(environment))
+
+
+def test_older_receipt_keeps_inventory_without_inventing_launch_options(private_home, tmp_path):
+ environment = tmp_path / "environment"
+ with gateway(tmp_path / "profile", environment):
+ observed = inspect_profiles(str(environment))[0]
+ path = installation_state_dir(environment) / "profiles" / f"{observed.receipt.id}.json"
+ payload = json.loads(path.read_text())
+ payload.pop("launch")
+ path.write_text(json.dumps(payload))
+ legacy = inspect_profiles(str(environment))[0]
+ assert legacy.state == "running"
+ assert legacy.receipt.config == observed.receipt.config
+ assert legacy.receipt.launch is None
+
+
+def test_separate_profile_and_environment_cannot_hide_a_shared_workspace_writer(private_home, tmp_path):
+ first, other = tmp_path / "first environment", tmp_path / "other environment"
+ workspace = tmp_path / "shared user project"
+ with gateway(tmp_path / "profile one", first, workspace=workspace):
+ reviewed = inspect_profiles(str(first))
+ with gateway(tmp_path / "profile two", other, workspace=workspace):
+ # The first profile is stopped and unchanged: its own inventory alone
+ # cannot prove that no other installation writes this workspace.
+ require_stopped_profiles(reviewed, str(first))
+ with pytest.raises(InstallationBusyError, match="data is in use"):
+ with data_access([workspace / "sessions"], updating=True):
+ pytest.fail("Another profile's shared workspace writer was ignored")
+ with data_access([workspace / "sessions"], updating=True):
+ pass
+
+
+def startup_profile(private_home, tmp_path, monkeypatch):
+ from nanobot.config.schema import Config
+
+ profile = tmp_path / "startup profile"
+ monkeypatch.setattr("nanobot.config.home._home_path", profile)
+ monkeypatch.setattr("nanobot.config.loader._current_config_path", profile / "config.json")
+ config = Config.model_validate({
+ "agents": {"defaults": {"workspace": str(profile / "workspace"),
+ "dream": {"enabled": False}}},
+ "gateway": {"heartbeat": {"enabled": False}},
+ })
+ return profile, config
+
+
+def test_startup_is_visible_and_protected_before_workspace_writes(startup_profile, monkeypatch):
+ from nanobot.cli import gateway_runtime
+ from nanobot.gateway.runtime import GatewayInstance, GatewayRuntime
+
+ profile, config = startup_profile
+ seen = []
+
+ def fail_initialization(workspace):
+ observed = inspect_profiles(sys.prefix)
+ assert len(observed) == 1 and observed[0].state == "running"
+ assert observed[0].receipt.workspace == str(workspace)
+ assert observed[0].receipt.pid == os.getpid()
+ with pytest.raises(InstallationBusyError, match="installation is in use"):
+ with installation_access(updating=True):
+ pytest.fail("An update entered while gateway initialization was writing")
+ with pytest.raises(InstallationBusyError, match="data is in use"):
+ with data_access([workspace / "sessions"], updating=True):
+ pytest.fail("A different installation could back up live gateway data")
+ seen.append(observed[0].receipt.run_id)
+ raise RuntimeError("workspace initialization failed")
+
+ monkeypatch.setattr(gateway_runtime, "sync_workspace_templates", fail_initialization)
+ # The same public runtime entrypoint can be retried after initialization fails.
+ for _ in range(2):
+ with pytest.raises(RuntimeError, match="workspace initialization failed"):
+ gateway_runtime._run_gateway(config, health_server_enabled=False,
+ webui_static_dist=False)
+ observed = inspect_profiles(sys.prefix)
+ assert len(observed) == 1 and observed[0].state == "stopped"
+ assert not observed[0].receipt.active
+ instance = GatewayInstance.resolve(config_path=profile / "config.json")
+ assert not GatewayRuntime(paths=instance.paths).status().running
+ with installation_access(updating=True):
+ pass
+ assert seen[0] != seen[1]
+
+
+def test_duplicate_gateway_cannot_initialize_workspace_before_claim(startup_profile, monkeypatch):
+ from nanobot.cli import gateway_runtime
+ from nanobot.gateway.runtime import GatewayAlreadyRunningError
+
+ profile, config = startup_profile
+ monkeypatch.setattr(gateway_runtime, "sync_workspace_templates",
+ lambda _path: pytest.fail("Duplicate startup touched the workspace"))
+ with gateway(profile, sys.prefix):
+ original = inspect_profiles(sys.prefix)
+ with pytest.raises(GatewayAlreadyRunningError):
+ gateway_runtime._run_gateway(config, health_server_enabled=False,
+ webui_static_dist=False)
+ assert inspect_profiles(sys.prefix) == original
+
+
[email protected]("interrupted", [False, True])
+def test_gateway_entrypoint_refuses_installation_before_initialization(startup_profile, monkeypatch, interrupted):
+ from nanobot.cli import gateway_runtime
+
+ profile, config = startup_profile
+ monkeypatch.setattr(gateway_runtime, "sync_workspace_templates",
+ lambda _path: pytest.fail("Blocked startup touched the workspace"))
+ if interrupted:
+ pending = pending_update_path()
+ pending.parent.mkdir(parents=True, exist_ok=True)
+ pending.write_text("interrupted")
+ with nullcontext() if interrupted else installation_access(updating=True):
+ with pytest.raises(InstallationBusyError):
+ gateway_runtime._run_gateway(config, health_server_enabled=False,
+ webui_static_dist=False)
+ assert inspect_profiles(sys.prefix) == []
+ assert not (profile / "workspace").exists()
+
+
+def test_gateway_refuses_shared_data_maintenance_before_initializing_writers(startup_profile, monkeypatch):
+ from nanobot.cli import gateway_runtime
+
+ profile, config = startup_profile
+ monkeypatch.setattr(gateway_runtime, "sync_workspace_templates",
+ lambda _path: pytest.fail("Startup wrote to a store under maintenance"))
+ with data_access([config.workspace_path / "sessions"], updating=True):
+ with pytest.raises(InstallationBusyError, match="data is in use"):
+ gateway_runtime._run_gateway(config, health_server_enabled=False, webui_static_dist=False)
+ assert inspect_profiles(sys.prefix) == []
+ assert not (profile / "workspace").exists()
+
+
+def test_classic_cli_holds_data_lease_before_writers_and_through_exit(startup_profile, monkeypatch):
+ from nanobot.cli import agent as cli_agent
+
+ _, config = startup_profile
+ monkeypatch.setattr(cli_agent, "_load_runtime_config", lambda *_args: config)
+ reached = []
+
+ def run_classic(_config, **_kwargs):
+ with pytest.raises(InstallationBusyError):
+ with data_access([config.workspace_path / "sessions"], updating=True):
+ pytest.fail("Classic CLI did not protect its shared data")
+ reached.append(True)
+ raise RuntimeError("simulated classic runtime exit")
+
+ monkeypatch.setattr(cli_agent, "_run_classic", run_classic)
+ with data_access([config.workspace_path / "sessions"], updating=True):
+ with pytest.raises(InstallationBusyError, match="data is in use"):
+ cli_agent.agent(message="hello", classic=True, theme="auto")
+ assert not reached
+ with pytest.raises(RuntimeError, match="simulated classic runtime exit"):
+ cli_agent.agent(message="hello", classic=True, theme="auto")
+ with data_access([config.workspace_path / "sessions"], updating=True):
+ pass
+ assert reached == [True]
+
+
[email protected](os.name == "nt", reason="Graceful SIGTERM proof uses the POSIX gateway handler")
+def test_actual_gateway_startup_records_custom_home_and_graceful_exit(private_home, tmp_path):
+ import http.client
+
+ # Run the actual gateway lifecycle with no providers/channels or browser. Only
+ # tokenizer prefetch is disabled so this test cannot download outside localhost.
+ source = """
+import sys
+from pathlib import Path
+from nanobot.config.home import set_home_path
+from nanobot.config.loader import set_config_path
+from nanobot.config.schema import Config
+from nanobot.installation_lock import installation_access
+from nanobot.cli import gateway_runtime
+from nanobot.agent.loop import AgentLoop
+original_from_config = AgentLoop.from_config
+def create_agent(config, bus, **kwargs):
+ assert kwargs['cron_service'].admission is bus.admission
+ return original_from_config(config, bus, **kwargs)
+AgentLoop.from_config = create_agent
+profile, port = Path(sys.argv[1]), int(sys.argv[2])
+set_home_path(profile)
+set_config_path(profile / 'config data' / 'config.json')
+config = Config.model_validate({'agents': {'defaults': {'workspace': str(profile / 'workspace'),
+ 'dream': {'enabled': False}}}, 'gateway': {'host': '127.0.0.1', 'port': port,
+ 'heartbeat': {'enabled': False}}})
+gateway_runtime.warmup_token_encoding = lambda: None
+with installation_access():
+ gateway_runtime._run_gateway(config, webui_static_dist=False, unconfigured_provider_error='No provider for lifecycle test')
+"""
+ with socket.socket() as listener:
+ listener.bind(("127.0.0.1", 0))
+ port = listener.getsockname()[1]
+ profile = tmp_path / "actual gateway"
+ profile.mkdir()
+ process = subprocess.Popen([sys.executable, "-c", source, str(profile), str(port)],
+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
+ try:
+ deadline = time.monotonic() + 20
+ while True:
+ if process.poll() is not None:
+ pytest.fail(process.stdout.read())
+ connection = http.client.HTTPConnection("127.0.0.1", port, timeout=0.2)
+ try:
+ connection.request("GET", "/health")
+ response = connection.getresponse()
+ if response.status == 200 and json.loads(response.read())["ready"]:
+ break
+ except (OSError, http.client.HTTPException):
+ pass
+ finally:
+ connection.close()
+ assert time.monotonic() < deadline, "Isolated gateway did not become ready"
+ time.sleep(0.05)
+ observed = inspect_profiles(sys.prefix)
+ assert len(observed) == 1 and observed[0].state == "running"
+ assert observed[0].receipt.home == str(profile)
+ assert observed[0].receipt.config == str(profile / "config data/config.json")
+ assert observed[0].receipt.data_dir == str(profile / "config data")
+ assert observed[0].receipt.workspace == str(profile / "workspace")
+ assert observed[0].receipt.pid == process.pid
+ process.send_signal(signal.SIGTERM)
+ output, _ = process.communicate(timeout=15)
+ assert process.returncode == 0, output
+ after = inspect_profiles(sys.prefix)
+ assert after[0].state == "stopped" and not after[0].receipt.active
+ assert after[0].receipt.run_id == observed[0].receipt.run_id
+ finally:
+ if process.poll() is None:
+ process.terminate()
+ process.communicate(timeout=15)
+
+
[email protected](os.name == "nt", reason="Native Windows graceful lifecycle needs its own execution evidence")
[email protected]("selected_home,explicit_workspace", [(False, False), (True, False), (True, True)])
+def test_recorded_launch_restarts_same_actual_gateway(private_home, tmp_path, monkeypatch,
+ selected_home, explicit_workspace):
+ from nanobot.config.home import set_home_path
+ from nanobot.gateway.runtime import GatewayInstance, GatewayRuntime
+
+ profile = tmp_path / "gateway home" if selected_home else private_home / ".nanobot"
+ workspace = tmp_path / "中文 user project"
+ config_path = profile / "config data/config.json" if selected_home else profile / "config.json"
+ working_directory = tmp_path / "original working directory"
+ config_path.parent.mkdir(parents=True)
+ working_directory.mkdir()
+ with socket.socket() as listener:
+ listener.bind(("127.0.0.1", 0))
+ port = listener.getsockname()[1]
+ config_path.write_text(json.dumps({
+ "agents": {"defaults": {"workspace": str(workspace), "dream": {"enabled": False},
+ "provider": "custom", "model": "lifecycle-fixture"}},
+ "providers": {"custom": {"apiKey": "fixture-not-a-secret", "apiBase": "http://127.0.0.1:1/v1"}},
+ "gateway": {"host": "127.0.0.1", "port": port, "heartbeat": {"enabled": False}},
+ "channels": {"websocket": {"enabled": False}},
+ }))
+ monkeypatch.setattr("nanobot.config.home._home_path", None)
+ if selected_home:
+ set_home_path(profile)
+ instance = GatewayInstance.resolve(config_path=config_path,
+ workspace=str(workspace) if explicit_workspace else None)
+ # Use the actual CLI/runtime from this checkout, even when restarting from a
+ # different cwd. Only tokenizer warmup is disabled (no network download).
+ source_root = str(Path(__file__).resolve().parents[1])
+ bootstrap = (
+ f"import sys; sys.path.insert(0, {source_root!r})\n"
+ "from nanobot.cli import gateway_runtime\n"
+ "gateway_runtime.warmup_token_encoding = lambda: None\n"
+ "from nanobot.cli.entry import main\nmain()\n"
+ )
+ processes = []
+ launch_directory = working_directory
+
+ def launch(command, **kwargs):
+ child = subprocess.Popen([command[0], "-c", bootstrap, *command[3:]],
+ cwd=launch_directory, **kwargs)
+ processes.append(child)
+ return child
+
+ runtime = GatewayRuntime(paths=instance.paths, python_executable=sys.executable, popen=launch)
+
+ def ready_profile():
+ deadline = time.monotonic() + 20
+ while True:
+ assert processes[-1].poll() is None, "\n".join(runtime.read_log_tail(tail=20))
+ observed = inspect_profiles(sys.prefix)
+ if runtime.status().ready and observed and observed[0].state == "running":
+ return observed[0].receipt
+ assert time.monotonic() < deadline, "Isolated gateway did not become ready"
+ time.sleep(0.05)
+
+ try:
+ assert runtime.start_background(instance.start_options(port=port, verbose=True)).ok
+ before = ready_profile()
+ assert before.launch is not None
+ assert before.launch.home == (str(profile) if selected_home else None)
+ assert before.launch.config_path == (str(config_path) if selected_home else None)
+ assert before.launch.workspace == (str(workspace) if explicit_workspace else None)
+ assert before.launch.working_directory == str(working_directory)
+ assert before.launch.verbose
+ assert before.launch_mode == "background" and before.launch.lifetime == "explicit"
+ assert "fixture-not-a-secret" not in before.model_dump_json()
+ with pytest.raises(ValueError, match="reviewed instance"):
+ verify_restarted_profile(before, version=before.version)
+ assert runtime.stop(timeout_s=10).ok
+ assert processes[-1].wait(timeout=10) == 0
+ stopped = inspect_profiles(sys.prefix)[0].receipt
+ assert stopped.launch == before.launch and not stopped.active
+
+ # No --workspace must remain no --workspace, even though config resolves
+ # the same final workspace. Guessing that flag changes the instance key.
+ monkeypatch.chdir(tmp_path)
+ launch_directory = Path(before.launch.working_directory)
+ assert runtime.start_background(before.launch.options(port=before.port)).ok
+ after = ready_profile()
+ assert verify_restarted_profile(before, version=after.version) == after
+ assert not runtime.verify_ready(before.health_identity)
+ with pytest.raises(ValueError, match="target version"):
+ verify_restarted_profile(before, version="999.0.0")
+ assert after.run_id != before.run_id and after.pid != before.pid
+ assert after.launch == before.launch
+ for field in ("id", "environment", "python", "package", "version", "home", "data_dir",
+ "config", "workspace", "state_path", "log_path", "port", "launch_mode"):
+ assert getattr(after, field) == getattr(before, field), field
+ assert runtime.stop(timeout_s=10).ok
+ assert processes[-1].wait(timeout=10) == 0
+ assert inspect_profiles(sys.prefix)[0].state == "stopped"
+ with pytest.raises(ValueError, match="not running"):
+ verify_restarted_profile(before, version=after.version)
+ finally:
+ if runtime.status().running:
+ runtime.stop(timeout_s=10)
+ for process in processes:
+ if process.poll() is None:
+ process.terminate()
+ process.wait(timeout=10)
+
+
+async def test_plan_lists_profiles_and_rejects_new_instance_before_confirmation(private_home, tmp_path):
+ environment = tmp_path / "environment"
+ snapshot = InstallationSnapshot(
+ environment=str(environment), python=str(environment / "python"), installed_version="0.3.4",
+ package_path=str(environment / "nanobot/__init__.py"), running_version="0.3.4",
+ running_package=str(environment / "nanobot/__init__.py"), owner="venv", records={},
+ )
+ filename = "nanobot_ai-0.3.5-py3-none-win_amd64.whl"
+ target = ReleaseTarget(version="0.3.5", source="pypi", url=f"https://files.pythonhosted.org/packages/{filename}",
+ artifact=ReleaseArtifact(filename=filename, size=123, sha256="a" * 64))
+ feed = SimpleNamespace(latest=AsyncMock(return_value=target), revalidate=AsyncMock())
+ plans = UpdatePlans(tmp_path / "plans")
+ with gateway(tmp_path / "profile one", environment):
+ plan = await plans.prepare(snapshot, "stable", feed, now=100)
+ assert len(plan.profiles) == 1
+ assert json.loads(describe_plan(plan))["profiles"][0]["state"] == "running"
+ await plans.revalidate(plan.id, snapshot, feed, now=101)
+ feed.revalidate.reset_mock()
+ with gateway(tmp_path / "profile two", environment):
+ with pytest.raises(ValueError, match="Gateway profiles changed"):
+ await plans.revalidate(plan.id, snapshot, feed, now=102)
+ feed.revalidate.assert_not_awaited()
diff --git a/tests/test_update_restart.py b/tests/test_update_restart.py
new file mode 100644
index 000000000..85b3d5fe7
--- /dev/null
+++ b/tests/test_update_restart.py
@@ -0,0 +1,302 @@
+"""Protected post-install startup with the actual gateway, isolated data and ports.
+
+These tests begin at the verified-package handoff, not at a public download or pip
+upgrade. The subprocess bootstrap selects this checkout's code while reusing the
+test interpreter's dependencies; no user installation is replaced or restarted.
+"""
+
+import asyncio
+import hashlib
+import http.client
+import json
+import os
+import socket
+import subprocess
+import sys
+import threading
+import time
+from concurrent.futures import ThreadPoolExecutor
+from dataclasses import asdict
+from pathlib import Path
+from uuid import uuid4
+
+import pytest
+
+import nanobot
+from nanobot.config.home import get_selected_home_path, set_home_path
+from nanobot.data_access import DataStartupGrant, data_access, profile_data_paths
+from nanobot.gateway.runtime import GatewayInstance, GatewayRuntime
+from nanobot.installation_lock import (
+ InstallationBusyError,
+ installation_access,
+ installation_state_dir,
+ pending_update_path,
+)
+from nanobot.release_feed import ReleaseTarget
+from nanobot.releases import ReleaseArtifact
+from nanobot.update_backup import BackupSource, unique_sources
+from nanobot.update_jobs import _worker_archive
+from nanobot.update_plan import InstallationSnapshot, UpdatePlan
+from nanobot.update_profiles import inspect_profiles, verify_restarted_profile
+from nanobot.update_restart import GatewayStartup, run_restarts
+from nanobot.update_worker import (
+ EnvironmentSnapshot,
+ JobStatus,
+ Phase,
+ StagedWheel,
+ WorkerSpec,
+ write_record,
+)
+
+
+def _port():
+ with socket.socket() as listener:
+ listener.bind(("127.0.0.1", 0))
+ return listener.getsockname()[1]
+
+
+def _http(port, path, *, method="GET"):
+ connection = http.client.HTTPConnection("127.0.0.1", port, timeout=0.4)
+ try:
+ connection.request(method, path)
+ response = connection.getresponse()
+ return response.status, response.read()
+ finally:
+ connection.close()
+
+
+def _wait(predicate, message, *, timeout=20):
+ deadline = time.monotonic() + timeout
+ while time.monotonic() < deadline:
+ try:
+ if result := predicate():
+ return result
+ except (OSError, http.client.HTTPException):
+ pass
+ time.sleep(0.05)
+ pytest.fail(message)
+
+
+def private_home(tmp_path, monkeypatch):
+ root = tmp_path / "private account"
+ root.mkdir()
+ monkeypatch.setenv("HOME", str(root))
+ monkeypatch.setenv("USERPROFILE", str(root))
+ return root
+
+
+def _job(previous, *, legacy_scope=False):
+ """Materialize the immutable record supplied by verified package installation."""
+ identifier = str(uuid4())
+ directory = installation_state_dir() / "jobs" / identifier
+ directory.mkdir(parents=True)
+ version = nanobot.__version__
+ filename = f"nanobot_ai-{version}-py3-none-win_amd64.whl"
+ snapshot = InstallationSnapshot(
+ environment=str(Path(sys.prefix).resolve()), python=sys.executable,
+ installed_version=version, running_version=version, package_path=nanobot.__file__,
+ running_package=nanobot.__file__, owner="venv", records={},
+ )
+ profiles = inspect_profiles(sys.prefix)
+ plan = UpdatePlan(
+ id=identifier, installation=snapshot, channel="stable", profiles=profiles,
+ restart_profiles=[previous.id], extras=[], created_at=int(time.time()), expires_at=int(time.time()) + 900,
+ target=ReleaseTarget(version=version, source="pypi", url=f"https://files.pythonhosted.org/packages/{filename}",
+ artifact=ReleaseArtifact(filename=filename, size=1, sha256="0" * 64)),
+ )
+ write_record(directory / "plan.json", plan.model_dump(mode="json"))
+ paths = profile_data_paths(
+ home=Path(previous.home), data_dir=Path(previous.data_dir),
+ config=Path(previous.config), workspace=Path(previous.workspace))
+ if legacy_scope:
+ paths = tuple(path for path in paths if path != Path(previous.data_dir) / "delivery")
+ sources = unique_sources([BackupSource(str(path)) for path in paths])
+ spec = WorkerSpec(
+ identifier, hashlib.sha256((directory / "plan.json").read_bytes()).hexdigest(),
+ _worker_archive(directory / "worker.pyz"),
+ EnvironmentSnapshot(snapshot.environment, sys.executable, sys.executable,
+ "0" * 64, {}, {}, version, {}), version,
+ (StagedWheel(filename, "nanobot-ai", version, 1, "0" * 64),), sources, (previous.id,),
+ )
+ spec.save(directory)
+ JobStatus(identifier, Phase.RESTARTING, 1, True, "Fixture: package verification completed", int(time.time())).save(directory)
+ with data_access((item.path for item in sources), updating=True, job_id=identifier) as data:
+ data.reserve()
+ pending_update_path().parent.mkdir(parents=True, exist_ok=True)
+ write_record(pending_update_path(), {"schema_version": 2, "job_id": identifier, "version": version})
+ return directory, spec
+
+
[email protected](os.name == "nt", reason="Native Windows lifecycle execution requires a Windows runner")
[email protected]("legacy_scope", [False, True])
+def test_actual_gateway_is_parked_until_exact_runtime_activation(private_home, tmp_path, monkeypatch, legacy_scope):
+ from nanobot import update_restart
+
+ profile = tmp_path / "gateway home"
+ workspace = tmp_path / "中文 workspace"
+ cwd = tmp_path / "original working directory"
+ profile.mkdir()
+ cwd.mkdir()
+ health_port, web_port = _port(), _port()
+ config_path = profile / "config.json"
+ config_path.write_text(json.dumps({
+ "agents": {"defaults": {"workspace": str(workspace), "dream": {"enabled": False},
+ "provider": "custom", "model": "lifecycle-test"}},
+ "providers": {"custom": {"apiKey": "fixture-not-a-secret", "apiBase": "http://127.0.0.1:1/v1"}},
+ "gateway": {"host": "127.0.0.1", "port": health_port, "heartbeat": {"enabled": False}},
+ "channels": {"websocket": {"enabled": True, "host": "127.0.0.1", "port": web_port}},
+ }))
+ source = Path(__file__).resolve().parents[1]
+ marker = tmp_path / "mcp-started"
+ bootstrap = (
+ f"import sys, runpy; sys.path.insert(0, {str(source)!r})\n"
+ "from pathlib import Path\nimport os\n"
+ "from nanobot.cli import gateway_runtime\n"
+ "from nanobot.agent.tools.mcp import MCPProvider\n"
+ "gateway_runtime.warmup_token_encoding = lambda: None\n"
+ "async def observe_connect(self):\n"
+ " assert 'NANOBOT_UPDATE_STARTUP_TOKEN' not in os.environ\n"
+ f" Path({str(marker)!r}).touch()\n"
+ "MCPProvider.connect = observe_connect\n"
+ )
+ original_popen = subprocess.Popen
+ children = []
+
+ def spawn(command, **kwargs):
+ if "--gateway" in command:
+ # Run the same frozen entrypoint with checkout imports selected by
+ # this test, only after protected site initialization. Keep the
+ # production -I -S flags; no application import may bypass them.
+ script = (
+ "import sys, runpy\nsys.argv = sys.argv[1:]\nsys.path.insert(0, sys.argv[0])\n"
+ "from _nanobot_update import update_worker\n"
+ "initialize = update_worker.initialize_runtime\n"
+ "def initialize_fixture(python, environment):\n"
+ " initialize(python, environment)\n"
+ f" exec({bootstrap!r}, {{}})\n"
+ "update_worker.initialize_runtime = initialize_fixture\n"
+ "runpy.run_path(sys.argv[0], run_name='__main__')\n"
+ )
+ assert command[1:3] == ["-I", "-S"]
+ command = [command[0], "-I", "-S", "-c", script, *command[3:]]
+ elif command[1:3] == ["-m", "nanobot"]:
+ script = bootstrap + "from nanobot.cli.entry import main\nmain()\n"
+ command = [command[0], "-c", script, *command[3:]]
+ kwargs["cwd"] = cwd
+ else:
+ return original_popen(command, **kwargs)
+ child = original_popen(command, **kwargs)
+ children.append(child)
+ return child
+
+ selected_home = get_selected_home_path()
+ set_home_path(profile)
+ instance = GatewayInstance.resolve(config_path=config_path)
+ runtime = GatewayRuntime(paths=instance.paths, python_executable=sys.executable, popen=spawn)
+ release = threading.Event()
+ parked = threading.Event()
+ executor = ThreadPoolExecutor(max_workers=1)
+ future = None
+ try:
+ assert runtime.start_background(instance.start_options(port=health_port)).ok
+ _wait(lambda: runtime.status().ready, "Original isolated gateway did not become ready")
+ previous = inspect_profiles(sys.prefix)[0].receipt
+ assert previous.launch.working_directory == str(cwd)
+ assert runtime.stop(timeout_s=10).ok
+ assert children[-1].wait(timeout=10) == 0
+ marker.unlink()
+ directory, spec = _job(previous, legacy_scope=legacy_scope)
+ original_wait = update_restart._wait_verified
+
+ def wait_verified(*args, **kwargs):
+ result = original_wait(*args, **kwargs)
+ if kwargs["maintenance"] is True:
+ parked.set()
+ assert release.wait(15), "Test did not release the inspected parked runtime"
+ return result
+
+ monkeypatch.setattr(update_restart, "_wait_verified", wait_verified)
+ monkeypatch.setattr(update_restart.subprocess, "Popen", spawn)
+
+ def coordinate():
+ with installation_access(allow_incomplete=True):
+ run_restarts(directory)
+
+ future = executor.submit(coordinate)
+ _wait(lambda: parked.is_set() or future.done(), "Restart did not reach protected readiness")
+ if future.done():
+ future.result()
+ assert parked.is_set(), "Coordinator skipped protected readiness"
+ status, body = _http(health_port, "/health")
+ assert status == 200 and json.loads(body)["maintenance"] is True
+ assert not marker.exists(), "MCP started before gateway activation"
+ assert not (Path(previous.data_dir) / "delivery/outbox.sqlite3").exists()
+ assert _http(web_port, "/webui/bootstrap")[0] == 503
+ assert _http(web_port, "/api/uploads", method="POST")[0] == 503
+ assert JobStatus.read(directory).phase == Phase.RESTARTING
+ with pytest.raises(InstallationBusyError):
+ with installation_access():
+ pytest.fail("Ordinary installation startup bypassed the pending handoff")
+ with pytest.raises(InstallationBusyError):
+ with data_access([workspace / "sessions"]):
+ pytest.fail("Ordinary data access bypassed the pending handoff")
+ release.set()
+ future.result(timeout=25)
+ assert JobStatus.read(directory).phase == Phase.SUCCEEDED
+ assert not pending_update_path().exists()
+ current = verify_restarted_profile(previous, version=spec.version, job_id=spec.plan_id, maintenance=False)
+ assert current.run_id != previous.run_id
+ _wait(marker.exists, "MCP did not start after activation")
+ assert _http(web_port, "/webui/bootstrap")[0] == 200
+ with installation_access(), data_access([workspace / "sessions"]):
+ pass
+ # Recover the real crash window after data cleanup but before unlinking
+ # the installation fence. Do not start another process or reinstall.
+ JobStatus(spec.plan_id, Phase.FINALIZING, 1, True, "Verified; cleanup interrupted", int(time.time())).save(directory)
+ write_record(pending_update_path(), {"schema_version": 2, "job_id": spec.plan_id, "version": spec.version})
+ run_restarts(directory)
+ assert JobStatus.read(directory).phase == Phase.SUCCEEDED
+ assert not pending_update_path().exists()
+ assert runtime.stop(timeout_s=10).ok
+ assert children[-1].wait(timeout=10) == 0
+ run_restarts(directory)
+ assert len(children) == 2, "Completed job restarted a gateway the user had stopped"
+ finally:
+ release.set()
+ if future is not None:
+ try:
+ future.result(timeout=130)
+ except Exception:
+ pass
+ executor.shutdown(wait=True)
+ if runtime.status().running:
+ runtime.stop(timeout_s=10)
+ for child in children:
+ if child.poll() is None:
+ child.terminate()
+ child.wait(timeout=10)
+ set_home_path(selected_home)
+
+
+async def test_activation_is_bound_to_new_run_not_just_profile(tmp_path):
+ from types import SimpleNamespace
+
+ identifier, participant = str(uuid4()), "a" * 64
+ directory = tmp_path / identifier
+ directory.mkdir()
+ startup = GatewayStartup(directory, SimpleNamespace(id=participant), DataStartupGrant(identifier, participant, "b" * 64))
+ from nanobot.gateway.runtime import GatewayHealthIdentity
+
+ identity = GatewayHealthIdentity(participant, "c" * 32, "0.3.5")
+ JobStatus(identifier, Phase.ACTIVATING, 1, True, "test activation", int(time.time())).save(directory)
+ write_record(directory / "activation.json", {"plan_id": identifier, participant: {**asdict(identity), "run_id": "d" * 32}})
+ waiting = asyncio.create_task(startup.wait_for_activation(identity))
+ try:
+ await asyncio.sleep(0.15)
+ assert not waiting.done()
+ write_record(directory / "activation.json", {"plan_id": identifier, participant: asdict(identity)})
+ await asyncio.wait_for(waiting, timeout=1)
+ finally:
+ waiting.cancel()
+ await asyncio.gather(waiting, return_exceptions=True)
diff --git a/tests/test_update_stop.py b/tests/test_update_stop.py
new file mode 100644
index 000000000..c3b5b8b5c
--- /dev/null
+++ b/tests/test_update_stop.py
@@ -0,0 +1,614 @@
+"""Cooperative shutdown protocol tests; no installer or real account is touched."""
+
+import asyncio
+import hashlib
+import json
+import os
+import socket
+import subprocess
+import sys
+import time
+from contextlib import ExitStack
+from pathlib import Path
+from types import SimpleNamespace
+from uuid import uuid4
+from zipfile import ZipFile
+
+import pytest
+
+import nanobot
+from nanobot.config.home import get_selected_home_path, set_home_path
+from nanobot.data_access import data_access, profile_data_paths
+from nanobot.gateway.runtime import GatewayInstance, GatewayRuntime
+from nanobot.installation_lock import file_access, installation_access, installation_state_dir
+from nanobot.release_feed import ReleaseTarget
+from nanobot.releases import ReleaseArtifact
+from nanobot.runtime_admission import RuntimeAdmission
+from nanobot.update_backup import BackupSource
+from nanobot.update_jobs import _worker_archive
+from nanobot.update_plan import InstallationSnapshot, UpdatePlan
+from nanobot.update_profiles import ObservedProfile, ProfileLaunch, ProfileReceipt, inspect_profiles
+from nanobot.update_stop import (
+ settle_uncommitted_handoff,
+ stop_reviewed_gateways,
+ watch_gateway_stop,
+)
+from nanobot.update_worker import (
+ EnvironmentSnapshot,
+ JobStatus,
+ Phase,
+ StagedWheel,
+ WorkerSpec,
+ read_record,
+ write_record,
+)
+
+
+def prepared_job(profiles, *, stop=None):
+ """Synthetic wheel metadata: not an actual nanobot installation fixture."""
+ identifier = str(uuid4())
+ directory = installation_state_dir() / "jobs" / identifier
+ directory.mkdir(parents=True)
+ snapshot = InstallationSnapshot(
+ environment=str(Path(sys.prefix).resolve()), python=sys.executable,
+ installed_version=nanobot.__version__, running_version=nanobot.__version__,
+ package_path=nanobot.__file__, running_package=nanobot.__file__, owner="venv", records={},
+ )
+ version = "99.0.0"
+ filename = f"nanobot_ai-{version}-py3-none-win_amd64.whl"
+ wheels = directory / "wheels"
+ wheels.mkdir()
+ wheel = wheels / filename
+ with ZipFile(wheel, "w") as archive:
+ archive.writestr(f"nanobot_ai-{version}.dist-info/METADATA",
+ f"Metadata-Version: 2.1\nName: nanobot-ai\nVersion: {version}\n")
+ size, checksum = wheel.stat().st_size, hashlib.sha256(wheel.read_bytes()).hexdigest()
+ plan = UpdatePlan(
+ id=identifier, installation=snapshot, channel="stable", profiles=profiles,
+ stop_profiles=[item.receipt.id for item in profiles] if stop is None else stop,
+ extras=[], created_at=int(time.time()), expires_at=int(time.time()) + 900,
+ target=ReleaseTarget(version=version, source="pypi", url=f"https://files.pythonhosted.org/packages/{filename}",
+ artifact=ReleaseArtifact(filename=filename, size=size, sha256=checksum)),
+ )
+ write_record(directory / "plan.json", plan.model_dump(mode="json"))
+ spec = WorkerSpec(
+ identifier, hashlib.sha256((directory / "plan.json").read_bytes()).hexdigest(),
+ _worker_archive(directory / "worker.pyz"),
+ EnvironmentSnapshot(snapshot.environment, sys.executable, sys.executable,
+ "0" * 64, {}, {}, nanobot.__version__, {}), version,
+ (StagedWheel(filename, "nanobot-ai", version, size, checksum),),
+ (BackupSource(str(directory / "fixture-data")),),
+ )
+ spec.save(directory)
+ JobStatus(identifier, Phase.READY, 0, False, "Fixture: staged, not installed", int(time.time())).save(directory)
+ return directory, plan
+
+
+def private_home(tmp_path, monkeypatch):
+ root = tmp_path / "private account"
+ root.mkdir()
+ monkeypatch.setenv("HOME", str(root))
+ monkeypatch.setenv("USERPROFILE", str(root))
+ return root
+
+
+def protocol(private_home, monkeypatch):
+ from nanobot import update_stop
+
+ profiles = []
+ for number in range(2):
+ root = private_home / f"gateway-{number}"
+ receipt = ProfileReceipt(
+ id=hashlib.sha256(str(root).encode()).hexdigest(), run_id=uuid4().hex,
+ environment=str(Path(sys.prefix).resolve()), python=sys.executable,
+ package=nanobot.__file__, version=nanobot.__version__, home=str(root), data_dir=str(root),
+ config=str(root / "config.json"), workspace=str(root / "workspace"),
+ state_path=str(root / "runtime.json"), log_path=str(root / "runtime.log"), port=18790 + number,
+ launch_mode="background", pid=os.getpid() + 10000 + number, process_identity=f"fixture-{number}",
+ active=True, stop_protocol=1,
+ launch=ProfileLaunch(home=str(root), config_path=None, workspace=None,
+ working_directory=str(root), verbose=False, lifetime="explicit"),
+ )
+ profiles.append(ObservedProfile(receipt=receipt, state="running"))
+ directory, plan = prepared_job(profiles)
+ gates = [RuntimeAdmission(), RuntimeAdmission()]
+ stops = [asyncio.Event(), asyncio.Event()]
+ # This test exercises mailbox/admission races with controlled process state;
+ # a separate subprocess test checks actual gateway exit and lease release.
+ monkeypatch.setattr(update_stop, "validate_profiles", lambda expected, environment: None)
+
+ def stopped(expected, environment):
+ if not all(event.is_set() for event in stops):
+ raise ValueError("still running")
+
+ monkeypatch.setattr(update_stop, "require_stopped_profiles", stopped)
+ monkeypatch.setattr(update_stop.GatewayRuntime, "process_is_running", lambda self, pid: False)
+ return directory, plan, gates, stops
+
+
+async def wait_until(predicate, *, timeout=5):
+ async with asyncio.timeout(timeout):
+ while not predicate():
+ await asyncio.sleep(0.01)
+
+
[email protected]("failure", [ValueError("Invalid release approval"), TimeoutError("Trust service unavailable")])
+async def test_handoff_rejects_approval_before_requesting_gateway_shutdown(protocol, monkeypatch, failure):
+ from unittest.mock import AsyncMock
+
+ from nanobot import update_handoff
+
+ directory, _, _, stops = protocol
+ state = JobStatus.read(directory)
+ state.advance(directory, Phase.CHECKING, "Checking approval", mutation_started=False)
+ # Environment inspection is covered by the real installed-process tests;
+ # exercise the actual handoff ordering and durable status here.
+ monkeypatch.setattr(update_handoff, "current_environment", lambda **_: None)
+ monkeypatch.setattr(update_handoff, "check_environment", lambda *_, **__: None)
+ monkeypatch.setattr(update_handoff.ReleaseFeed, "revalidate", AsyncMock(side_effect=failure))
+ stop = AsyncMock()
+ monkeypatch.setattr(update_handoff, "stop_reviewed_gateways", stop)
+ with pytest.raises(type(failure), match=str(failure)):
+ await update_handoff._prepare(directory)
+ stop.assert_not_called()
+ assert not any(event.is_set() for event in stops)
+ state = JobStatus.read(directory)
+ assert state.phase == Phase.HANDOFF_FAILED and not state.mutation_started
+ assert "shutdown was not requested" in state.message
+ assert not (directory / "handoff-approval.json").exists()
+
+
+async def test_handoff_rejects_observed_catalogue_rollback_before_gateway_shutdown(protocol, monkeypatch):
+ from dataclasses import replace
+ from unittest.mock import AsyncMock
+
+ import httpx
+ from packaging.tags import Tag
+
+ from nanobot import update_handoff
+ from nanobot.release_feed import CATALOGUE_URL, ReleaseFeed, ReleaseFeedError
+ from nanobot.releases import (
+ ReleaseCatalogue,
+ ReleaseManifest,
+ ReleasePointer,
+ release_filenames,
+ )
+
+ directory, plan, _, _ = protocol
+ artifact = plan.target.artifact
+ manifest = ReleaseManifest(
+ version=plan.target.version, source_commit="a" * 40, candidate_commit="b" * 40,
+ requires_python=">=3.11", artifacts=[
+ artifact if name == artifact.filename else ReleaseArtifact(filename=name, size=1, sha256="c" * 64)
+ for name in sorted(release_filenames(plan.target.version))
+ ],
+ )
+ payload = manifest.model_dump_json().encode()
+ pointer = ReleasePointer(version=manifest.version, candidate_commit=manifest.candidate_commit,
+ manifest_sha256=hashlib.sha256(payload).hexdigest())
+ original = ReleaseCatalogue(generation=1, stable=pointer)
+ observed = original.model_copy(update={"generation": 2, "withdrawn": {manifest.version: "Startup regression"}})
+ selected = original
+
+ def respond(request):
+ if str(request.url) == CATALOGUE_URL:
+ return httpx.Response(200, content=selected.model_dump_json())
+ if str(request.url) == pointer.manifest_url:
+ return httpx.Response(200, content=payload)
+ assert request.url.path == f"/pypi/nanobot-ai/{manifest.version}/json"
+ return httpx.Response(200, json={
+ "info": {"name": "nanobot-ai", "version": manifest.version, "requires_python": ">=3.11"},
+ "urls": [{"filename": item.filename, "size": item.size, "yanked": False,
+ "url": f"https://files.pythonhosted.org/packages/{item.filename}",
+ "digests": {"sha256": item.sha256}}
+ for item in manifest.artifacts if item.filename.endswith((".whl", ".tar.gz"))],
+ })
+
+ class CachedFeed(ReleaseFeed):
+ def __init__(self, cache_dir):
+ super().__init__(cache_dir, transport=httpx.MockTransport(respond),
+ supported_tags=[Tag("py3", "none", "win_amd64")])
+
+ # Publication authority is independent of catalogue freshness. These fixture
+ # bytes stand for a previously approved release that has since been withdrawn.
+ monkeypatch.setattr(ReleaseFeed, "_authorize", AsyncMock())
+ root = installation_state_dir(plan.installation.environment)
+ spec = WorkerSpec.read(directory)
+ async with CachedFeed(root / "releases") as feed:
+ target = await feed.latest("preview")
+ plan = plan.model_copy(update={"channel": "preview", "target": target})
+ write_record(directory / "plan.json", plan.model_dump(mode="json"))
+ selected = observed
+ assert await feed.catalogue() == observed
+ replace(spec, plan_sha256=hashlib.sha256((directory / "plan.json").read_bytes()).hexdigest()).save(directory)
+ JobStatus.read(directory).advance(directory, Phase.CHECKING, "Checking the exact release", mutation_started=False)
+ monkeypatch.setattr(update_handoff, "current_environment", lambda **_: spec.baseline)
+ monkeypatch.setattr(update_handoff, "ReleaseFeed", CachedFeed)
+ stop = AsyncMock()
+ monkeypatch.setattr(update_handoff, "stop_reviewed_gateways", stop)
+ selected = original
+ with pytest.raises(ReleaseFeedError, match="generation"):
+ await update_handoff._prepare(directory)
+ stop.assert_not_called()
+ state = JobStatus.read(directory)
+ assert state.phase == Phase.HANDOFF_FAILED and not state.mutation_started
+ assert "shutdown was not requested" in state.message
+
+
[email protected]("phase", [Phase.READY, Phase.HANDOFF_FAILED])
+def test_expired_uncommitted_handoff_can_be_settled_while_gateway_remains_running(protocol, monkeypatch, phase):
+ directory, plan, _, stops = protocol
+ monkeypatch.setattr(time, "time", lambda: plan.expires_at + 1)
+ JobStatus(plan.id, phase, 0, False, "No installation", plan.created_at).save(directory)
+ original = {path.name: path.read_bytes() for path in directory.iterdir() if path.is_file() and path.name != "status.json"}
+ with installation_access():
+ result = settle_uncommitted_handoff(directory)
+ assert result.phase == Phase.CANCELLED and not result.mutation_started
+ assert settle_uncommitted_handoff(directory) == result
+ assert not any(event.is_set() for event in stops)
+ assert original == {path.name: path.read_bytes() for path in directory.iterdir() if path.is_file() and path.name != "status.json"}
+
+
[email protected]("lock", ["worker.lock", "handoff-child.lock", "stop.lock"])
+def test_settlement_refuses_live_handoff_owners_without_changing_saved_state(protocol, lock):
+ directory, plan, _, _ = protocol
+ before = (directory / "status.json").read_bytes()
+ with file_access(installation_state_dir(plan.installation.environment) / lock, exclusive=True):
+ with pytest.raises(BlockingIOError):
+ settle_uncommitted_handoff(directory)
+ assert (directory / "status.json").read_bytes() == before
+
+
[email protected]("boundary", ["commit", "stopped", "approval", "mutation"])
+def test_settlement_never_undoes_shutdown_or_installation_authority(protocol, boundary):
+ directory, plan, _, _ = protocol
+ JobStatus(plan.id, Phase.HANDOFF_FAILED, 0, boundary == "mutation", "Saved failure", plan.created_at).save(directory)
+ if boundary in {"commit", "stopped"}:
+ write_record(installation_state_dir() / "stop.json", {
+ "plan_id": plan.id, "attempt": uuid4().hex, "phase": boundary, "deadline": time.monotonic() + 10,
+ })
+ elif boundary == "approval":
+ write_record(directory / "approval.json", {"plan_id": plan.id})
+ before = (directory / "status.json").read_bytes()
+ with pytest.raises(ValueError):
+ settle_uncommitted_handoff(directory)
+ assert (directory / "status.json").read_bytes() == before
+
+
+async def test_all_selected_runs_hold_admission_through_committed_shutdown(protocol):
+ directory, plan, gates, stops = protocol
+ outer = [ExitStack(), ExitStack()]
+ watchers = [asyncio.create_task(watch_gateway_stop(item.receipt, lambda gate=gate: gate.pause_if_idle(lambda: False),
+ stop, stack))
+ for item, gate, stop, stack in zip(plan.profiles, gates, stops, outer)]
+ try:
+ await stop_reviewed_gateways(directory)
+ assert all(stop.is_set() for stop in stops)
+ for watcher in watchers:
+ watcher.cancel()
+ await asyncio.gather(*watchers, return_exceptions=True)
+ assert all(gate.paused for gate in gates), "Watcher cancellation reopened committed intake"
+ assert read_record(installation_state_dir() / "stop.json")["phase"] == "stopped"
+ assert JobStatus.read(directory).phase == Phase.READY
+ assert not (directory / "approval.json").exists()
+ # Retrying completed handoff is a read/exit check, not a fresh stop.
+ await stop_reviewed_gateways(directory)
+ finally:
+ for watcher in watchers:
+ watcher.cancel()
+ await asyncio.gather(*watchers, return_exceptions=True)
+ for stack in outer:
+ stack.close()
+ assert not any(gate.paused for gate in gates)
+
+
[email protected]("reason", ["busy", "cancel", "timeout"])
+async def test_precommit_failure_releases_every_hold_without_shutdown(protocol, reason, expire_stop_deadline):
+ directory, plan, gates, stops = protocol
+ outer = [ExitStack(), ExitStack()]
+ holds = ExitStack()
+ if reason == "busy":
+ holds.enter_context(gates[1].activity())
+ watchers = [asyncio.create_task(watch_gateway_stop(plan.profiles[0].receipt,
+ lambda: gates[0].pause_if_idle(lambda: False), stops[0], outer[0]))]
+ if reason == "busy":
+ watchers.append(asyncio.create_task(watch_gateway_stop(plan.profiles[1].receipt,
+ lambda: gates[1].pause_if_idle(lambda: False), stops[1], outer[1])))
+ operation = asyncio.create_task(stop_reviewed_gateways(directory))
+ try:
+ if reason == "cancel":
+ await wait_until(lambda: gates[0].paused)
+ operation.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await operation
+ else:
+ if reason == "timeout":
+ # Expire only after a participant actually holds admission, so
+ # this proves release rather than racing slow filesystem I/O.
+ await wait_until(lambda: gates[0].paused)
+ expire_stop_deadline()
+ with pytest.raises(ValueError if reason == "busy" else TimeoutError,
+ match="busy or refused" if reason == "busy" else "did not prepare"):
+ await asyncio.wait_for(operation, timeout=30)
+ await wait_until(lambda: not any(gate.paused for gate in gates))
+ assert not any(stop.is_set() for stop in stops)
+ assert read_record(installation_state_dir() / "stop.json")["phase"] == "abort"
+ with gates[0].activity():
+ pass
+ holds.close()
+ if reason != "busy":
+ watchers.append(asyncio.create_task(watch_gateway_stop(plan.profiles[1].receipt,
+ lambda: gates[1].pause_if_idle(lambda: False), stops[1], outer[1])))
+ await asyncio.wait_for(stop_reviewed_gateways(directory), timeout=30)
+ assert all(stop.is_set() for stop in stops), "A refused attempt prevented a later explicit retry"
+ finally:
+ operation.cancel()
+ await asyncio.gather(operation, return_exceptions=True)
+ for watcher in watchers:
+ watcher.cancel()
+ await asyncio.gather(*watchers, return_exceptions=True)
+ for stack in outer:
+ stack.close()
+ holds.close()
+
+
+async def test_abandoned_prepare_releases_intake_when_coordinator_lease_disappears(protocol):
+ directory, plan, gates, stops = protocol
+ gate = ExitStack()
+ watcher = asyncio.create_task(watch_gateway_stop(plan.profiles[0].receipt,
+ lambda: gates[0].pause_if_idle(lambda: False), stops[0], gate))
+ try:
+ with file_access(installation_state_dir() / "stop.lock", exclusive=True):
+ write_record(installation_state_dir() / "stop.json", {
+ "plan_id": plan.id, "attempt": uuid4().hex, "phase": "prepare",
+ "deadline": time.monotonic() + 30,
+ })
+ await wait_until(lambda: gates[0].paused)
+ await wait_until(lambda: not gates[0].paused)
+ assert not stops[0].is_set()
+ finally:
+ watcher.cancel()
+ await asyncio.gather(watcher, return_exceptions=True)
+ gate.close()
+
+
+async def test_changed_run_cannot_accept_old_stop_selection(protocol):
+ directory, plan, gates, stops = protocol
+ different = plan.profiles[0].receipt.model_copy(update={"run_id": uuid4().hex})
+ outer = ExitStack()
+ watcher = asyncio.create_task(watch_gateway_stop(different, lambda: gates[0].pause_if_idle(lambda: False),
+ stops[0], outer))
+ try:
+ with pytest.raises(ValueError, match="run changed"):
+ await stop_reviewed_gateways(directory)
+ assert not stops[0].is_set() and not gates[0].paused
+ finally:
+ watcher.cancel()
+ await asyncio.gather(watcher, return_exceptions=True)
+ outer.close()
+
+
+async def test_unselected_running_gateway_refuses_before_sending_requests(protocol):
+ _, plan, _, stops = protocol
+ directory, _ = prepared_job(plan.profiles, stop=[plan.profiles[0].receipt.id])
+ with pytest.raises(ValueError, match="Every running gateway"):
+ await stop_reviewed_gateways(directory)
+ assert not (installation_state_dir() / "stop.json").exists()
+ assert not any(stop.is_set() for stop in stops)
+
+
+async def test_changed_staging_refuses_before_closing_task_intake(protocol):
+ directory, plan, gates, stops = protocol
+ (directory / "wheels" / plan.target.artifact.filename).write_bytes(b"interrupted download")
+ with pytest.raises(ValueError, match="Staged wheel"):
+ await stop_reviewed_gateways(directory)
+ assert not (installation_state_dir() / "stop.json").exists()
+ assert not any(gate.paused for gate in gates)
+ assert not any(stop.is_set() for stop in stops)
+
+
+async def test_written_commit_is_not_aborted_if_acknowledging_the_write_fails(protocol, monkeypatch):
+ from nanobot import update_stop
+
+ directory, plan, gates, stops = protocol
+ outer = [ExitStack(), ExitStack()]
+ watchers = [asyncio.create_task(watch_gateway_stop(item.receipt, lambda gate=gate: gate.pause_if_idle(lambda: False),
+ stop, stack))
+ for item, gate, stop, stack in zip(plan.profiles, gates, stops, outer)]
+ actual_write = update_stop.write_record
+
+ def fail_after_commit(path, data, **kwargs):
+ actual_write(path, data, **kwargs)
+ if path.name == "stop.json" and data.get("phase") == "commit":
+ raise OSError("Commit renamed before directory fsync failed")
+
+ monkeypatch.setattr(update_stop, "write_record", fail_after_commit)
+ try:
+ with pytest.raises(OSError, match="fsync"):
+ await stop_reviewed_gateways(directory)
+ await wait_until(lambda: all(stop.is_set() for stop in stops))
+ assert read_record(installation_state_dir() / "stop.json")["phase"] == "commit"
+ assert all(gate.paused for gate in gates)
+ await stop_reviewed_gateways(directory)
+ assert read_record(installation_state_dir() / "stop.json")["phase"] == "stopped"
+ assert not (directory / "approval.json").exists()
+ finally:
+ for watcher in watchers:
+ watcher.cancel()
+ await asyncio.gather(*watchers, return_exceptions=True)
+ for stack in outer:
+ stack.close()
+
+
+def expire_stop_deadline(monkeypatch):
+ from nanobot import update_stop
+
+ # Drive protocol deadlines from an observed state, not filesystem speed.
+ # Tests retain real-time watchdogs to catch stalled coordination.
+ now = 100.0
+ monkeypatch.setattr(update_stop, "time", SimpleNamespace(monotonic=lambda: now))
+
+ def expire():
+ nonlocal now
+ now += 31 # The production stop deadline is 30 seconds.
+
+ return expire
+
+
+async def test_stop_acknowledgement_does_not_prove_process_exit(protocol, monkeypatch, expire_stop_deadline):
+ from nanobot import update_stop
+
+ directory, plan, gates, stops = protocol
+ outer = [ExitStack(), ExitStack()]
+ watchers = [asyncio.create_task(watch_gateway_stop(item.receipt, lambda gate=gate: gate.pause_if_idle(lambda: False),
+ stop, stack))
+ for item, gate, stop, stack in zip(plan.profiles, gates, stops, outer)]
+ def still_running(_runtime, _pid):
+ expire_stop_deadline()
+ return True
+
+ monkeypatch.setattr(update_stop.GatewayRuntime, "process_is_running", still_running)
+ monkeypatch.setattr(update_stop.GatewayRuntime, "process_identity_match", lambda self, identity, pid: "match")
+ try:
+ with pytest.raises(TimeoutError, match="process exit is not confirmed"):
+ await asyncio.wait_for(stop_reviewed_gateways(directory), timeout=30)
+ assert all(stop.is_set() for stop in stops)
+ assert all(gate.paused for gate in gates)
+ assert read_record(installation_state_dir() / "stop.json")["phase"] == "commit"
+ monkeypatch.setattr(update_stop.GatewayRuntime, "process_is_running", lambda self, pid: False)
+ await stop_reviewed_gateways(directory)
+ finally:
+ for watcher in watchers:
+ watcher.cancel()
+ await asyncio.gather(*watchers, return_exceptions=True)
+ for stack in outer:
+ stack.close()
+
+
+async def test_inactive_unselected_profile_must_also_finish_its_process_exit(protocol, monkeypatch, expire_stop_deadline):
+ from nanobot import update_stop
+
+ _, original, gates, stops = protocol
+ first, second = original.profiles
+ inactive = second.model_copy(update={"state": "stopped", "receipt": second.receipt.model_copy(update={"active": False})})
+ directory, _ = prepared_job([first, inactive], stop=[first.receipt.id])
+
+ def require_stopped(_expected, _environment):
+ if not stops[0].is_set():
+ raise ValueError("First gateway has not stopped")
+
+ monkeypatch.setattr(update_stop, "require_stopped_profiles", require_stopped)
+ def still_running(_runtime, pid):
+ if pid == second.receipt.pid:
+ expire_stop_deadline()
+ return True
+ return False
+
+ monkeypatch.setattr(update_stop.GatewayRuntime, "process_is_running", still_running)
+ monkeypatch.setattr(update_stop.GatewayRuntime, "process_identity_match", lambda self, identity, pid: "match")
+ outer = ExitStack()
+ watcher = asyncio.create_task(watch_gateway_stop(first.receipt, lambda: gates[0].pause_if_idle(lambda: False),
+ stops[0], outer))
+ try:
+ with pytest.raises(TimeoutError, match="process exit is not confirmed"):
+ await asyncio.wait_for(stop_reviewed_gateways(directory), timeout=30)
+ assert stops[0].is_set() and not stops[1].is_set()
+ monkeypatch.setattr(update_stop.GatewayRuntime, "process_is_running", lambda self, pid: False)
+ await stop_reviewed_gateways(directory)
+ finally:
+ watcher.cancel()
+ await asyncio.gather(watcher, return_exceptions=True)
+ outer.close()
+
+
[email protected]("change", [{"stop_protocol": None}, {"launch_mode": "foreground"}])
+def test_old_or_externally_owned_gateway_cannot_be_selected_for_stop(protocol, change):
+ _, plan, _, _ = protocol
+ values = plan.model_dump(mode="json")
+ values["profiles"][0]["receipt"].update(change)
+ with pytest.raises(ValueError, match="cooperative stop support"):
+ UpdatePlan.model_validate(values)
+
+
+async def test_actual_gateway_exits_normally_before_installation_and_data_leases_are_available(private_home, tmp_path):
+ """Actual gateway stop, not a public download/install/restart E2E."""
+ profile = tmp_path / "gateway home"
+ workspace = tmp_path / "中文 workspace"
+ profile.mkdir()
+ with socket.socket() as listener:
+ listener.bind(("127.0.0.1", 0))
+ port = listener.getsockname()[1]
+ config_path = profile / "config.json"
+ config_path.write_text(json.dumps({
+ "agents": {"defaults": {"workspace": str(workspace), "dream": {"enabled": False},
+ "provider": "custom", "model": "lifecycle-test"}},
+ "providers": {"custom": {"apiKey": "fixture-not-a-secret", "apiBase": "http://127.0.0.1:1/v1"}},
+ "gateway": {"host": "127.0.0.1", "port": port, "heartbeat": {"enabled": False}},
+ "channels": {"websocket": {"enabled": False}},
+ }))
+ source = Path(__file__).resolve().parents[1]
+ script = (
+ f"import sys; sys.path.insert(0, {str(source)!r})\n"
+ "from nanobot.cli import gateway_runtime\n"
+ "gateway_runtime.warmup_token_encoding = lambda: None\n"
+ "from nanobot.cli.entry import main\nmain()\n"
+ )
+ children = []
+
+ def spawn(command, **kwargs):
+ assert command[1:3] == ["-m", "nanobot"]
+ child = subprocess.Popen([command[0], "-c", script, *command[3:]], **kwargs)
+ children.append(child)
+ return child
+
+ selected_home = get_selected_home_path()
+ set_home_path(profile)
+ instance = GatewayInstance.resolve(config_path=config_path)
+ runtime = GatewayRuntime(paths=instance.paths, python_executable=sys.executable, popen=spawn)
+ try:
+ assert runtime.start_background(instance.start_options(port=port)).ok
+
+ def gateway_ready():
+ assert children[0].poll() is None, "Gateway exited before readiness"
+ return runtime.status().ready
+
+ try:
+ # Importing a real gateway on a shared Windows runner can exceed the
+ # 5 s budget for the in-process protocol tests. Match the WebUI smoke
+ # test's startup budget without relaxing shutdown or lease assertions.
+ await wait_until(gateway_ready, timeout=20)
+ except (TimeoutError, AssertionError) as exc:
+ logs = instance.paths.log_path.read_text(encoding="utf-8", errors="replace")[-8000:]
+ raise AssertionError(f"Gateway did not become ready: {exc}\n{logs}") from exc
+ profiles = inspect_profiles(sys.prefix)
+ assert len(profiles) == 1 and profiles[0].receipt.stop_protocol == 1
+ assert profiles[0].receipt.launch_mode == "background"
+ directory, plan = prepared_job(profiles)
+ await stop_reviewed_gateways(directory, timeout=10)
+ assert children[0].wait(timeout=5) == 0
+ assert not runtime.status().running
+ assert inspect_profiles(sys.prefix)[0].state == "stopped"
+ receipt = plan.profiles[0].receipt
+ with installation_access(updating=True), data_access(profile_data_paths(
+ home=Path(receipt.home), data_dir=Path(receipt.data_dir),
+ config=Path(receipt.config), workspace=Path(receipt.workspace),
+ ), updating=True):
+ pass
+ assert JobStatus.read(directory).phase == Phase.READY
+ assert not (directory / "approval.json").exists()
+ assert len(children) == 1, "Stop-only handoff launched an unrequested replacement"
+ finally:
+ for child in children:
+ if child.poll() is None:
+ if os.name == "nt":
+ # A venv python.exe may be only a redirector. On failure,
+ # clean up its owned tree rather than orphan the gateway.
+ subprocess.run(["taskkill", "/PID", str(child.pid), "/T", "/F"],
+ capture_output=True, timeout=10)
+ else:
+ child.terminate()
+ child.wait(timeout=10)
+ set_home_path(selected_home)
diff --git a/tests/test_update_uv.py b/tests/test_update_uv.py
new file mode 100644
index 000000000..bab75c713
--- /dev/null
+++ b/tests/test_update_uv.py
@@ -0,0 +1,319 @@
+"""Real uv/frozen-worker transactions; synthetic packages and a private HTTP index.
+
+These prove manager ownership and prepared-input behavior, not gateway migration,
+UI acceptance, public distribution or native Windows support.
+"""
+
+import asyncio
+import hashlib
+import os
+import shutil
+import subprocess
+import sys
+import threading
+import time
+from functools import partial
+from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
+from pathlib import Path
+from unittest.mock import AsyncMock
+from uuid import uuid4
+from zipfile import ZipFile
+
+import httpx
+import pytest
+from packaging.tags import sys_tags
+from test_update_jobs import _preparer_script, wheel
+
+import nanobot.update_jobs as jobs
+from nanobot.installation_lock import (
+ InstallationBusyError,
+ file_access,
+ installation_access,
+ installation_state_dir,
+)
+from nanobot.release_feed import ReleaseFeed, ReleaseTarget
+from nanobot.releases import PLATFORMS, ReleaseArtifact, release_filenames
+from nanobot.update_manager import read_manager_policy
+from nanobot.update_plan import InstallationSnapshot, UpdatePlan
+from nanobot.update_stop import stop_reviewed_gateways
+from nanobot.update_uv import UV_TRANSACTION_VERSION, cache_digest, uv_environment
+from nanobot.update_worker import JobStatus, Phase, WorkerSpec, inspect_environment
+
+pytestmark = pytest.mark.skipif(os.name != "posix" or not shutil.which("uv"), reason="Native POSIX uv required")
+
+_FAIL_VERIFICATION_ONCE = """
+from _nanobot_update import update_worker
+original_verify = update_worker._verify
+def verify(spec, directory):
+ marker = directory / 'fail-verification'
+ if marker.exists():
+ marker.unlink()
+ raise ValueError('Controlled post-install verification failure')
+ original_verify(spec, directory)
+update_worker._verify = verify
+"""
+
+
+class IndexHandler(SimpleHTTPRequestHandler):
+ def log_message(self, *_args):
+ pass
+
+
+def uv_installation(tmp_path, monkeypatch):
+ # Private synthetic package-manager fixtures, not release-signature proof.
+ monkeypatch.setattr(ReleaseFeed, "_authorize", AsyncMock())
+ from nanobot import update_process
+
+ manager_version = subprocess.check_output([shutil.which("uv"), "--version"], text=True, timeout=10)
+ if manager_version.split()[:2] != ["uv", UV_TRANSACTION_VERSION]:
+ pytest.skip(f"Native transaction integration requires uv {UV_TRANSACTION_VERSION}")
+ tmp_path = tmp_path.resolve()
+ account = tmp_path / "private account"
+ account.mkdir()
+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: account))
+ # The read-only bootstrap has the same isolated account as frozen workers.
+ monkeypatch.setattr(update_process, "_INSPECTION_BOOTSTRAP", (
+ "from pathlib import Path\n"
+ f"Path.home = classmethod(lambda cls: Path({str(account)!r}))\n"
+ ) + update_process._INSPECTION_BOOTSTRAP)
+ archive_worker = jobs._worker_archive
+
+ def private_worker(path):
+ # All worker entrypoints, including installer children, use a private
+ # account. Do not change HOME or patch production transaction behavior.
+ archive_worker(path)
+ with ZipFile(path) as source:
+ files = {item.filename: source.read(item) for item in source.infolist()}
+ files["__main__.py"] = (
+ "from pathlib import Path\n"
+ f"Path.home = classmethod(lambda cls: Path({str(account)!r}))\n"
+ ).encode() + _FAIL_VERIFICATION_ONCE.encode() + files["__main__.py"]
+ with ZipFile(path, "w") as target:
+ for name, content in files.items():
+ target.writestr(name, content)
+ return hashlib.sha256(path.read_bytes()).hexdigest()
+
+ monkeypatch.setattr(jobs, "_worker_archive", private_worker)
+ artifacts = tmp_path / "index"
+ artifacts.mkdir()
+
+ def index():
+ for file in artifacts.glob("*.whl"):
+ name = file.name.split("-")[0].replace("_", "-")
+ page = artifacts / "simple" / name / "index.html"
+ page.parent.mkdir(parents=True, exist_ok=True)
+ links = artifacts.glob(file.name.split("-")[0] + "-*.whl")
+ page.write_text("\n".join(f'<a href="../../{item.name}">{item.name}</a>' for item in links))
+
+ wheel(artifacts, "fixture-feature", "1.0.0")
+ wheel(artifacts, "fixture-injected", "1.0.0")
+ wheel(artifacts, "fixture-obsolete", "1.0.0")
+ wheel(artifacts, "nanobot-ai", "0.3.4", extras=["feature"], entrypoint=True,
+ requires=['fixture-feature>=1; extra == "feature"', "fixture-obsolete==1.0.0"])
+ index()
+ server = ThreadingHTTPServer(("127.0.0.1", 0), partial(IndexHandler, directory=str(artifacts)))
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ try:
+ tools, binaries = tmp_path / "tools", tmp_path / "bin"
+ env = uv_environment(tools=tools, binaries=binaries, cache=tmp_path / "original cache")
+ subprocess.run([
+ shutil.which("uv"), "tool", "install", "--no-config", "--python", sys._base_executable,
+ "--index-url", f"http://127.0.0.1:{server.server_port}/simple/",
+ "--with", "fixture-injected==1.0.0", "nanobot-ai[feature]>=0.3.4,<0.4",
+ ], env=env, check=True, capture_output=True, timeout=60)
+ environment = tools / "nanobot-ai"
+ python = str(environment / "bin/python")
+ baseline = inspect_environment(python, uv=True)
+ receipt = environment / "uv-receipt.toml"
+ assert "no-build" not in receipt.read_text(), "Baseline must not already have staging's no-build option"
+ package = subprocess.check_output([
+ python, "-I", "-c", "import nanobot; print(nanobot.__file__)",
+ ], text=True).strip()
+ snapshot = InstallationSnapshot(
+ environment=str(environment), python=python, installed_version="0.3.4", running_version="0.3.4",
+ package_path=package, running_package=package, owner="uv",
+ records={"pyvenv.cfg": baseline.receipt_sha, "uv-receipt.toml": baseline.manager_receipt_sha,
+ **baseline.app_records},
+ manager=read_manager_policy(environment, "uv", baseline.manager_receipt_sha),
+ )
+ wheel(artifacts, "fixture-feature", "2.0.0")
+ wheel(artifacts, "fixture-runtime", "2.0.0")
+ platform = next(tag.platform for tag in sys_tags() if tag.platform in PLATFORMS.values())
+ candidate = wheel(artifacts, "nanobot-ai", "0.3.5", platform=platform, extras=["feature"], entrypoint=True,
+ requires=['fixture-feature>=2; extra == "feature"', "fixture-runtime>=2"])
+ wheel(artifacts, "nanobot-ai", "0.3.6", entrypoint=True)
+ index()
+ target = ReleaseTarget(version="0.3.5", source="pypi",
+ url=f"https://files.pythonhosted.org/packages/{candidate.name}",
+ artifact=ReleaseArtifact(filename=candidate.name, size=candidate.stat().st_size,
+ sha256=hashlib.sha256(candidate.read_bytes()).hexdigest()))
+ now = int(time.time())
+ plan = UpdatePlan(id=str(uuid4()), installation=snapshot, target=target, extras=["feature"],
+ channel="stable", created_at=now, expires_at=now + 900)
+
+ def response(request):
+ if request.url.host == "files.pythonhosted.org":
+ assert request.url.path.endswith(candidate.name)
+ return httpx.Response(200, content=candidate.read_bytes())
+ assert request.url.path == "/pypi/nanobot-ai/0.3.5/json"
+ files = []
+ for filename in release_filenames("0.3.5"):
+ if filename.endswith((".whl", ".tar.gz")):
+ selected = filename == candidate.name
+ files.append({"filename": filename, "size": target.artifact.size if selected else 1,
+ "url": f"https://files.pythonhosted.org/packages/{filename}", "yanked": False,
+ "digests": {"sha256": target.artifact.sha256 if selected else "a" * 64}})
+ return httpx.Response(200, json={"info": {"name": "nanobot-ai", "version": "0.3.5", "requires_python": ">=3.11"}, "urls": files})
+
+ yield plan, baseline, receipt, httpx.MockTransport(response), server
+ finally:
+ server.shutdown()
+ server.server_close()
+ thread.join(timeout=10)
+
+
[email protected]("mode", ["install", "tamper", "repair", "external-policy"])
+async def test_uv_prepared_job_preserves_owner_and_sealed_inputs(uv_installation, tmp_path, monkeypatch, mode):
+ plan, before, receipt, transport, server = uv_installation
+ original_receipt = receipt.read_bytes()
+ async with ReleaseFeed(tmp_path / "feed", transport=transport) as feed:
+ if mode == "external-policy":
+ # A later user-level index/security policy cannot silently disappear
+ # merely because this first implementation only froze the receipt.
+ config_root = tmp_path / "user config"
+ config = config_root / "uv/uv.toml"
+ config.parent.mkdir(parents=True)
+ config.write_text('exclude-newer = "2026-01-01T00:00:00Z"\n')
+ monkeypatch.setenv("XDG_CONFIG_HOME", str(config_root))
+ with pytest.raises(ValueError, match="External uv configuration"):
+ await jobs.prepare_job(plan, feed)
+ assert inspect_environment(plan.installation.python, uv=True) == before
+ assert receipt.read_bytes() == original_receipt
+ return
+ directory = await jobs.prepare_job(plan, feed)
+ spec = WorkerSpec.read(directory)
+ assert spec.uv is not None
+ assert inspect_environment(plan.installation.python, uv=True) == before
+ assert receipt.read_bytes() == original_receipt
+ # The selected app is not the newer index version, injected packages and
+ # extras survive, and an obsolete dependency is removed by the owner.
+ assert spec.uv.versions == {
+ "nanobot-ai": "0.3.5", "fixture-feature": "2.0.0",
+ "fixture-runtime": "2.0.0", "fixture-injected": "1.0.0",
+ }
+ cache = directory / spec.uv.cache
+ server.shutdown()
+ server.server_close() # Dependencies must come entirely from prepared inputs.
+ if mode == "tamper":
+ (cache / "changed-after-preparation").write_text("not part of approved preparation")
+ # Preflight can encounter cache changes after the initial worker
+ # check (for example during release revalidation). Refuse before
+ # posting even a shutdown preparation request to the gateways.
+ with pytest.raises(ValueError, match="cache changed"):
+ await stop_reviewed_gateways(directory)
+ assert not (directory.parent.parent / "stop.json").exists()
+ with pytest.raises(ValueError, match="cache changed"):
+ await jobs.start_job(directory, feed)
+ assert not (directory / "approval.json").exists()
+ assert not (directory / "backup").exists()
+ assert inspect_environment(plan.installation.python, uv=True) == before
+ return
+ if mode == "repair":
+ (directory / "fail-verification").touch()
+ process = await jobs.start_job(directory, feed)
+ code = await asyncio.to_thread(process.wait, 60)
+ status = JobStatus.read(directory)
+ if mode == "repair":
+ assert code != 0 and status.phase == Phase.FAILED and status.mutation_started
+ backup = (directory / "backup/data.zip").read_bytes()
+ with pytest.raises(ValueError, match="explicit repair"):
+ await jobs.start_job(directory, feed)
+ process = await jobs.start_job(directory, feed, repair=True)
+ code = await asyncio.to_thread(process.wait, 60)
+ status = JobStatus.read(directory)
+ assert (directory / "backup/data.zip").read_bytes() == backup
+ assert code == 0, status
+ assert status.phase == Phase.INSTALLED, status
+ assert inspect_environment(plan.installation.python, uv=True).versions == spec.uv.versions
+ assert receipt.read_bytes() == original_receipt
+ assert cache_digest(cache) == spec.uv.cache_sha256
+ assert (directory / "backup/data.zip").is_file()
+ assert len(list(directory.glob(".uv-apply-*"))) == (2 if mode == "repair" else 1)
+
+
+async def test_orphan_native_uv_preparation_keeps_lease_and_can_be_settled(uv_installation, tmp_path):
+ plan, before, receipt, transport, server = uv_installation
+ async with ReleaseFeed(tmp_path / "ready-feed", transport=transport) as feed:
+ prepared = await jobs.prepare_job(plan, feed)
+ plan = plan.model_copy(update={"id": str(uuid4())})
+ root = installation_state_dir(plan.installation.environment)
+ directory = root / "jobs" / plan.id
+ entered, release = threading.Event(), threading.Event()
+ original_receipt = receipt.read_bytes()
+ native_pid = tmp_path / "native-pid"
+
+ class HeldIndex(IndexHandler):
+ def do_GET(self):
+ if self.path.startswith("/simple/fixture-runtime/"):
+ entered.set()
+ assert release.wait(20), "The native uv test was not released"
+ super().do_GET()
+
+ server.RequestHandlerClass = partial(HeldIndex, directory=str(tmp_path / "index"))
+ template = tmp_path / "private-worker.pyz"
+ jobs._worker_archive(template) # Existing fixture makes every child use the private account.
+ hook = f"""
+import shutil, subprocess
+Path.home = classmethod(lambda cls: Path({str(Path.home())!r}))
+def private_worker(path):
+ shutil.copyfile({str(template)!r}, path)
+ return 'unused-before-final-checksum'
+update_jobs._worker_archive = private_worker
+original_popen = subprocess.Popen
+def observed_popen(*args, **kwargs):
+ child = original_popen(*args, **kwargs)
+ Path({str(native_pid)!r}).write_text(str(child.pid))
+ return child
+subprocess.Popen = observed_popen
+"""
+ script = _preparer_script(plan, tmp_path / "index" / plan.target.artifact.filename, tmp_path / "feed", hook)
+ parent = subprocess.Popen([sys.executable, "-I", "-c", script], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+ try:
+ async with asyncio.timeout(15):
+ while not entered.is_set():
+ assert parent.poll() is None, "Preparation exited before native uv reached the index"
+ await asyncio.sleep(0.01)
+ parent.kill()
+ await asyncio.to_thread(parent.wait, 10)
+ os.kill(int(native_pid.read_text()), 0)
+ with pytest.raises(InstallationBusyError):
+ with installation_access(updating=True, environment=plan.installation.environment):
+ pytest.fail("Native uv lost its own runtime lease after parent death")
+ with pytest.raises(BlockingIOError):
+ jobs.settle_interrupted_preparation(directory)
+ with pytest.raises(BlockingIOError):
+ await stop_reviewed_gateways(prepared)
+ assert not (root / "stop.json").exists(), "A live native preparation must be refused before shutdown"
+ assert JobStatus.read(directory).phase == Phase.PREPARING
+ assert not (directory / "request.json").exists()
+ finally:
+ release.set()
+ if parent.poll() is None:
+ parent.kill()
+ await asyncio.to_thread(parent.wait, 10)
+ async with asyncio.timeout(20):
+ while True:
+ try:
+ with file_access(root / "prepare-native.lock", exclusive=True):
+ break
+ except BlockingIOError:
+ await asyncio.sleep(0.01)
+ assert jobs.settle_interrupted_preparation(directory).phase == Phase.PREPARATION_FAILED
+ assert inspect_environment(plan.installation.python, uv=True) == before
+ assert receipt.read_bytes() == original_receipt
+ async with ReleaseFeed(tmp_path / "retry-feed", transport=transport) as feed:
+ assert await jobs.prepare_job(plan, feed) == directory
+ assert JobStatus.read(directory).phase == Phase.READY
+ assert not (directory / "approval.json").exists()
diff --git a/tests/test_windows_update_paths.py b/tests/test_windows_update_paths.py
new file mode 100644
index 000000000..f648ceabd
--- /dev/null
+++ b/tests/test_windows_update_paths.py
@@ -0,0 +1,124 @@
+"""Ordinary Windows path inputs at the update record and lease I/O boundaries."""
+
+import stat
+import sys
+from pathlib import Path
+
+import pytest
+
+from nanobot.installation_lock import file_access
+from nanobot.update_worker import read_record, write_record
+from nanobot.utils.atomic_file import (
+ _open_snapshot,
+ atomic_write_lines,
+ atomic_write_text,
+ io_path,
+ read_atomic_bytes,
+)
+
+pytestmark = pytest.mark.skipif(sys.platform != "win32", reason="Windows filesystem semantics")
+
+
+def record_path(root: Path, length: int) -> Path:
+ # Only fixture setup/inspection uses the extended namespace. Every product
+ # operation below receives an ordinary absolute path, including at 280 chars.
+ root = Path(str(root).removeprefix("\\\\?\\"))
+ padding = length - len(str(root)) - len("\\status.json") - 1
+ assert 0 < padding < 255
+ path = root / ("d" * padding) / "status.json"
+ assert path.is_absolute() and len(str(path)) == length
+ return path
+
+
+def fixture_path(path: Path) -> Path:
+ return Path("\\\\?\\" + str(path))
+
+
[email protected]("length", [228, 280], ids=["long-sibling", "long-target"])
[email protected]("kind", ["text", "lines"])
+def test_atomic_io(tmp_path: Path, length: int, kind: str) -> None:
+ target = record_path(tmp_path, length)
+ sibling = target.with_name(f".{target.name}.{'0' * 32}.tmp")
+ assert len(str(sibling)) == length + 38 > 260
+ if kind == "lines":
+ fixture_path(target.parent).mkdir(parents=True)
+
+ def write(text: str) -> None:
+ if kind == "text":
+ atomic_write_text(target, text)
+ else:
+ atomic_write_lines(target, [text])
+
+ suffix = b"" if kind == "text" else b"\n"
+ write("old")
+ with _open_snapshot(target) as previous:
+ write("new")
+ assert previous.read() == b"old" + suffix
+ assert read_atomic_bytes(target) == b"new" + suffix
+ assert read_atomic_bytes(target, max_bytes=2) == b"ne"
+ assert list(fixture_path(target.parent).glob("*.tmp")) == []
+
+
[email protected]("length", [228, 280], ids=["long-sibling", "long-target"])
+def test_update_record(tmp_path: Path, length: int) -> None:
+ target = record_path(tmp_path, length)
+ fixture_path(target.parent).mkdir(parents=True)
+ write_record(target, {"state": "ready"})
+ assert read_record(target) == {"state": "ready"}
+ with _open_snapshot(target) as previous:
+ write_record(target, {"state": "stopping"})
+ assert previous.read() == b'{"state":"ready"}\n'
+ assert read_record(target) == {"state": "stopping"}
+
+
[email protected]("kind", ["text", "lines"])
+def test_readonly_record_keeps_old_value(tmp_path: Path, kind: str) -> None:
+ target = record_path(tmp_path, 228)
+ fixture_path(target.parent).mkdir(parents=True)
+ fixture_path(target).write_bytes(b"kept\n")
+ target.chmod(stat.S_IREAD)
+ try:
+ with pytest.raises(PermissionError):
+ if kind == "text":
+ atomic_write_text(target, "new\n")
+ else:
+ atomic_write_lines(target, ["new"])
+ assert read_atomic_bytes(target) == b"kept\n"
+ assert list(fixture_path(target.parent).glob("*.tmp")) == []
+ finally:
+ target.chmod(stat.S_IWRITE)
+
+
+def test_long_file_lease(tmp_path: Path) -> None:
+ target = record_path(tmp_path, 280).with_suffix(".lock")
+ with file_access(target, exclusive=False):
+ with file_access(target, exclusive=False):
+ with pytest.raises(BlockingIOError):
+ with file_access(target, exclusive=True):
+ pytest.fail("An updater acquired a live runtime's lease")
+ with file_access(target, exclusive=True):
+ with pytest.raises(BlockingIOError):
+ with file_access(target, exclusive=False):
+ pytest.fail("A runtime entered an updating installation")
+ with file_access(target, exclusive=False):
+ pass
+
+
+def test_io_path_spelling(tmp_path: Path) -> None:
+ ordinary = tmp_path / "nested" / ".." / "status.json"
+ extended = fixture_path(tmp_path / "status.json")
+ assert io_path(ordinary) == extended
+ assert io_path(extended) == extended
+ assert io_path(Path(r"\\server\share\updates\status.json")) == Path(
+ r"\\?\UNC\server\share\updates\status.json"
+ )
+
+
+def test_relative_atomic_io(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.chdir(tmp_path)
+ target = Path("relative state") / "status.json"
+ atomic_write_text(target, "old")
+ with _open_snapshot(target) as previous:
+ atomic_write_text(target, "new")
+ assert previous.read() == b"old"
+ assert read_atomic_bytes(target) == b"new"
diff --git a/tests/tools/test_shell_execution_budgets.py b/tests/tools/test_shell_execution_budgets.py
index 5dcfbca9d..33d2aa353 100644
--- a/tests/tools/test_shell_execution_budgets.py
+++ b/tests/tools/test_shell_execution_budgets.py
@@ -8,6 +8,7 @@ import sys
import time
from contextlib import suppress
from pathlib import Path
+from unittest.mock import Mock
import pytest
@@ -122,6 +123,20 @@ async def _pid_stopped(pid: int, *, timeout: float = 6) -> None:
assert not _pid_running(pid), f"subprocess {pid} is still running after {timeout}s"
[email protected](sys.platform != "linux", reason="Linux /proc process probe")
[email protected]("disappeared", [FileNotFoundError, ProcessLookupError])
+async def test_pid_stopped_tolerates_exit_during_proc_read(monkeypatch, disappeared):
+ stat = Mock()
+ stat.exists.return_value = True
+ stat.read_text.side_effect = disappeared("process exited during stat read")
+ monkeypatch.setattr(sys.modules[__name__], "Path", Mock(return_value=stat))
+ monkeypatch.setattr(os, "kill", Mock(side_effect=[None, ProcessLookupError, ProcessLookupError]))
+
+ await _pid_stopped(123, timeout=1)
+
+ stat.read_text.assert_called_once()
+
+
async def _cleanup_pidfiles(*paths: Path) -> None:
pids = [int(path.read_text()) for path in paths if path.exists() and path.read_text()]
for pid in pids:
diff --git a/tests/utils/test_helpers.py b/tests/utils/test_helpers.py
index 6cf677202..3e6c35d48 100644
--- a/tests/utils/test_helpers.py
+++ b/tests/utils/test_helpers.py
@@ -5,7 +5,7 @@ from pathlib import Path
import pytest
-from nanobot.utils import helpers, token_encoding
+from nanobot.utils import atomic_file, file_io, token_encoding
from nanobot.utils.helpers import (
_write_text_atomic,
atomic_write_lines,
@@ -162,9 +162,9 @@ def test_write_text_atomic_fsyncs_file_and_parent_directory(
fsync_calls.append(fd)
with monkeypatch.context() as patch:
- patch.setattr(helpers.os, "fsync", fake_fsync)
- patch.setattr(helpers.os, "open", lambda path, flags: 12345)
- patch.setattr(helpers.os, "close", lambda fd: closed_fds.append(fd))
+ patch.setattr(file_io.os, "fsync", fake_fsync)
+ patch.setattr(file_io.os, "open", lambda path, flags: 12345)
+ patch.setattr(file_io.os, "close", lambda fd: closed_fds.append(fd))
_write_text_atomic(target, '{"approved": {}}')
@@ -185,8 +185,8 @@ def test_write_text_atomic_keeps_file_when_directory_fsync_is_unsupported(
raise OSError("directory fsync unsupported")
with monkeypatch.context() as patch:
- patch.setattr(helpers.os, "fsync", lambda fd: fsync_calls.append(fd))
- patch.setattr(helpers.os, "open", fake_open)
+ patch.setattr(file_io.os, "fsync", lambda fd: fsync_calls.append(fd))
+ patch.setattr(file_io.os, "open", fake_open)
_write_text_atomic(target, '{"pending": {}}')
@@ -215,9 +215,24 @@ def test_atomic_write_lines_round_trip_replaces_target(tmp_path: Path) -> None:
atomic_write_lines(target, ['{"a": 1}', "café"])
assert target.read_text(encoding="utf-8") == '{"a": 1}\ncafé\n'
+ assert target.read_bytes() == '{"a": 1}\ncafé\n'.encode("utf-8")
assert list(tmp_path.glob("*.tmp")) == []
[email protected]("name", ["status.json", "更新状态-🐈.json"])
+def test_atomic_record_reader_does_not_block_concurrent_replacement(tmp_path: Path, name: str) -> None:
+ """The update UI can poll while a detached worker commits its next phase."""
+ from nanobot.utils.atomic_file import _open_snapshot, read_atomic_bytes
+
+ target = tmp_path / name
+ atomic_write_lines(target, ['{"phase":"checking"}'])
+ with _open_snapshot(target) as previous:
+ atomic_write_lines(target, ['{"phase":"stopping"}'])
+ assert previous.read() == b'{"phase":"checking"}\n'
+ assert read_atomic_bytes(target) == b'{"phase":"stopping"}\n'
+ assert read_atomic_bytes(target, max_bytes=2) == b'{"'
+
+
def test_atomic_write_lines_empty_input_replaces_file_with_empty(tmp_path: Path) -> None:
target = tmp_path / "history.jsonl"
target.write_text("old\n", encoding="utf-8")
@@ -245,7 +260,7 @@ def test_atomic_writes_clean_temp_when_replace_fails(
def fail_replace(*_args: object, **_kwargs: object) -> None:
raise error_type("replace failed")
- monkeypatch.setattr(helpers.os, "replace", fail_replace)
+ monkeypatch.setattr("nanobot.utils.atomic_file.replace_atomic", fail_replace)
with pytest.raises(error_type, match="replace failed"):
write(target, "new")
@@ -271,7 +286,7 @@ def test_atomic_write_lines_skips_fsync_when_disabled(
) -> None:
target = tmp_path / "session.jsonl"
fsync_calls: list[int] = []
- monkeypatch.setattr(helpers.os, "fsync", lambda fd: fsync_calls.append(fd))
+ monkeypatch.setattr(atomic_file.os, "fsync", lambda fd: fsync_calls.append(fd))
atomic_write_lines(target, ["line"], fsync=False)
@@ -285,7 +300,7 @@ def test_atomic_write_lines_suppresses_directory_permission_error(
"""Windows directory open raises PermissionError; the replace must still stick."""
target = tmp_path / "history.jsonl"
opened: list[tuple[object, int]] = []
- real_open = helpers.os.open
+ real_open = atomic_file.os.open
def open_directory(path: object, flags: int, *args: object, **kwargs: object) -> int:
opened.append((path, flags))
@@ -293,12 +308,12 @@ def test_atomic_write_lines_suppresses_directory_permission_error(
raise PermissionError("directory open denied")
return real_open(path, flags, *args, **kwargs)
- monkeypatch.setattr(helpers.os, "open", open_directory)
+ monkeypatch.setattr(atomic_file.os, "open", open_directory)
atomic_write_lines(target, ["ok"])
assert target.read_text(encoding="utf-8") == "ok\n"
- assert opened == [(str(tmp_path), os.O_RDONLY)]
+ assert opened == [(str(atomic_file.io_path(tmp_path)), os.O_RDONLY)]
@pytest.mark.parametrize("error_number", [errno.EINVAL, errno.EIO], ids=["unsupported", "io-error"])
@@ -319,9 +334,9 @@ def test_atomic_writes_directory_fsync_errors(
target = tmp_path / "session.jsonl"
directory_fd = 12345
fsync_calls = 0
- real_fsync = helpers.os.fsync
- real_open = helpers.os.open
- real_close = helpers.os.close
+ real_fsync = atomic_file.os.fsync
+ real_open = atomic_file.os.open
+ real_close = atomic_file.os.close
opened: list[tuple[object, int]] = []
closed: list[int] = []
@@ -344,9 +359,9 @@ def test_atomic_writes_directory_fsync_errors(
return
raise OSError(error_number, "directory fsync failed")
- monkeypatch.setattr(helpers.os, "open", tracking_open)
- monkeypatch.setattr(helpers.os, "close", tracking_close)
- monkeypatch.setattr(helpers.os, "fsync", fsync_then_error)
+ monkeypatch.setattr(atomic_file.os, "open", tracking_open)
+ monkeypatch.setattr(atomic_file.os, "close", tracking_close)
+ monkeypatch.setattr(atomic_file.os, "fsync", fsync_then_error)
if error_number == errno.EINVAL:
write(target, "ok")
@@ -357,5 +372,5 @@ def test_atomic_writes_directory_fsync_errors(
assert target.read_text(encoding="utf-8") == expected_content
assert fsync_calls == 2
- assert opened == [(str(tmp_path), directory_fd)]
+ assert opened == [(str(atomic_file.io_path(tmp_path)), directory_fd)]
assert closed == [directory_fd]
diff --git a/tests/webui/test_build.py b/tests/webui/test_build.py
index ab2f5fdaa..b35b5d0ed 100644
--- a/tests/webui/test_build.py
+++ b/tests/webui/test_build.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import os
+from contextlib import nullcontext
from pathlib import Path
from nanobot.webui.build import (
@@ -100,7 +101,8 @@ def test_inspect_webui_bundle_accepts_fresh_dist(tmp_path: Path) -> None:
assert status.reason == "fresh"
-def test_ensure_webui_bundle_auto_builds_stale_dist(tmp_path: Path) -> None:
+def test_ensure_webui_bundle_auto_builds_stale_dist(tmp_path: Path, monkeypatch) -> None:
+ monkeypatch.setattr("nanobot.webui.build.bun_environment", lambda _: nullcontext({"PATH": "bun"}))
source = tmp_path / "webui"
dist = tmp_path / "nanobot" / "web" / "dist"
_touch(source / "package.json", mtime_ns=10)
@@ -108,11 +110,13 @@ def test_ensure_webui_bundle_auto_builds_stale_dist(tmp_path: Path) -> None:
_touch(dist / "index.html", mtime_ns=20)
commands: list[tuple[str, ...]] = []
- def fake_run(command, *, cwd: Path, check: bool) -> None:
+ def fake_run(command, *, cwd: Path, check: bool, env: dict[str, str], timeout: int) -> None:
commands.append(tuple(command))
assert cwd == source
assert check is True
- if command == ["bun", "run", "build"]:
+ assert "PATH" in env
+ assert timeout == 900
+ if command == ["bun", "--bun", "run", "build"]:
_touch(dist / "index.html", mtime_ns=40)
status = ensure_webui_bundle(
@@ -124,7 +128,7 @@ def test_ensure_webui_bundle_auto_builds_stale_dist(tmp_path: Path) -> None:
)
assert status.stale is False
- assert commands == [("bun", "install"), ("bun", "run", "build")]
+ assert commands == [("bun", "install", "--frozen-lockfile"), ("bun", "--bun", "run", "build")]
def test_pick_webui_build_runner_returns_resolved_executable(monkeypatch) -> None:
diff --git a/tests/webui/test_mcp_oauth_api.py b/tests/webui/test_mcp_oauth_api.py
index 274f84cf2..1aeeba857 100644
--- a/tests/webui/test_mcp_oauth_api.py
+++ b/tests/webui/test_mcp_oauth_api.py
@@ -5,6 +5,7 @@ import asyncio
import pytest
from nanobot.config.schema import MCPServerConfig
+from nanobot.runtime_admission import RuntimeAdmission, RuntimeBusyError, RuntimeMaintenanceError
from nanobot.webui.mcp_oauth_api import (
McpOAuthError,
McpOAuthManager,
@@ -45,7 +46,7 @@ def _config() -> MCPServerConfig:
async def test_browser_flow_retries_current_server_and_ignores_unrelated_reload_failure(
monkeypatch: pytest.MonkeyPatch,
) -> None:
- manager = McpOAuthManager()
+ manager = McpOAuthManager(RuntimeAdmission())
connection = _Connection()
received: dict[str, object] = {}
reload_calls = 0
@@ -116,6 +117,7 @@ async def test_browser_flow_retries_current_server_and_ignores_unrelated_reload_
assert first["hot_reload"]["failed"] == ["notion"]
assert received["callback"] == ("oauth-code", "state-123")
assert reload_calls == 2
+ await manager.close()
assert connection.closed is True
@@ -123,7 +125,8 @@ async def test_browser_flow_retries_current_server_and_ignores_unrelated_reload_
async def test_browser_flow_activates_tools_before_probe_cleanup_completes(
monkeypatch: pytest.MonkeyPatch,
) -> None:
- manager = McpOAuthManager()
+ admission = RuntimeAdmission()
+ manager = McpOAuthManager(admission)
connection = _BlockingConnection()
reload_started = asyncio.Event()
@@ -159,27 +162,92 @@ async def test_browser_flow_activates_tools_before_probe_cleanup_completes(
)
manager.submit_callback(state="blocked-close", code="oauth-code", error=None)
+ shutdown = None
try:
await asyncio.wait_for(reload_started.wait(), timeout=0.5)
await asyncio.wait_for(connection.close_started.wait(), timeout=0.5)
result = await manager.status(started["flow_id"])
assert result["status"] == "connected"
assert connection.closed is False
+ with pytest.raises(RuntimeBusyError), admission.pause_if_idle(lambda: False):
+ pytest.fail("MCP transport cleanup is still running")
+ shutdown = asyncio.create_task(manager.close())
+ await asyncio.wait({shutdown}, timeout=0.01)
+ assert not shutdown.done(), "Shutdown must join the in-flight transport cleanup"
finally:
connection.allow_close.set()
+ if shutdown is not None:
+ await shutdown
for _ in range(10):
await asyncio.sleep(0)
if connection.closed:
break
assert connection.closed is True
+ await manager.close()
+ with admission.pause_if_idle(lambda: False):
+ pass
+
+
[email protected]("expire", [False, True])
+async def test_browser_flow_remains_busy_through_cancelled_or_expired_cleanup(
+ monkeypatch: pytest.MonkeyPatch, expire: bool,
+) -> None:
+ admission = RuntimeAdmission()
+ manager = McpOAuthManager(admission)
+ cleanup_started = asyncio.Event()
+ allow_cleanup = asyncio.Event()
+ monkeypatch.setattr("nanobot.webui.mcp_oauth_api.validate_url_target", lambda _: (True, ""))
+ if expire:
+ monkeypatch.setattr("nanobot.webui.mcp_oauth_api._FLOW_TTL_S", 0)
+
+ async def connect(_servers, _registry, *, oauth_handlers):
+ handlers = oauth_handlers["linear"]
+ await handlers.redirect_handler("https://accounts.example.com/auth?state=pending")
+ try:
+ await handlers.callback_handler()
+ finally:
+ cleanup_started.set()
+ await allow_cleanup.wait()
+ return {}
+
+ monkeypatch.setattr("nanobot.webui.mcp_oauth_api.connect_mcp_servers", connect)
+ started = await manager.start(
+ "linear", _config(), "https://agent.example.com/auth/mcp/callback",
+ reload_mcp=lambda: asyncio.sleep(0, result={"ok": True}),
+ )
+ with pytest.raises(RuntimeBusyError), admission.pause_if_idle(lambda: False):
+ pytest.fail("The browser response does not finish authorization")
+ if expire:
+ with pytest.raises(McpOAuthError, match="expired"):
+ await manager.status(started["flow_id"])
+ await asyncio.wait_for(cleanup_started.wait(), timeout=0.5)
+
+ shutdown = asyncio.create_task(manager.close())
+ try:
+ await asyncio.wait_for(cleanup_started.wait(), timeout=0.5)
+ await asyncio.wait({shutdown}, timeout=0.01)
+ assert not shutdown.done()
+ with pytest.raises(RuntimeBusyError), admission.pause_if_idle(lambda: False):
+ pytest.fail("An expired or cancelled flow still owns its cleanup")
+ finally:
+ allow_cleanup.set()
+ await shutdown
+
+ with admission.pause_if_idle(lambda: False):
+ with pytest.raises(RuntimeMaintenanceError):
+ await manager.start(
+ "linear", _config(), "https://agent.example.com/auth/mcp/callback",
+ reload_mcp=lambda: asyncio.sleep(0, result={"ok": True}),
+ )
@pytest.mark.asyncio
async def test_remote_http_flow_accepts_a_pasted_loopback_callback(
monkeypatch: pytest.MonkeyPatch,
) -> None:
- manager = McpOAuthManager()
+ manager = McpOAuthManager(RuntimeAdmission())
connection = _Connection()
received: dict[str, object] = {}
@@ -247,6 +315,7 @@ async def test_remote_http_flow_accepts_a_pasted_loopback_callback(
assert result["status"] == "connected"
assert result["completion_input"] == "callback_url"
assert received["callback"] == ("oauth-code", "manual-state")
+ await manager.close()
assert connection.closed is True
@@ -254,7 +323,7 @@ async def test_remote_http_flow_accepts_a_pasted_loopback_callback(
async def test_browser_flow_surfaces_provider_denial_without_callback_description(
monkeypatch: pytest.MonkeyPatch,
) -> None:
- manager = McpOAuthManager()
+ manager = McpOAuthManager(RuntimeAdmission())
monkeypatch.setattr(
"nanobot.webui.mcp_oauth_api.validate_url_target",
lambda _url: (True, ""),
@@ -300,7 +369,7 @@ async def test_browser_flow_blocks_unsafe_authorization_url(
url_is_safe: bool,
state: str,
) -> None:
- manager = McpOAuthManager()
+ manager = McpOAuthManager(RuntimeAdmission())
monkeypatch.setattr(
"nanobot.webui.mcp_oauth_api.validate_url_target",
lambda _url: (url_is_safe, "private address"),
diff --git a/tests/webui/test_settings_api.py b/tests/webui/test_settings_api.py
index b44fd2123..abb039bf6 100644
--- a/tests/webui/test_settings_api.py
+++ b/tests/webui/test_settings_api.py
@@ -1941,6 +1941,13 @@ def test_openai_codex_oauth_login_passes_configured_proxy(
authorization_url = "https://auth.openai.com/oauth/authorize?state=test"
remaining_seconds = 600
expired = False
+ has_pending_work = False
+
+ def start(self):
+ pass
+
+ def wait_closed(self):
+ pass
def cancel(self) -> None:
captured["cancelled"] = True
@@ -1954,7 +1961,7 @@ def test_openai_codex_oauth_login_passes_configured_proxy(
return FakeFlow()
monkeypatch.setattr(
- "nanobot.providers.openai_codex_oauth.start_openai_codex_oauth_login",
+ "nanobot.providers.openai_codex_oauth.OpenAICodexOAuthLoginFlow",
fake_start,
)
@@ -1981,10 +1988,7 @@ def test_openai_codex_oauth_login_passes_configured_proxy(
return None
return SimpleNamespace(access="access-token")
- monkeypatch.setattr(
- "nanobot.providers.openai_codex_oauth.complete_openai_codex_oauth_login",
- fake_complete,
- )
+ monkeypatch.setattr(FakeFlow, "complete", fake_complete, raising=False)
monkeypatch.setattr(
"nanobot.webui.settings_api.settings_payload",
lambda **_kwargs: {"settings": "ready"},
@@ -2026,6 +2030,13 @@ def test_openai_codex_remote_login_uses_headless_dependency_mode(
authorization_url = "https://auth.openai.com/oauth/authorize?state=test"
remaining_seconds = 600
expired = False
+ has_pending_work = False
+
+ def start(self):
+ pass
+
+ def wait_closed(self):
+ pass
def cancel(self) -> None:
captured["cancelled"] = True
@@ -2035,7 +2046,7 @@ def test_openai_codex_remote_login_uses_headless_dependency_mode(
return FakeFlow()
monkeypatch.setattr(
- "nanobot.providers.openai_codex_oauth.start_openai_codex_oauth_login",
+ "nanobot.providers.openai_codex_oauth.OpenAICodexOAuthLoginFlow",
fake_start,
)
@@ -2109,6 +2120,13 @@ def test_xai_grok_login_starts_fresh_browser_flow_with_proxy(
authorization_url = "https://auth.x.ai/oauth2/authorize?state=test"
remaining_seconds = 600
expired = False
+ has_pending_work = False
+
+ def start(self):
+ pass
+
+ def wait_closed(self):
+ pass
def cancel(self) -> None:
captured["cancelled"] = True
@@ -2117,7 +2135,7 @@ def test_xai_grok_login_starts_fresh_browser_flow_with_proxy(
captured.update(proxy=proxy, timeout_s=timeout_s)
return FakeFlow()
- monkeypatch.setattr("nanobot.providers.xai_oauth.start_xai_oauth_login", fake_start)
+ monkeypatch.setattr("nanobot.providers.xai_oauth.create_xai_oauth_login", fake_start)
payload = login_oauth_provider(
{"provider": ["xai-grok"]},
@@ -2140,10 +2158,7 @@ def test_xai_grok_login_starts_fresh_browser_flow_with_proxy(
return None
return SimpleNamespace(access="access-token")
- monkeypatch.setattr(
- "nanobot.providers.xai_oauth.complete_xai_oauth_login",
- fake_complete,
- )
+ monkeypatch.setattr(FakeFlow, "complete", fake_complete, raising=False)
monkeypatch.setattr(
"nanobot.webui.settings_api.settings_payload",
lambda **_kwargs: {"settings": "ready"},
@@ -2181,7 +2196,7 @@ def test_xai_grok_login_reports_upstream_failure_as_bad_gateway(
def fake_start(**_kwargs):
raise failure
- monkeypatch.setattr("nanobot.providers.xai_oauth.start_xai_oauth_login", fake_start)
+ monkeypatch.setattr("nanobot.providers.xai_oauth.create_xai_oauth_login", fake_start)
with pytest.raises(WebUISettingsError) as exc:
login_oauth_provider(
@@ -2391,7 +2406,7 @@ def test_copilot_explicit_login_does_not_reuse_revoked_credentials(monkeypatch,
lambda: SimpleNamespace(access="revoked-token"),
)
monkeypatch.setattr(GitHubCopilotOAuthFlow, "start", start)
- monkeypatch.setattr(GitHubCopilotOAuthFlow, "complete", lambda _: SimpleNamespace(access="new-token"))
+ monkeypatch.setattr(GitHubCopilotOAuthFlow, "complete", lambda *_: SimpleNamespace(access="new-token"))
monkeypatch.setattr("nanobot.webui.settings_models.invalidate_oauth_model_catalog", invalidate)
monkeypatch.setattr("nanobot.webui.settings_api.settings_payload", lambda **_: {"ready": True})
payload = login_oauth_provider({"provider": ["github-copilot"]}, oauth_flows=oauth_flows)
@@ -2429,17 +2444,18 @@ def test_oauth_completion_clears_same_account_catalog_failure(monkeypatch, oauth
class Flow:
expired = False
+ has_pending_work = False
def cancel(self):
pass
- def complete(*_args):
- signed_in[0] = True
- return SimpleNamespace(access="fixture")
+ def wait_closed(self):
+ pass
+
+ def complete(self, _response=None):
+ signed_in[0] = True
+ return SimpleNamespace(access="fixture")
- owner = "openai_codex_oauth" if provider == "openai_codex" else "xai_oauth"
- completion = "complete_openai_codex_oauth_login" if provider == "openai_codex" else "complete_xai_oauth_login"
- monkeypatch.setattr(f"nanobot.providers.{owner}.{completion}", complete)
oauth_flows.register(provider, "flow-test", Flow())
before = provider_models_payload({"provider": [provider]})
assert before["error_kind"] == "auth_required"
diff --git a/tests/webui/test_settings_routes.py b/tests/webui/test_settings_routes.py
index cfad6842d..89c495d15 100644
--- a/tests/webui/test_settings_routes.py
+++ b/tests/webui/test_settings_routes.py
@@ -12,7 +12,10 @@ from urllib.parse import parse_qs, urlsplit
import pytest
from websockets.datastructures import Headers
+from nanobot.bus.queue import MessageBus
from nanobot.config.loader import get_config_path
+from nanobot.config.schema import MCPServerConfig
+from nanobot.runtime_admission import RuntimeBusyError
from nanobot.webui.http_utils import http_json_response
from nanobot.webui.mcp_presets_api import custom_mcp_action
from nanobot.webui.settings_routes import WebUISettingsRouter
@@ -35,8 +38,8 @@ def _router(
rename_model_preset=rename_model_preset,
refresh_runtime_config=refresh_runtime_config,
),
- bus=SimpleNamespace(),
- logger=SimpleNamespace(exception=lambda *_args: None),
+ bus=MessageBus(),
+ logger=SimpleNamespace(exception=lambda *_args: None, warning=lambda *_args: None),
check_api_token=lambda _request: authorized,
parse_query=lambda path: parse_qs(urlsplit(path).query),
json_response=http_json_response,
@@ -61,12 +64,37 @@ def _mutation_request(path: str, payload: dict[str, object]) -> SimpleNamespace:
return request
+async def test_nanobot_update_requires_auth_local_permission_and_websocket(tmp_path, monkeypatch):
+ router = _router(config_path=tmp_path / "config.json")
+ path = "/api/settings/nanobot-update/job/prepare"
+ request = SimpleNamespace(path=path, headers=Headers())
+ response = await router.dispatch(None, request, path)
+ assert response.status_code == 405
+ response = await router.dispatch(None, _mutation_request(path, {}), path)
+ assert response.status_code == 403
+ unauthorized = _router(authorized=False, config_path=tmp_path / "config.json")
+ response = await unauthorized.dispatch(None, _mutation_request(path, {}), path)
+ assert response.status_code == 401
+ monkeypatch.setattr(router._system, "allow_feature_package_install", lambda _: True)
+ response = await router.dispatch(None, _mutation_request(path, {"id": "invalid"}), path)
+ assert response.status_code == 400
+ router._runtime_surface = "native"
+ response = await router.dispatch(None, _mutation_request(path, {}), path)
+ assert response.status_code == 409
+
+
@pytest.mark.asyncio
async def test_close_releases_channel_connectors() -> None:
router = _router()
closed = False
class Connector:
+ has_pending_work = False
+
+ async def handle(self, action, query):
+ return {}
+
async def close(self) -> None:
nonlocal closed
closed = True
@@ -79,6 +107,162 @@ async def test_close_releases_channel_connectors() -> None:
assert router._system._channel_connectors == {}
[email protected]("finish", ["cancel", "logout", "shutdown"])
+async def test_provider_login_keeps_maintenance_busy_until_worker_exits(tmp_path, monkeypatch, finish):
+ router = _router(config_path=tmp_path / "config.json")
+ stopping, release = threading.Event(), threading.Event()
+ saved = []
+
+ def login(*, on_authorization, cancelled, persist, **_kwargs):
+ assert persist is False
+ on_authorization("https://github.com/login/device", "FIXTURE", 60)
+ assert cancelled.wait(3)
+ stopping.set()
+ assert release.wait(3)
+ return SimpleNamespace(access="late-fixture-token")
+
+ monkeypatch.setattr("nanobot.providers.github_copilot_oauth.login_github_copilot", login)
+ monkeypatch.setattr("nanobot.providers.github_copilot_provider.get_storage", lambda: SimpleNamespace(
+ get_token_path=lambda: tmp_path / "copilot.json", save=saved.append,
+ ))
+ monkeypatch.setattr("nanobot.webui.settings_api.settings_payload", lambda **_: {})
+ path = "/api/settings/provider/oauth-login"
+ response = await router.dispatch(None, _mutation_request(path, {"provider": "github_copilot"}), path)
+ assert response.status_code == 200
+ payload = json.loads(response.body)
+ with pytest.raises(RuntimeBusyError), router.bus.admission.pause_if_idle(lambda: False):
+ pytest.fail("The authorization prompt still has a live worker")
+ try:
+ if finish == "shutdown":
+ shutdown = asyncio.create_task(router.close())
+ assert await asyncio.to_thread(stopping.wait, 1)
+ shutdown.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await shutdown
+ else:
+ path = (
+ "/api/settings/provider/oauth-logout" if finish == "logout"
+ else "/api/settings/provider/oauth-login/complete"
+ )
+ response = await router.dispatch(None, _mutation_request(path, {
+ "provider": "github_copilot", "flow_id": payload["flow_id"], "cancel": "true",
+ }), path)
+ assert response.status_code == 200
+ assert await asyncio.to_thread(stopping.wait, 1)
+ assert router.settings.oauth_flows.get("github_copilot", payload["flow_id"]) is None
+ with pytest.raises(RuntimeBusyError), router.bus.admission.pause_if_idle(lambda: False):
+ pytest.fail("Removing a login or cancelling its close awaiter cannot forget the thread")
+ finally:
+ release.set()
+ await router.close()
+ assert saved == []
+ assert not router.settings.oauth_flows.has_pending_work
+ with router.bus.admission.pause_if_idle(lambda: False):
+ pass
+
+
+async def test_failed_codex_login_start_still_owns_late_worker(tmp_path, monkeypatch):
+ import nanobot.providers.openai_codex_oauth as oauth
+
+ router = _router(config_path=tmp_path / "config.json")
+ entered, release = threading.Event(), threading.Event()
+ target = tmp_path / "codex.json"
+ monkeypatch.setenv("OAUTH_CLI_KIT_TOKEN_PATH", str(target))
+ monkeypatch.setattr(oauth, "_AUTHORIZATION_URL_TIMEOUT_S", 0.02)
+
+ def login(*, storage, **_kwargs):
+ entered.set()
+ assert release.wait(3)
+ # The actual SDK can finish its token exchange after start() timed out.
+ storage.save(SimpleNamespace(access="late-fixture-token"))
+
+ monkeypatch.setattr(oauth, "login_oauth_interactive", login)
+ path = "/api/settings/provider/oauth-login"
+ try:
+ response = await router.dispatch(None, _mutation_request(path, {
+ "provider": "openai_codex", "remote_browser": "true",
+ }), path)
+ assert response.status_code == 502
+ assert entered.is_set()
+ with pytest.raises(RuntimeBusyError), router.bus.admission.pause_if_idle(lambda: False):
+ pytest.fail("A failed start must retain its background worker")
+ finally:
+ release.set()
+ await router.close()
+ assert not target.exists()
+ with router.bus.admission.pause_if_idle(lambda: False):
+ pass
+
+
[email protected]("close_fails", [False, True])
+async def test_channel_setup_blocks_maintenance_until_confirmed_cleanup(
+ tmp_path, monkeypatch, close_fails,
+) -> None:
+ router = _router(config_path=tmp_path / "config.json")
+ cleanup_started, allow_cleanup = asyncio.Event(), asyncio.Event()
+
+ class Connector:
+ has_pending_work = True
+
+ async def handle(self, action, query):
+ return {"status": "pending", "session_id": "test"}
+
+ async def close(self):
+ cleanup_started.set()
+ await allow_cleanup.wait()
+ if close_fails:
+ raise RuntimeError("native writer has not stopped")
+ self.has_pending_work = False
+
+ connector = Connector()
+ monkeypatch.setattr(
+ "nanobot.webui.settings_routes.load_channel_plugin",
+ lambda _: SimpleNamespace(load_connector=lambda: connector),
+ )
+ path = "/api/settings/channels/whatsapp/connect/start"
+ response = await router.dispatch(None, _mutation_request(path, {}), path)
+ assert response.status_code == 200
+ assert json.loads(response.body)["status"] == "pending"
+ with pytest.raises(RuntimeBusyError), router.bus.admission.pause_if_idle(lambda: False):
+ pytest.fail("Returning a QR code does not finish its connection")
+ shutdown = asyncio.create_task(router.close())
+ try:
+ await asyncio.wait_for(cleanup_started.wait(), timeout=0.5)
+ with pytest.raises(RuntimeBusyError), router.bus.admission.pause_if_idle(lambda: False):
+ pytest.fail("Cleanup still owns its pending connection")
+ finally:
+ allow_cleanup.set()
+ await shutdown
+ if close_fails:
+ assert router._system._channel_connectors["whatsapp"] is connector
+ with pytest.raises(RuntimeBusyError), router.bus.admission.pause_if_idle(lambda: False):
+ pytest.fail("A failed close must not release ownership")
+ close_fails = False
+ await router.close()
+ assert router._system._channel_connectors == {}
+ with router.bus.admission.pause_if_idle(lambda: False):
+ pass
+
+
+async def test_legacy_connector_can_connect_but_cannot_claim_maintenance_idle(tmp_path, monkeypatch):
+ router = _router(config_path=tmp_path / "config.json")
+ connector = SimpleNamespace(handle=AsyncMock(return_value={"status": "pending"}))
+ monkeypatch.setattr(
+ "nanobot.webui.settings_routes.load_channel_plugin",
+ lambda _: SimpleNamespace(load_connector=lambda: connector),
+ )
+ path = "/api/settings/channels/custom/connect/start"
+ response = await router.dispatch(None, _mutation_request(path, {}), path)
+ assert response.status_code == 200
+ await router.close()
+ with pytest.raises(RuntimeBusyError), router.bus.admission.pause_if_idle(lambda: False):
+ pytest.fail("An untracked extension must not be assumed idle")
+
+
@pytest.mark.asyncio
async def test_mcp_list_serializes_local_runtime_failure_snapshot(tmp_path) -> None:
config_path = tmp_path / "config.json"
@@ -222,6 +406,50 @@ async def test_mcp_reload_callback_is_bounded(
}
+async def test_settings_shutdown_joins_browser_authorization_and_releases_admission(
+ tmp_path, monkeypatch,
+) -> None:
+ config = MCPServerConfig(type="streamableHttp", auth="oauth", url="https://mcp.example/mcp")
+ monkeypatch.setattr(
+ "nanobot.webui.settings_routes.ensure_mcp_oauth_server",
+ lambda _query, *, config_path=None: ("linear", config),
+ )
+ monkeypatch.setattr("nanobot.webui.mcp_oauth_api.validate_url_target", lambda _: (True, ""))
+ cleanup_started, allow_cleanup = asyncio.Event(), asyncio.Event()
+
+ async def connect(_servers, _registry, *, oauth_handlers):
+ handlers = oauth_handlers["linear"]
+ await handlers.redirect_handler("https://accounts.example/authorize?state=settings")
+ try:
+ await handlers.callback_handler()
+ finally:
+ cleanup_started.set()
+ await allow_cleanup.wait()
+ return {}
+
+ monkeypatch.setattr("nanobot.webui.mcp_oauth_api.connect_mcp_servers", connect)
+ router = _router(config_path=tmp_path / "config.json")
+ path = "/api/settings/mcp-oauth/start"
+ response = await router.dispatch(None, _mutation_request(path, {"name": "linear"}), path)
+ assert response.status_code == 200
+ assert json.loads(response.body)["status"] == "authorization_required"
+ with pytest.raises(RuntimeBusyError), router.bus.admission.pause_if_idle(lambda: False):
+ pytest.fail("Settings returned, but authorization has not finished")
+
+ shutdown = asyncio.create_task(router.close())
+ try:
+ await asyncio.wait_for(cleanup_started.wait(), timeout=0.5)
+ assert not shutdown.done()
+ with pytest.raises(RuntimeBusyError), router.bus.admission.pause_if_idle(lambda: False):
+ pytest.fail("Settings shutdown must retain ownership through cleanup")
+ finally:
+ allow_cleanup.set()
+ await shutdown
+ with router.bus.admission.pause_if_idle(lambda: False):
+ pass
+
+
@pytest.mark.asyncio
async def test_mcp_oauth_start_uses_gateway_callback_and_requires_api_auth(monkeypatch) -> None:
config = SimpleNamespace(
@@ -554,7 +782,7 @@ async def test_version_check_route_returns_stable_payload(
) -> None:
monkeypatch.setattr(
"nanobot.webui.settings_routes.check_for_update",
- lambda: update_info,
+ lambda: {"updateAvailable": update_info, "releaseStatus": {"state": "available" if update_info else "current"}},
)
request = SimpleNamespace(path="/api/settings/version-check", headers=Headers())
@@ -585,6 +813,45 @@ async def test_version_check_route_enforces_auth_and_bounds_failures(
assert "upstream secret body" not in failed.body.decode()
[email protected]("state", ["waiting_stable", "withdrawn", "unavailable", "publishing", "unsupported"])
+async def test_channel_status_is_explicit_and_old_clients_never_report_false_success(monkeypatch, state):
+ result = {"updateAvailable": None, "releaseStatus": {
+ "channel": "stable", "revision": 2, "currentVersion": "0.3.7.dev42", "state": state,
+ }}
+ monkeypatch.setattr("nanobot.webui.settings_routes.check_for_update", lambda: result)
+ request = SimpleNamespace(path="/api/settings/version-check", headers=Headers())
+ router = _router()
+ response = await router.dispatch(None, request, request.path)
+ assert response.status_code == 409
+ request.path += "?channel_status=1"
+ response = await router.dispatch(None, request, "/api/settings/version-check")
+ assert response.status_code == 200
+ assert json.loads(response.body)["releaseStatus"] == result["releaseStatus"]
+ assert response.headers["Cache-Control"] == "no-store"
+
+
+async def test_version_check_owner_is_additive_read_only_and_failure_is_not_a_release_failure(monkeypatch):
+ from nanobot.webui import settings_system
+
+ result = {"updateAvailable": None, "releaseStatus": {"state": "current"}}
+ monkeypatch.setattr("nanobot.webui.settings_routes.check_for_update", lambda: result)
+ inspect_owner = MagicMock(return_value=SimpleNamespace(owner="pipx", records={}))
+ monkeypatch.setattr(settings_system, "inspect_update_installation", inspect_owner)
+ request = SimpleNamespace(path="/api/settings/version-check", headers=Headers())
+ router = _router()
+ legacy = await router.dispatch(None, request, "/api/settings/version-check")
+ assert json.loads(legacy.body) == {"updateAvailable": None}
+ inspect_owner.assert_not_called()
+ request.path += "?channel_status=1"
+ modern = await router.dispatch(None, request, "/api/settings/version-check")
+ assert json.loads(modern.body)["installation_method"] == "pipx"
+ inspect_owner.side_effect = ValueError("private receipt secret")
+ unavailable = await router.dispatch(None, request, "/api/settings/version-check")
+ body = json.loads(unavailable.body)
+ assert body["installation_method"] is None and body["releaseStatus"] == result["releaseStatus"]
+ assert "secret" not in unavailable.body.decode()
+
+
async def test_runtime_config_route_authentication_validation_and_restart(tmp_path):
from nanobot.config.loader import load_config
diff --git a/tests/webui/test_settings_services.py b/tests/webui/test_settings_services.py
index a356fa1b5..bc88c1537 100644
--- a/tests/webui/test_settings_services.py
+++ b/tests/webui/test_settings_services.py
@@ -19,6 +19,8 @@ from nanobot.webui.settings_services import (
class _Flow:
+ has_pending_work = False
+
def __init__(self, *, expired: bool = False) -> None:
self.expired = expired
self.cancel_count = 0
@@ -26,6 +28,12 @@ class _Flow:
def cancel(self) -> None:
self.cancel_count += 1
+ def wait_closed(self) -> None:
+ pass
+
+ def complete(self, response=None):
+ return None
+
def _gateway(config_path: Path, workspace: Path):
return build_gateway_services(
@@ -243,3 +251,87 @@ def test_oauth_registry_preserves_expiry_capacity_completion_and_cancel() -> Non
registry.clear("openai_codex")
assert replacement.cancel_count == 1
assert registry.get("openai_codex", "replacement") is None
+
+
+def test_oauth_registry_capacity_counts_cancelled_workers_until_exit():
+ release = threading.Event()
+ cancelled = threading.Event()
+
+ class ThreadFlow(_Flow):
+ def __init__(self):
+ super().__init__()
+ self.thread = threading.Thread(target=lambda: release.wait(3))
+
+ @property
+ def has_pending_work(self):
+ return self.thread.is_alive()
+
+ def cancel(self):
+ cancelled.set()
+
+ def wait_closed(self):
+ self.thread.join()
+
+ registry = WebUIOAuthFlowRegistry(max_flows=1)
+ flow = ThreadFlow()
+ registry.register("github_copilot", "first", flow)
+ flow.thread.start()
+ replacement = _Flow()
+ try:
+ with pytest.raises(RuntimeError, match="still stopping"):
+ registry.register("github_copilot", "next", replacement)
+ assert cancelled.is_set()
+ assert registry.get("github_copilot", "first") is None
+ assert registry.get("github_copilot", "next") is None
+ assert registry.has_pending_work
+ finally:
+ release.set()
+ flow.wait_closed()
+ assert not registry.has_pending_work
+ registry.register("github_copilot", "next", replacement)
+ registry.close()
+ with pytest.raises(RuntimeError, match="closing"):
+ registry.register("github_copilot", "after-close", _Flow())
+
+
+def test_oauth_registry_keeps_flow_that_starts_while_cancellation_is_pending():
+ cancelling, allow_cancel, release_worker = (threading.Event() for _ in range(3))
+
+ class StartingFlow(_Flow):
+ def __init__(self):
+ super().__init__()
+ self.thread = threading.Thread(target=lambda: release_worker.wait(3))
+
+ @property
+ def has_pending_work(self):
+ return self.thread.is_alive()
+
+ def cancel(self):
+ cancelling.set()
+ assert allow_cancel.wait(3)
+
+ def wait_closed(self):
+ if self.thread.ident is not None:
+ self.thread.join()
+
+ registry = WebUIOAuthFlowRegistry(max_flows=2)
+ flow = StartingFlow()
+ registry.register("github_copilot", "starting", flow)
+ removal = threading.Thread(target=lambda: registry.remove("github_copilot", "starting", flow))
+ removal.start()
+ try:
+ assert cancelling.wait(1)
+ # Another request can register between register/start in the first login,
+ # while its cancellation is waiting for the provider's commit lock.
+ registry.register("xai_grok", "another", _Flow())
+ flow.thread.start()
+ allow_cancel.set()
+ removal.join(timeout=1)
+ assert not removal.is_alive()
+ assert registry.has_pending_work
+ finally:
+ allow_cancel.set()
+ release_worker.set()
+ removal.join(timeout=2)
+ flow.wait_closed()
+ registry.close()
diff --git a/tests/webui/test_update_plans.py b/tests/webui/test_update_plans.py
new file mode 100644
index 000000000..817335784
--- /dev/null
+++ b/tests/webui/test_update_plans.py
@@ -0,0 +1,925 @@
+"""Authenticated, refresh-safe review and job reads; no installer or server process runs."""
+
+import asyncio
+import json
+import os
+import platform
+import subprocess
+import sys
+import threading
+import time
+from pathlib import Path
+from types import SimpleNamespace
+from uuid import uuid4
+
+import httpx
+import pytest
+from packaging.tags import Tag
+from websockets.datastructures import Headers
+from websockets.http11 import Request
+
+import nanobot
+from nanobot import update_plan, update_service
+from nanobot.bus.queue import MessageBus
+from nanobot.channels.websocket.runtime import WebSocketConfig
+from nanobot.config.home import get_selected_home_path, set_home_path
+from nanobot.installation_lock import (
+ InstallationBusyError,
+ file_access,
+ installation_access,
+ installation_state_dir,
+ pending_update_path,
+)
+from nanobot.release_feed import ReleaseFeed
+from nanobot.releases import release_filenames
+from nanobot.runtime_admission import RuntimeBusyError
+from nanobot.update_manager import ManagerPolicy
+from nanobot.update_plan import InstallationSnapshot, UpdatePlans
+from nanobot.update_process import PreparationProcess
+from nanobot.update_profiles import ObservedProfile, ProfileLaunch, ProfileReceipt
+from nanobot.update_worker import ExecutionConfirmation, JobStatus, Phase
+from nanobot.webui.client_contract import webui_contract
+from nanobot.webui.gateway_services import build_gateway_services
+
+CREATE = "/api/settings/nanobot-update/plan/create"
+READ = "/api/settings/nanobot-update/plan"
+JOB = "/api/settings/nanobot-update/job"
+PREPARE = "settings.nanobot.update.prepare"
+SETTLE = "settings.nanobot.update.settle"
+EXECUTE = "settings.nanobot.update.execute"
+RETRY = "settings.nanobot.update.retry"
+CHANNEL = "settings.nanobot.update.channel"
+
+
+async def test_channel_mutation_preserves_authority_and_invalidates_old_reviews(preparation_gateway):
+ from nanobot.update_channel import read_update_channel
+
+ fixture = preparation_gateway
+ gateway, plan = await preparation_plan(fixture)
+ # Plain HTTP cannot mutate; remote callers do not acquire install authority.
+ response = await fetch(gateway, "/api/settings/nanobot-update/channel")
+ assert response.status_code == 405
+ response = await gateway.http.dispatch_webui_mutation(connection(), CHANNEL, {"channel": "preview", "revision": 0})
+ assert response.status_code == 403
+ assert read_update_channel().revision == 0
+ response = await gateway.http.dispatch_webui_mutation(connection(local=True), CHANNEL, {"channel": "preview", "revision": 0})
+ assert response.status_code == 200, response.body
+ assert json.loads(response.body) == {"channel": "preview", "revision": 1}
+ assert "webui.update-channels.v1" in webui_contract()["capabilities"]
+ reviewed = await fetch(gateway, READ + "?id=" + plan.id)
+ assert json.loads(reviewed.body)["plan"]["validity"] == "channel_changed"
+ prepared = await gateway.http.dispatch_webui_mutation(connection(local=True), PREPARE, {"id": plan.id})
+ assert prepared.status_code == 409
+ assert not (fixture.directory / "jobs" / plan.id / "status.json").exists()
+ # Stale tabs cannot overwrite the newer selection; native uses its distributor.
+ assert (await gateway.http.dispatch_webui_mutation(connection(local=True), CHANNEL,
+ {"channel": "stable", "revision": 0})).status_code == 409
+ assert (await fixture.gateway("native").http.dispatch_webui_mutation(connection(local=True), CHANNEL,
+ {"channel": "stable", "revision": 1})).status_code == 409
+
+
[email protected]("payload", [{"channel": "preview"}, {"channel": "beta", "revision": 0},
+ {"channel": "preview", "revision": True},
+ {"channel": "preview", "revision": 0, "url": "https://other.example"}])
+async def test_channel_mutation_validates_untrusted_requests(preparation_gateway, payload):
+ gateway = preparation_gateway.gateway()
+ response = await gateway.http.dispatch_webui_mutation(connection(local=True), CHANNEL, payload)
+ assert response.status_code == 400
+
+
+async def test_review_uses_saved_channel_and_rejects_a_change_during_discovery(preparation_gateway, monkeypatch):
+ from nanobot.update_channel import UpdateChannelRequest
+
+ fixture = preparation_gateway
+ gateway, stable = await preparation_plan(fixture)
+ service = update_service.UpdateJobService()
+ service.change_channel(UpdateChannelRequest(channel="preview", revision=0))
+ observed = []
+ race = False
+
+ class Feed:
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *_):
+ pass
+
+ async def latest(self, channel):
+ observed.append(channel)
+ if race:
+ service.change_channel(UpdateChannelRequest(channel="stable", revision=1))
+ # Preview subscriptions can receive a final release too.
+ return stable.target
+
+ monkeypatch.setattr(update_plan, "ReleaseFeed", lambda _: Feed())
+ response = await gateway.http.dispatch_webui_mutation(connection(local=True), "settings.nanobot.update.plan", {"extras": []})
+ assert response.status_code == 200
+ saved = UpdatePlans(fixture.directory / "plans").load(json.loads(response.body)["plan"]["id"])
+ assert (saved.channel, saved.channel_revision) == ("preview", 1)
+ race = True
+ response = await gateway.http.dispatch_webui_mutation(connection(local=True), "settings.nanobot.update.plan", {"extras": []})
+ assert response.status_code == 409
+ assert observed == ["preview", "preview"]
+ assert not (fixture.directory / "jobs").exists()
+
+
+def review_gateway(tmp_path, monkeypatch):
+ account = tmp_path / "private account"
+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: account))
+ previous_home = get_selected_home_path()
+ set_home_path(tmp_path / "profile")
+ environment = tmp_path / "tool environment"
+ package = str(environment / "lib/nanobot/__init__.py")
+ snapshot = InstallationSnapshot(
+ environment=str(environment), python=str(environment / "bin/python"),
+ package_path=package, running_package=package, installed_version="0.3.4",
+ running_version="0.3.4", owner="uv", manager_version="0.11.16", records={"uv-receipt.toml": "a" * 64},
+ manager=ManagerPolicy(manager="uv", backend="uv", source="registry", extras=["webui"]),
+ )
+ observed = []
+ for number, state in enumerate(("running", "stopped")):
+ root = tmp_path / f"profile-{number}"
+ receipt = ProfileReceipt(
+ id=str(number + 1) * 64, run_id=uuid4().hex, environment=str(environment),
+ python=snapshot.python, package=package, version="0.3.4", home=str(root),
+ data_dir=str(root), config=str(root / "config.json"), workspace=str(root / "project"),
+ state_path=str(root / "run/gateway.json"), log_path=str(root / "log/gateway.log"),
+ port=19000 + number, launch_mode="background", pid=os.getpid() + 10000 + number,
+ process_identity=f"fixture-{number}", active=state == "running", stop_protocol=1,
+ launch=ProfileLaunch(home=str(root), config_path=None, workspace=None,
+ working_directory=str(root), verbose=False, lifetime="explicit"),
+ )
+ observed.append(ObservedProfile(receipt=receipt, state=state))
+ monkeypatch.setattr(update_plan, "inspect_installation", lambda: snapshot)
+ monkeypatch.setattr(update_plan, "inspect_profiles", lambda _: list(observed))
+ requests = []
+
+ def release(request):
+ requests.append(str(request.url))
+ assert request.url.path == "/pypi/nanobot-ai/json"
+ return httpx.Response(200, json={
+ "info": {"name": "nanobot-ai", "version": "0.3.5", "requires_python": ">=3.11"},
+ "urls": [{"filename": name, "size": 123, "digests": {"sha256": "b" * 64},
+ "url": f"https://files.pythonhosted.org/packages/{name}", "yanked": False}
+ for name in release_filenames("0.3.5") if name.endswith((".whl", ".tar.gz"))],
+ })
+
+ monkeypatch.setattr(update_plan, "ReleaseFeed", lambda directory: ReleaseFeed(
+ directory, transport=httpx.MockTransport(release), supported_tags=[Tag("py3", "none", "win_amd64")],
+ ))
+ def gateway(surface="gateway"):
+ return build_gateway_services(
+ config=WebSocketConfig(), bus=MessageBus(), session_manager=None,
+ static_dist_path=None, workspace_path=tmp_path / "workspace",
+ default_restrict_to_workspace=True, config_path=tmp_path / "config.json",
+ runtime_model_name=None, runtime_surface=surface, runtime_capabilities_overrides=None,
+ )
+
+ try:
+ yield SimpleNamespace(gateway=gateway, snapshot=snapshot, observed=observed,
+ requests=requests, directory=installation_state_dir(environment))
+ finally:
+ set_home_path(previous_home)
+
+
+def connection(*, local=False):
+ host = "127.0.0.1:8765" if local else "remote.example"
+ return SimpleNamespace(remote_address=("127.0.0.1" if local else "192.0.2.1", 12345),
+ request=Request("/ws", Headers({"Host": host, "Origin": f"http://{host}"})))
+
+
+async def fetch(gateway, path, *, authorized=True):
+ headers = Headers()
+ if authorized:
+ headers["Authorization"] = f"Bearer {gateway.tokens.issue_api_token(60)}"
+ return await gateway.http.dispatch(connection(), Request(path, headers))
+
+
+def preparation_gateway(review_gateway, monkeypatch):
+ fixture = review_gateway
+ snapshot = fixture.snapshot.model_copy(update={"owner": "venv", "manager": None})
+ monkeypatch.setattr(update_plan, "inspect_installation", lambda: snapshot)
+ monkeypatch.setattr(sys, "prefix", snapshot.environment)
+ fixture.snapshot = snapshot
+ return fixture
+
+
+async def preparation_plan(fixture):
+ gateway = fixture.gateway()
+ response = await gateway.http.dispatch_webui_mutation(
+ connection(local=True), "settings.nanobot.update.plan", {"extras": []},
+ )
+ assert response.status_code == 200, response.body
+ return gateway, UpdatePlans(fixture.directory / "plans").load(json.loads(response.body)["plan"]["id"])
+
+
+async def execution_plan(fixture):
+ gateway, original = await preparation_plan(fixture)
+ active = original.profiles[0].model_copy(update={"receipt": original.profiles[0].receipt.model_copy(
+ update={"pid": os.getpid()},
+ )})
+ plan = original.model_copy(update={"id": str(uuid4()), "profiles": [active, original.profiles[1]],
+ "stop_profiles": [active.receipt.id], "restart_profiles": [active.receipt.id]})
+ directory = fixture.directory / "jobs" / plan.id
+ directory.mkdir(parents=True)
+ (directory / "plan.json").write_text(plan.model_dump_json())
+ JobStatus(plan.id, Phase.READY, 0, False, "Staged routing fixture", int(time.time())).save(directory)
+ return gateway, plan, directory
+
+
+async def test_execution_consent_survives_cancelled_response_and_duplicate_requests(preparation_gateway, monkeypatch):
+ fixture = preparation_gateway
+ gateway, plan, directory = await execution_plan(fixture)
+ entered, release = threading.Event(), threading.Event()
+ launches = []
+ children = []
+ confirmation = ExecutionConfirmation(uuid4().hex, plan.id, "a" * 64, plan.created_at, plan.expires_at)
+
+ def launch(path, *, once):
+ assert path == directory and once
+ launches.append(plan.id)
+ confirmation.save(path)
+ JobStatus(plan.id, Phase.CHECKING, 0, False, "Controlled launch", int(time.time())).save(path)
+ entered.set()
+ assert release.wait(5)
+ child = subprocess.Popen([sys.executable, "-I", "-c", "import sys; sys.stdin.buffer.read()"],
+ stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+ children.append(child)
+ return child
+
+ monkeypatch.setattr(update_service, "start_handoff", launch)
+ payload = {"id": plan.id, "confirm_restart": True}
+ operation = asyncio.create_task(gateway.http.dispatch_webui_mutation(connection(local=True), EXECUTE, payload))
+ try:
+ async with asyncio.timeout(5):
+ while not entered.is_set():
+ await asyncio.sleep(0.001)
+ operation.cancel()
+ await asyncio.sleep(0)
+ assert not operation.done(), "A lost requester cannot abandon a still-running launch thread"
+ fresh = fixture.gateway()
+ duplicate = await fresh.http.dispatch_webui_mutation(connection(local=True), EXECUTE, payload)
+ assert duplicate.status_code == 200, duplicate.body
+ assert duplicate.headers["Cache-Control"] == "no-store"
+ saved = json.loads(duplicate.body)["job"]
+ assert saved["execution_confirmation_id"] == confirmation.id
+ assert saved["recorded_phase"] == "checking" and not saved["mutation_started"]
+ restored = await fetch(fresh, JOB + "?id=" + plan.id)
+ assert json.loads(restored.body)["job"] == saved
+ finally:
+ release.set()
+ try:
+ with pytest.raises(asyncio.CancelledError):
+ await operation
+ assert gateway.http.settings_routes._system._update_jobs._reapers
+ await asyncio.wait_for(gateway.http.settings_routes.close(), 5)
+ assert children[0].poll() is None, "Gateway shutdown must not wait for its independent updater"
+ finally:
+ for child in children:
+ child.stdin.close()
+ assert await asyncio.to_thread(child.wait, 5) == 0
+ assert launches == [plan.id]
+ assert "webui.update-jobs.execute.v1" in webui_contract()["capabilities"]
+
+
+async def test_execution_requires_explicit_restart_and_existing_install_authority(preparation_gateway, monkeypatch):
+ fixture = preparation_gateway
+ gateway, plan, directory = await execution_plan(fixture)
+
+ def forbidden(*args, **kwargs):
+ pytest.fail("Unconfirmed or unauthorized requests cannot launch an updater")
+
+ monkeypatch.setattr(update_service, "start_handoff", forbidden)
+ assert (await fetch(gateway, JOB + "/execute")).status_code == 405
+ payload = {"id": plan.id, "confirm_restart": True}
+ assert (await gateway.http.dispatch_webui_mutation(connection(), EXECUTE, payload)).status_code == 403
+ assert (await fixture.gateway("native").http.dispatch_webui_mutation(connection(local=True), EXECUTE, payload)).status_code == 409
+ for bad in ({"id": plan.id}, {"id": plan.id, "confirm_restart": False},
+ {"id": plan.id, "confirm_restart": "true"}, {"id": plan.id, "confirm_restart": 1},
+ {**payload, "repair": True}, {**payload, "command": "pip install"}):
+ result = await gateway.http.dispatch_webui_mutation(connection(local=True), EXECUTE, bad)
+ assert result.status_code == 400
+ assert ExecutionConfirmation.read(directory) is None
+
+
+async def test_retry_is_explicit_authorized_and_old_submissions_only_read_history(preparation_gateway, monkeypatch):
+ fixture = preparation_gateway
+ gateway, plan, directory = await execution_plan(fixture)
+ previous = ExecutionConfirmation(uuid4().hex, plan.id, "a" * 64, plan.created_at, plan.expires_at)
+ current = ExecutionConfirmation(uuid4().hex, plan.id, "a" * 64, plan.created_at, plan.expires_at)
+ previous.save(directory)
+ JobStatus(plan.id, Phase.HANDOFF_FAILED, 0, False, "Stopped before mutation", int(time.time())).save(directory)
+ calls = []
+
+ def retry(path, previous_id):
+ assert path == directory and previous_id == previous.id
+ calls.append(previous_id)
+ current.save(path)
+ JobStatus(plan.id, Phase.CHECKING, 0, False, "Retry confirmed", int(time.time())).save(path)
+ return None
+
+ monkeypatch.setattr(update_service, "retry_handoff", retry)
+ payload = {"id": plan.id, "previous_confirmation_id": previous.id, "confirm_restart": True}
+ assert (await fetch(gateway, JOB + "/retry")).status_code == 405
+ assert (await gateway.http.dispatch_webui_mutation(connection(), RETRY, payload)).status_code == 403
+ assert (await fixture.gateway("native").http.dispatch_webui_mutation(connection(local=True), RETRY, payload)).status_code == 409
+ for bad in ({"id": plan.id, "confirm_restart": True}, {**payload, "confirm_restart": False},
+ {**payload, "previous_confirmation_id": "bad-id"}, {**payload, "repair": True},
+ {**payload, "confirm_restart": "true"}):
+ assert (await gateway.http.dispatch_webui_mutation(connection(local=True), RETRY, bad)).status_code == 400
+ assert not calls
+ first = await gateway.http.dispatch_webui_mutation(connection(local=True), RETRY, payload)
+ assert first.status_code == 200, first.body
+ assert first.headers["Cache-Control"] == "no-store"
+ assert json.loads(first.body)["job"]["execution_confirmation_id"] == current.id
+ fresh = fixture.gateway()
+ for action, body in ((RETRY, payload), (EXECUTE, {"id": plan.id, "confirm_restart": True})):
+ repeated = await fresh.http.dispatch_webui_mutation(connection(local=True), action, body)
+ assert repeated.status_code == 200 and json.loads(repeated.body) == json.loads(first.body)
+ assert calls == [previous.id]
+ assert "webui.update-jobs.retry-handoff.v1" in webui_contract()["capabilities"]
+
+
+async def test_busy_retry_does_not_look_like_an_accepted_new_confirmation(preparation_gateway, monkeypatch):
+ gateway, plan, directory = await execution_plan(preparation_gateway)
+ previous = ExecutionConfirmation(uuid4().hex, plan.id, "a" * 64, plan.created_at, plan.expires_at)
+ previous.save(directory)
+
+ def busy(*args):
+ raise BlockingIOError("private lease path must not reach the response")
+
+ monkeypatch.setattr(update_service, "retry_handoff", busy)
+ response = await gateway.http.dispatch_webui_mutation(connection(local=True), RETRY,
+ {"id": plan.id, "previous_confirmation_id": previous.id, "confirm_restart": True})
+ assert response.status_code == 409
+ assert b"private lease" not in response.body
+ assert ExecutionConfirmation.read(directory) == previous
+
+
+async def test_handoff_settlement_route_preserves_permission_and_reads_cancelled_job(preparation_gateway, monkeypatch):
+ from nanobot import update_stop
+
+ gateway, plan, directory = await execution_plan(preparation_gateway)
+ previous = ExecutionConfirmation(uuid4().hex, plan.id, "a" * 64, plan.created_at, plan.expires_at)
+ previous.save(directory)
+ JobStatus(plan.id, Phase.HANDOFF_FAILED, 0, False, "Refused shutdown", plan.created_at).save(directory)
+ calls = []
+
+ def settle(path):
+ calls.append(path)
+ assert path == directory
+ state = JobStatus(plan.id, Phase.CANCELLED, 0, False, "Settled fixture", plan.created_at)
+ state.save(path)
+ return state
+
+ monkeypatch.setattr(update_stop, "settle_uncommitted_handoff", settle)
+ assert (await gateway.http.dispatch_webui_mutation(connection(), SETTLE, {"id": plan.id})).status_code == 403
+ assert calls == []
+ response = await gateway.http.dispatch_webui_mutation(connection(local=True), SETTLE, {"id": plan.id})
+ assert response.status_code == 200, response.body
+ assert json.loads(response.body)["job"]["recorded_phase"] == "cancelled"
+ assert json.loads(response.body)["job"]["execution_confirmation_id"] == previous.id
+ assert (await fetch(gateway, JOB + "?id=" + plan.id)).body == response.body
+ assert calls == [directory]
+ assert "webui.update-jobs.settle-handoff.v1" in webui_contract()["capabilities"]
+
+
[email protected]("problem", ["self_not_selected", "peer_not_selected", "no_restart"])
+async def test_execution_refuses_unreviewed_gateway_lifecycle(preparation_gateway, monkeypatch, problem):
+ fixture = preparation_gateway
+ gateway, plan, directory = await execution_plan(fixture)
+ changes = {}
+ if problem == "self_not_selected":
+ changes["profiles"] = [plan.profiles[0].model_copy(update={"receipt": plan.profiles[0].receipt.model_copy(
+ update={"pid": os.getpid() + 10000},
+ )}), plan.profiles[1]]
+ elif problem == "peer_not_selected":
+ changes["profiles"] = [plan.profiles[0], plan.profiles[1].model_copy(update={"state": "running"})]
+ else:
+ changes["restart_profiles"] = []
+ (directory / "plan.json").write_text(plan.model_copy(update=changes).model_dump_json())
+
+ def forbidden(*args, **kwargs):
+ pytest.fail("Unsupported lifecycle cannot launch an updater")
+
+ monkeypatch.setattr(update_service, "start_handoff", forbidden)
+ result = await gateway.http.dispatch_webui_mutation(connection(local=True), EXECUTE,
+ {"id": plan.id, "confirm_restart": True})
+ assert result.status_code == 409, result.body
+ assert ExecutionConfirmation.read(directory) is None
+
+
+async def test_preparation_is_durable_idempotent_and_independent_of_browser(preparation_gateway, monkeypatch):
+ fixture = preparation_gateway
+ gateway, plan = await preparation_plan(fixture)
+ entered, release = asyncio.Event(), asyncio.Event()
+ validated, prepared = [], []
+
+ async def revalidate(self, target):
+ validated.append(target)
+
+ async def stage(exact, feed):
+ prepared.append(exact)
+ directory = fixture.directory / "jobs" / exact.id
+ JobStatus(exact.id, Phase.PREPARING, 0, False, "Preparing", int(time.time())).save(directory)
+ entered.set()
+ await release.wait()
+ JobStatus(exact.id, Phase.READY, 0, False, "Staged fixture", int(time.time())).save(directory)
+ return directory
+
+ monkeypatch.setattr(update_service.ReleaseFeed, "revalidate", revalidate)
+ monkeypatch.setattr(update_service, "prepare_job", stage)
+ close = None
+ try:
+ response = await gateway.http.dispatch_webui_mutation(connection(local=True), PREPARE, {"id": plan.id})
+ assert response.status_code == 200, response.body
+ assert json.loads(response.body)["job"]["recorded_phase"] == "preparation_requested"
+ assert response.headers["Cache-Control"] == "no-store"
+ directory = fixture.directory / "jobs" / plan.id
+ assert JobStatus.read(directory).phase == Phase.PREPARATION_REQUESTED
+ await asyncio.wait_for(entered.wait(), 5)
+ # A recreated router has no reference to the original browser's task.
+ fresh = fixture.gateway()
+ duplicate = await fresh.http.dispatch_webui_mutation(connection(local=True), PREPARE, {"id": plan.id})
+ assert duplicate.status_code == 200
+ assert json.loads(duplicate.body)["job"]["recorded_phase"] == "preparing"
+ assert (await fetch(fresh, JOB + "?id=" + plan.id)).status_code == 200
+ assert (await fresh.http.dispatch_webui_mutation(connection(local=True), SETTLE, {"id": plan.id})).status_code == 409
+ other = plan.model_copy(update={"id": str(uuid4())})
+ UpdatePlans(fixture.directory / "plans").save(other)
+ busy = await fresh.http.dispatch_webui_mutation(connection(local=True), PREPARE, {"id": other.id})
+ assert busy.status_code == 409
+ assert not (fixture.directory / "jobs" / other.id).exists()
+ with pytest.raises(RuntimeBusyError):
+ with gateway.http.settings_routes._system._admission.pause_if_idle(lambda: False):
+ pytest.fail("Preparation must be counted as runtime work")
+ close = asyncio.create_task(gateway.http.settings_routes.close())
+ async with asyncio.timeout(5):
+ while not gateway.http.settings_routes._system._update_jobs._closing:
+ await asyncio.sleep(0.001)
+ close.cancel()
+ await asyncio.sleep(0)
+ assert not close.done(), "Shutdown cancellation must not release a running preparation"
+ with pytest.raises(InstallationBusyError):
+ with installation_access(updating=True):
+ pytest.fail("Preparation lost its shared installation lease")
+ finally:
+ release.set()
+ if close is not None:
+ await asyncio.wait_for(close, 5)
+ else:
+ await gateway.http.settings_routes.close()
+ final = await fetch(fixture.gateway(), JOB + "?id=" + plan.id)
+ assert json.loads(final.body)["job"]["recorded_phase"] == "ready"
+ assert validated == [plan.target] and prepared == [plan]
+ assert len(fixture.requests) == 1, "The staging controller must not reselect latest"
+ for name in ("approval.json", "handoff-approval.json"):
+ assert not (directory / name).exists()
+ assert not (fixture.directory / "stop.json").exists()
+ assert "webui.update-jobs.prepare.v1" in webui_contract()["capabilities"]
+
+
+async def test_preparation_revalidation_failure_is_saved_and_never_retried_by_refresh(preparation_gateway, monkeypatch):
+ fixture = preparation_gateway
+ gateway, plan = await preparation_plan(fixture)
+ targets = []
+
+ async def withdrawn(self, target):
+ targets.append(target)
+ raise ValueError("private-index-user:secret")
+
+ async def forbidden(*args):
+ pytest.fail("A withdrawn target must not reach staging")
+
+ monkeypatch.setattr(update_service.ReleaseFeed, "revalidate", withdrawn)
+ monkeypatch.setattr(update_service, "prepare_job", forbidden)
+ accepted = await gateway.http.dispatch_webui_mutation(connection(local=True), PREPARE, {"id": plan.id})
+ assert accepted.status_code == 200
+ await gateway.http.settings_routes.close()
+ duplicate = await fixture.gateway().http.dispatch_webui_mutation(connection(local=True), PREPARE, {"id": plan.id})
+ assert duplicate.status_code == 200
+ assert json.loads(duplicate.body)["job"]["recorded_phase"] == "preparation_failed"
+ assert b"secret" not in duplicate.body
+ directory = fixture.directory / "jobs" / plan.id
+ assert "secret" not in (directory / "status.json").read_text()
+ assert targets == [plan.target]
+ assert not (directory / "request.json").exists()
+
+
[email protected]("operation", [PREPARE, SETTLE])
+async def test_preparation_mutations_require_authority_and_exact_id(preparation_gateway, operation):
+ fixture = preparation_gateway
+ gateway, plan = await preparation_plan(fixture)
+ path = JOB + ("/prepare" if operation == PREPARE else "/settle")
+ assert (await fetch(gateway, path)).status_code == 405
+ remote = await gateway.http.dispatch_webui_mutation(connection(), operation, {"id": plan.id})
+ assert remote.status_code == 403
+ desktop = await fixture.gateway("native").http.dispatch_webui_mutation(connection(local=True), operation, {"id": plan.id})
+ assert desktop.status_code == 409
+ for payload in ({}, {"id": "../plan"}, {"id": 12}, {"id": plan.id, "target": "new-version"},
+ {"id": plan.id, "repair": True}):
+ response = await gateway.http.dispatch_webui_mutation(connection(local=True), operation, payload)
+ assert response.status_code == 400
+ assert not (fixture.directory / "jobs").exists()
+
+
[email protected]("problem", ["expired", "source", "unknown_extras", "foreign"])
+async def test_preparation_rejects_unexecutable_reviews_before_creating_work(preparation_gateway, problem):
+ fixture = preparation_gateway
+ gateway, plan = await preparation_plan(fixture)
+ changes = {"id": str(uuid4())}
+ if problem == "expired":
+ changes.update(created_at=plan.created_at - 1800, expires_at=plan.expires_at - 1800)
+ elif problem == "source":
+ changes["installation"] = plan.installation.model_copy(update={"owner": "source"})
+ elif problem == "unknown_extras":
+ changes["extras"] = None
+ else:
+ changes["installation"] = plan.installation.model_copy(update={"environment": str(fixture.directory / "foreign")})
+ invalid = plan.model_copy(update=changes)
+ UpdatePlans(fixture.directory / "plans").save(invalid)
+ response = await gateway.http.dispatch_webui_mutation(connection(local=True), PREPARE, {"id": invalid.id})
+ assert response.status_code == 409
+ assert not (fixture.directory / "jobs").exists()
+
+
[email protected]("phase", [Phase.PREPARATION_REQUESTED, Phase.PREPARING])
+async def test_explicit_settlement_checks_ownership_and_does_not_retry(preparation_gateway, monkeypatch, phase):
+ fixture = preparation_gateway
+ gateway, plan = await preparation_plan(fixture)
+ directory = fixture.directory / "jobs" / plan.id
+ directory.mkdir(parents=True)
+ (directory / "plan.json").write_text(plan.model_dump_json())
+ JobStatus(plan.id, phase, 0, False, "Interrupted fixture", int(time.time())).save(directory)
+ if phase == Phase.PREPARING:
+ PreparationProcess.create(directory, plan.installation.environment)
+
+ async def forbidden(*args):
+ pytest.fail("Reading or settling interrupted staging cannot restart it")
+
+ monkeypatch.setattr(update_service.ReleaseFeed, "revalidate", forbidden)
+ restored = await gateway.http.dispatch_webui_mutation(connection(local=True), PREPARE, {"id": plan.id})
+ assert json.loads(restored.body)["job"]["recorded_phase"] == phase.value
+ lock = "prepare-native.lock" if phase == Phase.PREPARING else "preparation-controller.lock"
+ with file_access(fixture.directory / lock, exclusive=True):
+ blocked = await gateway.http.dispatch_webui_mutation(connection(local=True), SETTLE, {"id": plan.id})
+ assert blocked.status_code == 409
+ assert JobStatus.read(directory).phase == phase
+ settled = await gateway.http.dispatch_webui_mutation(connection(local=True), SETTLE, {"id": plan.id})
+ assert settled.status_code == 200, settled.body
+ assert json.loads(settled.body)["job"]["recorded_phase"] == "preparation_failed"
+ if phase == Phase.PREPARING:
+ assert PreparationProcess.load(directory).active is False
+ assert not (directory / "request.json").exists()
+ duplicate = await fixture.gateway().http.dispatch_webui_mutation(connection(local=True), PREPARE, {"id": plan.id})
+ assert json.loads(duplicate.body)["job"]["recorded_phase"] == "preparation_failed"
+
+
+async def test_exact_review_survives_router_recreation_without_reselection_or_install(review_gateway):
+ fixture = review_gateway
+ gateway = fixture.gateway()
+ denied = await fetch(gateway, READ + "?id=" + str(uuid4()), authorized=False)
+ assert denied.status_code == 401
+ denied = await fetch(gateway, CREATE)
+ assert denied.status_code == 405
+ response = await gateway.http.dispatch_webui_mutation(
+ connection(), "settings.nanobot.update.plan", {"channel": "stable", "restart_running": True},
+ )
+ assert response.status_code == 200, response.body
+ assert response.headers["Cache-Control"] == "no-store"
+ payload = json.loads(response.body)
+ review = payload["plan"]
+ assert payload["installation_allowed"] is False
+ assert payload["execution_available"] is False
+ assert (review["running_version"], review["target_version"], review["owner"]) == ("0.3.4", "0.3.5", "uv")
+ assert review["extras"] == ["webui"] and review["validity"] == "current"
+ assert review["guide"]["method"] == "uv"
+ assert review["guide"]["host"] == review["host"]
+ assert review["guide"]["environment"] == fixture.snapshot.environment
+ assert [(item["reviewed_state"], item["stop"], item["restart"]) for item in review["profiles"]] == [
+ ("running", True, True), ("stopped", False, False),
+ ]
+ assert {"records", "manager", "python", "url", "target"}.isdisjoint(review)
+ saved = UpdatePlans(fixture.directory / "plans").load(review["id"])
+ assert saved.stop_profiles == saved.restart_profiles == [fixture.observed[0].receipt.id]
+ assert not (fixture.directory / "jobs").exists()
+ assert not (fixture.directory / "stop.json").exists()
+ assert fixture.requests == ["https://pypi.org/pypi/nanobot-ai/json"]
+
+ fresh_gateway = fixture.gateway()
+ restored = await fetch(fresh_gateway, READ + "?id=" + review["id"])
+ assert restored.headers["Cache-Control"] == "no-store"
+ assert json.loads(restored.body) == payload
+ assert len(fixture.requests) == 1, "Reading an existing review must not resolve a different latest target"
+ assert "webui.update-plans.v1" in webui_contract()["capabilities"]
+
+
+async def test_live_update_review_requires_this_gateway_and_preserves_owner_policy(review_gateway):
+ fixture = review_gateway
+ running = fixture.observed[0]
+ fixture.observed[0] = running.model_copy(update={"receipt": running.receipt.model_copy(update={"pid": os.getpid()})})
+ gateway = fixture.gateway()
+ response = await gateway.http.dispatch_webui_mutation(
+ connection(local=True), "settings.nanobot.update.plan", {"restart_running": True},
+ )
+ payload = json.loads(response.body)
+ assert payload["installation_allowed"] is True
+ assert payload["execution_available"] is (os.name == "posix")
+ assert payload["plan"]["extras"] == ["webui"]
+ plan = UpdatePlans(fixture.directory / "plans").load(payload["plan"]["id"])
+ assert update_plan.inline_update_blocked_reason(plan, "expired") == "review_changed"
+ assert update_plan.inline_update_blocked_reason(plan.model_copy(update={"restart_profiles": []})) == (
+ "external_restart" if os.name == "posix" else "installation_owner"
+ )
+ assert not (fixture.directory / "jobs").exists(), "Review must not prepare or install"
+
+
[email protected]("manager_version", [None, "0.11.15", "0.11.17"])
+async def test_review_routes_unverified_uv_versions_to_the_installation_owner(review_gateway, monkeypatch, manager_version):
+ fixture = review_gateway
+ snapshot = fixture.snapshot.model_copy(update={"manager_version": manager_version})
+ monkeypatch.setattr(update_plan, "inspect_installation", lambda: snapshot)
+ running = fixture.observed[0]
+ fixture.observed[0] = running.model_copy(update={"receipt": running.receipt.model_copy(update={"pid": os.getpid()})})
+ response = await fixture.gateway().http.dispatch_webui_mutation(
+ connection(local=True), "settings.nanobot.update.plan", {"restart_running": True},
+ )
+ assert response.status_code == 200
+ payload = json.loads(response.body)
+ assert payload["execution_available"] is False
+ plan = UpdatePlans(fixture.directory / "plans").load(payload["plan"]["id"])
+ assert update_plan.inline_update_blocked_reason(plan) == "installation_owner"
+ assert not (fixture.directory / "jobs").exists()
+
+
+async def test_review_reports_profile_and_installation_changes_without_replacing_plan(review_gateway, monkeypatch):
+ fixture = review_gateway
+ gateway = fixture.gateway()
+ created = await gateway.http.dispatch_webui_mutation(connection(local=True), "settings.nanobot.update.plan", {})
+ assert created.status_code == 200
+ payload = json.loads(created.body)
+ assert payload["installation_allowed"] is True
+ review = payload["plan"]
+ assert not any(item["stop"] or item["restart"] for item in review["profiles"])
+ saved_bytes = (fixture.directory / "plans" / f"{review['id']}.json").read_bytes()
+ fixture.observed[0] = fixture.observed[0].model_copy(update={
+ "receipt": fixture.observed[0].receipt.model_copy(update={"run_id": uuid4().hex}),
+ })
+ response = await fetch(gateway, READ + "?id=" + review["id"])
+ assert json.loads(response.body)["plan"]["validity"] == "profiles_changed"
+ monkeypatch.setattr(update_plan, "inspect_installation", lambda: fixture.snapshot.model_copy(update={
+ "installed_version": "0.3.5", "records": {"uv-receipt.toml": "c" * 64},
+ }))
+ response = await fetch(gateway, READ + "?id=" + review["id"])
+ changed = json.loads(response.body)["plan"]
+ assert changed["validity"] == "installation_changed"
+ assert changed["installed_version"] == "0.3.5"
+ assert (fixture.directory / "plans" / f"{review['id']}.json").read_bytes() == saved_bytes
+
+
[email protected]("payload", [
+ {"channel": "dev"}, {"restart_running": "true"}, {"extras": ["--index-url"]},
+ {"target": "https://untrusted.example/wheel"}, {"installation": "/another/tool"},
+])
+async def test_invalid_client_request_cannot_select_code_or_environment(review_gateway, payload):
+ fixture = review_gateway
+ response = await fixture.gateway().http.dispatch_webui_mutation(
+ connection(), "settings.nanobot.update.plan", payload,
+ )
+ assert response.status_code == 400
+ assert fixture.requests == []
+ assert not (fixture.directory / "plans").exists()
+
+
+async def test_expired_unknown_and_foreign_plans_have_explicit_results(review_gateway, monkeypatch):
+ fixture = review_gateway
+ gateway = fixture.gateway()
+ response = await gateway.http.dispatch_webui_mutation(connection(), "settings.nanobot.update.plan", {})
+ review = json.loads(response.body)["plan"]
+ now = time.time()
+ monkeypatch.setattr(update_plan.time, "time", lambda: now + 901)
+ response = await fetch(gateway, READ + "?id=" + review["id"])
+ assert json.loads(response.body)["plan"]["validity"] == "expired"
+ missing = await fetch(gateway, READ + "?id=" + str(uuid4()))
+ assert missing.status_code == 404
+ traversal = await fetch(gateway, READ + "?id=../../config")
+ assert traversal.status_code == 400
+ other = fixture.snapshot.model_copy(update={"environment": str(fixture.directory / "other")})
+ monkeypatch.setattr(update_plan, "inspect_installation", lambda: other)
+ missing = await fetch(gateway, READ + "?id=" + review["id"])
+ assert missing.status_code == 404
+
+
+async def test_desktop_and_failed_discovery_do_not_claim_executable_or_current(review_gateway, monkeypatch):
+ fixture = review_gateway
+ desktop = await fixture.gateway("native").http.dispatch_webui_mutation(
+ connection(), "settings.nanobot.update.plan", {},
+ )
+ assert desktop.status_code == 409 and fixture.requests == []
+
+ def failed_probe():
+ raise ValueError("https://user:[email protected]/private")
+
+ monkeypatch.setattr(update_plan, "inspect_installation", failed_probe)
+ failed = await fixture.gateway().http.dispatch_webui_mutation(connection(), "settings.nanobot.update.plan", {})
+ assert failed.status_code == 409
+ assert b"secret" not in failed.body
+ assert not (fixture.directory / "plans").exists()
+
+
+async def test_environment_replaced_during_discovery_does_not_return_a_valid_review(review_gateway, monkeypatch):
+ fixture = review_gateway
+ calls = 0
+
+ def changed_probe():
+ nonlocal calls
+ calls += 1
+ if calls == 1:
+ return fixture.snapshot
+ return fixture.snapshot.model_copy(update={"installed_version": "0.3.6"})
+
+ monkeypatch.setattr(update_plan, "inspect_installation", changed_probe)
+ response = await fixture.gateway().http.dispatch_webui_mutation(
+ connection(), "settings.nanobot.update.plan", {},
+ )
+ assert response.status_code == 409
+ assert response.body == b"Could not verify an update plan for this installation. No update was started."
+ assert calls == 2
+ assert not (fixture.directory / "jobs").exists()
+
+
+async def test_missing_interpreter_is_not_misreported_as_a_missing_plan(review_gateway, monkeypatch):
+ fixture = review_gateway
+ gateway = fixture.gateway()
+ response = await gateway.http.dispatch_webui_mutation(connection(), "settings.nanobot.update.plan", {})
+ plan_id = json.loads(response.body)["plan"]["id"]
+
+ def removed_python():
+ raise FileNotFoundError("/private/installation/bin/python")
+
+ monkeypatch.setattr(update_plan, "inspect_installation", removed_python)
+ failed = await fetch(gateway, READ + "?id=" + plan_id)
+ assert failed.status_code == 409
+ assert b"/private/installation" not in failed.body
+ assert (fixture.directory / "plans" / f"{plan_id}.json").exists()
+
+
+async def test_job_reads_survive_refresh_expiry_and_unavailable_installation(review_gateway, monkeypatch):
+ fixture = review_gateway
+ gateway = fixture.gateway()
+ response = await gateway.http.dispatch_webui_mutation(connection(), "settings.nanobot.update.plan", {})
+ plan_id = json.loads(response.body)["plan"]["id"]
+ plan = UpdatePlans(fixture.directory / "plans").load(plan_id)
+ directory = fixture.directory / "jobs" / plan_id
+ directory.mkdir(parents=True)
+ (directory / "plan.json").write_text(plan.model_dump_json())
+ JobStatus(plan_id, Phase.PREPARING, 0, False, "private diagnostic", plan.created_at).save(directory)
+ monkeypatch.setattr(sys, "prefix", fixture.snapshot.environment)
+
+ def unavailable_probe():
+ pytest.fail("Reading a saved job must not launch the changing installation")
+
+ monkeypatch.setattr(update_plan, "inspect_installation", unavailable_probe)
+ response = await fetch(gateway, JOB + "?id=" + plan_id, authorized=False)
+ assert response.status_code == 401
+ response = await fetch(gateway, JOB + "?id=" + plan_id)
+ assert response.status_code == 200
+ job = json.loads(response.body)["job"]
+ recovery = job.pop("recovery_command")
+ assert plan.id in recovery and recovery.endswith(" --repair")
+ assert "recover.py" in recovery
+ assert job == {
+ "id": plan_id, "installation_id": fixture.snapshot.installation_id,
+ "host": platform.node(), "previous_version": "0.3.4",
+ "target_version": "0.3.5", "channel": "stable", "recorded_phase": "preparing",
+ "attempt": 0, "mutation_started": False, "updated_at": plan.created_at,
+ "execution_confirmation_id": None,
+ "running_version": nanobot.__version__,
+ "recovery_active": False,
+ "service_restored": False,
+ "automatic_recovery": False,
+ }
+ assert not (directory / "request.json").exists(), "An early journal must not require committed staging"
+ assert "webui.update-jobs.read.v1" in webui_contract()["capabilities"]
+
+ # A journal is recoverable without revalidating the expired plan or reading
+ # package metadata; it is not permission to retry or proof a worker is live.
+ monkeypatch.setattr(update_plan.time, "time", lambda: plan.expires_at + 1)
+ JobStatus(plan_id, Phase.FAILED, 1, True, "https://user:[email protected]", plan.expires_at).save(directory)
+ pending = pending_update_path()
+ pending.parent.mkdir(parents=True)
+ pending.write_text("interrupted update")
+ with installation_access(updating=True):
+ response = await fetch(fixture.gateway(), JOB + "?id=" + plan_id)
+ assert response.status_code == 200
+ assert response.headers["Cache-Control"] == "no-store"
+ job = json.loads(response.body)["job"]
+ assert job["recorded_phase"] == "failed" and job["mutation_started"] is True
+ assert job["attempt"] == 1 and job["updated_at"] == plan.expires_at
+ assert b"secret" not in response.body
+ # Only the explicit recovery command exposes the launcher's exact location;
+ # job diagnostics and profile paths must remain out of the status payload.
+ assert job.pop("recovery_command") == recovery
+ assert "private account" not in json.dumps(job)
+ assert {"message", "running", "can_retry", "python", "url", "profiles"}.isdisjoint(job)
+ assert len(fixture.requests) == 1
+ assert not (directory / "approval.json").exists()
+
+ # A completed program restoration is not a successful installation. Keep
+ # the legacy wire phase readable while exposing the precise new result.
+ JobStatus(plan_id, Phase.RESTORED, 2, True, "Private recovery detail", plan.expires_at).save(directory)
+ response = await fetch(fixture.gateway(), JOB + "?id=" + plan_id)
+ job = json.loads(response.body)["job"]
+ assert job["recorded_phase"] == "failed" and job["service_restored"] is True
+ assert b"Private recovery detail" not in response.body
+
+
+async def test_job_reads_reject_missing_foreign_and_corrupt_records(review_gateway, monkeypatch):
+ fixture = review_gateway
+ gateway = fixture.gateway()
+ response = await gateway.http.dispatch_webui_mutation(connection(), "settings.nanobot.update.plan", {})
+ plan_id = json.loads(response.body)["plan"]["id"]
+ plan = UpdatePlans(fixture.directory / "plans").load(plan_id)
+ monkeypatch.setattr(sys, "prefix", fixture.snapshot.environment)
+ for query in ("", "?id=../../config", "?id=not-a-uuid"):
+ assert (await fetch(gateway, JOB + query)).status_code == 400
+ assert (await fetch(gateway, JOB + "?id=" + plan_id)).status_code == 404
+ directory = fixture.directory / "jobs" / plan_id
+ directory.mkdir(parents=True)
+ (directory / "plan.json").write_text(plan.model_dump_json())
+ (directory / "status.json").write_text('{"private":"secret"}')
+ response = await fetch(gateway, JOB + "?id=" + plan_id)
+ assert response.status_code == 409 and b"secret" not in response.body
+ assert response.headers["Cache-Control"] == "no-store"
+ JobStatus(plan_id, Phase.READY, 0, False, "Prepared", plan.created_at).save(directory)
+ foreign = plan.model_copy(update={"installation": fixture.snapshot.model_copy(
+ update={"environment": str(fixture.directory / "another installation")},
+ )})
+ (directory / "plan.json").write_text(foreign.model_dump_json())
+ assert (await fetch(gateway, JOB + "?id=" + plan_id)).status_code == 409
+ (directory / "plan.json").write_text(plan.model_dump_json())
+ assert (await fetch(fixture.gateway("native"), JOB + "?id=" + plan_id)).status_code == 409
+ monkeypatch.setattr(sys, "prefix", str(fixture.directory / "another installation"))
+ assert (await fetch(gateway, JOB + "?id=" + plan_id)).status_code == 404
+
+
[email protected]("reading", [False, True])
+async def test_cancelled_request_keeps_probe_lease_until_native_work_exits(review_gateway, monkeypatch, reading):
+ fixture = review_gateway
+ entered, release = threading.Event(), threading.Event()
+
+ def native_probe():
+ entered.set()
+ assert release.wait(5), "The test did not settle its native probe"
+ return fixture.snapshot
+
+ monkeypatch.setattr(update_plan, "inspect_installation", native_probe)
+ task = asyncio.create_task(update_plan.read_release_plan(str(uuid4())) if reading
+ else update_plan.preview_release_update("stable"))
+ try:
+ assert await asyncio.to_thread(entered.wait, 5)
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ with pytest.raises(InstallationBusyError):
+ with installation_access(updating=True):
+ pytest.fail("Native inspection outlived its installation lease")
+ assert fixture.requests == []
+ finally:
+ release.set()
+ # Wait for the probe's actual lease release before restoring Path.home.
+ async with asyncio.timeout(5):
+ while True:
+ try:
+ with installation_access(updating=True):
+ break
+ except InstallationBusyError:
+ await asyncio.sleep(0.01)
+
+
[email protected]("problem", ["unknown", "supervisor", "extras"])
+async def test_plan_cannot_invent_restart_ownership_or_replace_manager_extras(review_gateway, problem):
+ fixture = review_gateway
+ payload = {"restart_running": True}
+ if problem == "unknown":
+ fixture.observed[0] = fixture.observed[0].model_copy(update={"state": "unconfirmed"})
+ elif problem == "supervisor":
+ fixture.observed[0] = fixture.observed[0].model_copy(update={
+ "receipt": fixture.observed[0].receipt.model_copy(update={"launch_mode": "foreground"}),
+ })
+ else:
+ payload["extras"] = []
+ response = await fixture.gateway().http.dispatch_webui_mutation(connection(), "settings.nanobot.update.plan", payload)
+ if problem == "extras":
+ assert response.status_code == 409
+ assert not (fixture.directory / "plans").exists()
+ else:
+ assert response.status_code == 200
+ payload = json.loads(response.body)
+ assert payload["execution_available"] is False
+ assert payload["plan"]["execution_blocked_reason"] == (
+ "external_restart" if os.name == "posix" else "installation_owner"
+ )
+ assert not any(profile["restart"] for profile in payload["plan"]["profiles"])
diff --git a/tests/webui/test_version_check.py b/tests/webui/test_version_check.py
index f2ad30107..1f521b37f 100644
--- a/tests/webui/test_version_check.py
+++ b/tests/webui/test_version_check.py
@@ -1,64 +1,163 @@
from __future__ import annotations
-from unittest.mock import MagicMock
+import hashlib
+import sys
+from pathlib import Path
+from types import SimpleNamespace
+import httpx
import pytest
+from packaging.tags import Tag
+import nanobot
import nanobot.webui.version_check as version_check
-
-
[email protected](autouse=True)
-def _reset_version_cache(monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(version_check, "_cache", (0.0, None))
- monkeypatch.setattr(version_check.time, "monotonic", lambda: 1_000.0)
-
-
-def _pypi_response(latest: object) -> MagicMock:
- response = MagicMock()
- response.json.return_value = {"info": {"version": latest}}
- return response
-
-
-def test_version_check_reports_only_a_newer_release_and_caches_it(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- get = MagicMock(return_value=_pypi_response("1.3.0"))
- monkeypatch.setattr(version_check, "__version__", "1.2.0")
- monkeypatch.setattr(version_check.httpx, "get", get)
-
- expected = {
- "currentVersion": "1.2.0",
- "latestVersion": "1.3.0",
- "pypiUrl": "https://pypi.org/project/nanobot-ai/",
- }
- assert version_check.check_for_update() == expected
- assert version_check.check_for_update() == expected
- get.assert_called_once_with(
- "https://pypi.org/pypi/nanobot-ai/json",
- timeout=5.0,
- follow_redirects=True,
- )
-
-
[email protected]("latest", ["1.2.0", "1.1.9", "not-a-version", 42, None])
-def test_version_check_ignores_non_newer_or_invalid_releases(
- monkeypatch: pytest.MonkeyPatch,
- latest: object,
-) -> None:
- monkeypatch.setattr(version_check, "__version__", "1.2.0")
- monkeypatch.setattr(version_check.httpx, "get", lambda *_args, **_kwargs: _pypi_response(latest))
-
- assert version_check.check_for_update() is None
-
-
-def test_version_check_treats_network_failure_as_best_effort(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- get = MagicMock(side_effect=TimeoutError("offline"))
- monkeypatch.setattr(version_check.httpx, "get", get)
-
- assert version_check.check_for_update() is None
-
- # Failures are not cached, so a later explicit check can recover.
- assert version_check.check_for_update() is None
- assert get.call_count == 2
+from nanobot.release_feed import CATALOGUE_URL, PYPI_URL, ReleaseFeed
+from nanobot.releases import (
+ ReleaseArtifact,
+ ReleaseCatalogue,
+ ReleaseManifest,
+ ReleasePointer,
+ release_filenames,
+)
+from nanobot.update_channel import UpdateChannelRequest, read_update_channel
+from nanobot.update_service import UpdateJobService
+
+
+def releases(tmp_path, monkeypatch):
+ monkeypatch.setattr(Path, "home", classmethod(lambda cls: tmp_path / "account"))
+ monkeypatch.setattr(sys, "prefix", str(tmp_path / "installation"))
+ monkeypatch.setattr(nanobot, "__version__", "0.3.6")
+ state = SimpleNamespace(stable="0.3.6", preview="0.3.7.dev42", generation=1,
+ withdrawn={}, partial=False, offline=False, incompatible=False, missing=False, requests=[])
+
+ def manifest(version):
+ value = ReleaseManifest(version=version, source_commit="a" * 40, candidate_commit="b" * 40,
+ requires_python=">=3.11", artifacts=[
+ ReleaseArtifact(filename=name, size=123, sha256="c" * 64) for name in sorted(release_filenames(version))])
+ payload = value.model_dump_json().encode()
+ return ReleasePointer(version=version, candidate_commit=value.candidate_commit,
+ manifest_sha256=hashlib.sha256(payload).hexdigest()), payload
+
+ def handler(request):
+ state.requests.append(str(request.url))
+ if state.offline:
+ raise httpx.ConnectError("private proxy credential", request=request)
+ if str(request.url) == CATALOGUE_URL:
+ if state.missing:
+ return httpx.Response(404)
+ catalogue = ReleaseCatalogue(generation=state.generation, stable=manifest(state.stable)[0],
+ preview=manifest(state.preview)[0], withdrawn=state.withdrawn)
+ return httpx.Response(200, content=catalogue.model_dump_json())
+ if str(request.url).startswith(PYPI_URL):
+ version = state.stable
+ files = [name for name in sorted(release_filenames(version)) if name.endswith((".whl", ".tar.gz"))]
+ return httpx.Response(200, json={
+ "info": {"name": "nanobot-ai", "version": version, "requires_python": ">=3.11"},
+ "urls": [{"filename": name, "size": 123, "yanked": False, "digests": {"sha256": "c" * 64},
+ "url": f"https://files.pythonhosted.org/packages/{name}"}
+ for name in (files[:-1] if state.partial else files)],
+ })
+ version = request.url.path.split("/v", 1)[1].split("/", 1)[0]
+ return httpx.Response(200, content=manifest(version)[1])
+
+ monkeypatch.setattr(version_check, "ReleaseFeed", lambda directory: ReleaseFeed(
+ directory, transport=httpx.MockTransport(handler), python_version="3.11.4",
+ supported_tags=[] if state.incompatible else [Tag("py3", "none", "win_amd64")],
+ ))
+ return state
+
+
+def select(channel):
+ current = read_update_channel()
+ return UpdateJobService().change_channel(UpdateChannelRequest(channel=channel, revision=current.revision))
+
+
+def test_stable_preview_exit_wait_and_final_release(releases, monkeypatch):
+ assert version_check.check_for_update()["releaseStatus"]["state"] == "current"
+ assert CATALOGUE_URL not in releases.requests
+ select("preview")
+ result = version_check.check_for_update()
+ assert result["updateAvailable"]["latestVersion"] == "0.3.7.dev42"
+ monkeypatch.setattr(nanobot, "__version__", "0.3.7.dev42")
+ releases.preview, releases.generation = "0.3.7.dev43", 2
+ assert version_check.check_for_update()["updateAvailable"]["latestVersion"] == "0.3.7.dev43"
+ select("stable")
+ result = version_check.check_for_update()
+ assert result["releaseStatus"]["state"] == "waiting_stable"
+ assert result["updateAvailable"] is None
+ releases.stable, releases.generation = "0.3.7", 3
+ assert version_check.check_for_update()["updateAvailable"]["latestVersion"] == "0.3.7"
+ assert read_update_channel().channel == "stable"
+
+
+def test_preview_subscription_survives_final_release_and_next_cycle(releases, monkeypatch):
+ select("preview")
+ releases.stable = "0.3.7"
+ monkeypatch.setattr(nanobot, "__version__", "0.3.7.dev42")
+ assert version_check.check_for_update()["updateAvailable"]["latestVersion"] == "0.3.7"
+ monkeypatch.setattr(nanobot, "__version__", "0.3.7")
+ assert version_check.check_for_update()["releaseStatus"]["state"] == "current"
+ assert read_update_channel().channel == "preview"
+ releases.preview, releases.generation = "0.3.8.dev1", 2
+ assert version_check.check_for_update()["updateAvailable"]["latestVersion"] == "0.3.8.dev1"
+
+
+def test_leaving_preview_can_find_a_newer_stable_when_catalogue_is_unavailable(releases, monkeypatch):
+ select("preview")
+ monkeypatch.setattr(nanobot, "__version__", "0.3.7.dev42")
+ select("stable")
+ releases.missing = True
+ releases.stable = "0.3.7"
+ result = version_check.check_for_update()
+ assert result["updateAvailable"]["latestVersion"] == "0.3.7"
+ assert result["releaseStatus"]["state"] == "available"
+ assert read_update_channel().channel == "stable"
+ # A broken Preview index cannot authorize a partial release or a downgrade,
+ # or turn unverified withdrawal status into a green 'up to date'.
+ releases.partial = True
+ assert version_check.check_for_update()["updateAvailable"] is None
+ releases.partial = False
+ releases.stable = "0.3.6"
+ result = version_check.check_for_update()
+ assert result["updateAvailable"] is None
+ assert result["releaseStatus"]["state"] == "unavailable"
+
+
[email protected]("replacement", ["older", "newer", "incompatible"])
[email protected]("channel", ["stable", "preview"])
+def test_withdrawn_running_preview_is_not_reported_up_to_date(releases, monkeypatch, replacement, channel):
+ select(channel)
+ monkeypatch.setattr(nanobot, "__version__", "0.3.7.dev42")
+ releases.withdrawn = {"0.3.7.dev42": "Startup regression"}
+ if replacement != "older":
+ releases.preview = "0.3.7.dev43"
+ releases.stable = "0.3.7"
+ releases.incompatible = replacement == "incompatible"
+ result = version_check.check_for_update()
+ assert result["releaseStatus"]["state"] == "withdrawn"
+ assert (result["updateAvailable"] is not None) == (replacement == "newer")
+
+
[email protected]("problem,state", [("partial", "publishing"), ("offline", "unavailable"),
+ ("incompatible", "unsupported"), ("missing", "unavailable")])
+def test_unavailable_checks_have_feedback_and_can_recover(releases, problem, state):
+ if problem == "missing":
+ select("preview")
+ setattr(releases, problem, True)
+ result = version_check.check_for_update()
+ assert result["updateAvailable"] is None
+ assert result["releaseStatus"]["state"] == state
+ assert "credential" not in str(result)
+ setattr(releases, problem, False)
+ assert version_check.check_for_update()["releaseStatus"]["state"] in {"current", "available"}
+
+
+def test_current_dev_does_not_implicitly_opt_in_and_older_target_is_not_offered(releases, monkeypatch):
+ monkeypatch.setattr(nanobot, "__version__", "0.3.8.dev1")
+ assert read_update_channel().channel == "stable"
+ assert version_check.check_for_update()["releaseStatus"]["state"] == "waiting_stable"
+ select("preview")
+ result = version_check.check_for_update()
+ assert result["updateAvailable"] is None
+ assert result["releaseStatus"]["state"] == "ahead"
diff --git a/tui/src/app/layout.test.ts b/tui/src/app/layout.test.ts
index 33fbb6935..3a0dc00a9 100644
--- a/tui/src/app/layout.test.ts
+++ b/tui/src/app/layout.test.ts
@@ -840,12 +840,15 @@ describe("NanobotTui layout and themes", () => {
setup.renderer.emit(CliRenderEvents.THEME_MODE, mode)
await setup.flush()
- const shimmerColors = new Set(
+ const shimmerColors = () => new Set(
(ui.status.content as StyledText).chunks
.slice(0, "Thinking".length)
.map((chunk) => chunk.fg?.toInts().slice(0, 3).join(",")),
)
- expect(shimmerColors.size).toBeGreaterThan(1)
+ // Theme detection updates the palette now; the next animation tick paints
+ // its StyledText chunks. A renderer flush does not advance that timer.
+ await waitUntil(() => shimmerColors().size > 1, 2_000)
+ expect(shimmerColors().size).toBeGreaterThan(1)
expect(ui.composer.textColor.intent).toBe("rgb")
expect(ui.composer.textColor.toInts().slice(0, 3)).toEqual(
mode === "light" ? [24, 24, 27] : [236, 237, 238],
diff --git a/webui/browser/about-layout.spec.ts b/webui/browser/about-layout.spec.ts
new file mode 100644
index 000000000..1b1bcb64c
--- /dev/null
+++ b/webui/browser/about-layout.spec.ts
@@ -0,0 +1,45 @@
+import { expect, test } from "@playwright/test";
+
+test("About current-version feedback keeps its initial row height with wider system fonts", async ({ page }) => {
+ await page.setViewportSize({ width: 1440, height: 1000 });
+ await page.emulateMedia({ reducedMotion: "reduce" });
+ await page.addInitScript(() => localStorage.setItem("nanobot.locale", "en"));
+ const positions: number[] = [];
+ for (const state of ["loaded", "loading"]) {
+ await page.goto(`/browser/fixture.html?case=skeleton-additions&surface=settings&state=${state}&section=about`);
+ await page.addStyleTag({ content: "body { font-family: monospace; }" });
+ if (state === "loaded") await expect(page.getByText("You're up to date", { exact: true })).toBeVisible();
+ const row = page.locator("[data-settings-section] .settings-list-row").first();
+ await expect(row).toBeVisible();
+ positions.push((await row.boundingBox())!.y);
+ expect(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth)).toBe(false);
+ }
+ expect(Math.abs(positions[0] - positions[1])).toBeLessThan(0.5);
+});
+
+for (const state of ["loaded", "loading"]) {
+ test(`About ${state} reserves the wordmark before its image loads`, async ({ page }) => {
+ await page.setViewportSize({ width: 1440, height: 1000 });
+ await page.emulateMedia({ reducedMotion: "reduce" });
+ let release!: () => void;
+ const pendingImage = new Promise<void>(resolve => { release = resolve; });
+ await page.route("**/brand/nanobot_wordmark.svg", async route => {
+ await pendingImage;
+ await route.continue();
+ });
+ try {
+ await page.goto(`/browser/fixture.html?case=skeleton-additions&surface=settings&state=${state}&section=about`, { waitUntil: "domcontentloaded" });
+ const row = page.locator("[data-settings-section] .settings-list-row").first();
+ await expect(row).toBeVisible();
+ const before = await row.boundingBox();
+ release();
+ const wordmark = page.locator('img[alt="nanobot"]');
+ await expect(wordmark).toHaveJSProperty("complete", true);
+ expect(await wordmark.evaluate(image => (image as HTMLImageElement).naturalWidth)).toBeGreaterThan(0);
+ const after = await row.boundingBox();
+ expect(Math.abs(after!.y - before!.y)).toBeLessThan(0.5);
+ } finally {
+ release();
+ }
+ });
+}
diff --git a/webui/browser/skeleton-additions.spec.ts b/webui/browser/skeleton-additions.spec.ts
index c91cfe774..a20629122 100644
--- a/webui/browser/skeleton-additions.spec.ts
+++ b/webui/browser/skeleton-additions.spec.ts
@@ -19,10 +19,10 @@ async function boxes(locator: Locator) {
}));
}
-function sameBoxes(actual: Awaited<ReturnType<typeof boxes>>, expected: typeof actual) {
+function sameBoxes(actual: Awaited<ReturnType<typeof boxes>>, expected: typeof actual, surface = "") {
expect(actual).toHaveLength(expected.length);
for (let index = 0; index < actual.length; index++) for (const key of ["x", "y", "width", "height"] as const) {
- expect(Math.abs(actual[index][key] - expected[index][key]), `row ${index} ${key}`).toBeLessThan(0.5);
+ expect(Math.abs(actual[index][key] - expected[index][key]), `${surface} row ${index} ${key}: ${JSON.stringify({ actual: actual[index], expected: expected[index] })}`).toBeLessThan(0.5);
}
}
@@ -81,7 +81,7 @@ for (const width of [390, 1440]) for (const locale of ["en", "zh-CN"]) {
await settle(page);
const skeletonSelector = section === "overview" ? "[data-overview-skeleton-row]" : section === "models" ? "[data-model-preset-skeleton], .settings-footer" : section === "about" ? ".settings-list-row" : "[data-settings-skeleton-row]";
const skeleton = await boxes(target.locator(skeletonSelector + notificationDetails));
- sameBoxes(skeleton, loaded);
+ sameBoxes(skeleton, loaded, section);
if (readingControl) sameBoxes(await boxes(target.locator("[data-skeleton-reading-size]")), readingControl);
if (loadedControls) {
const skeletonControls = await boxes(target.locator("[data-skeleton-switch]"));
diff --git a/webui/src/App.tsx b/webui/src/App.tsx
index 373a1dfa4..da54c5100 100644
--- a/webui/src/App.tsx
+++ b/webui/src/App.tsx
@@ -78,6 +78,8 @@ import { BrowserNotifications, useBrowserNotificationLifecycle } from "@/compone
import { ThreadMessageCache } from "@/lib/thread-message-cache";
import { FilePreviewStore } from "@/hooks/useFilePreviewState";
import { ClientProvider, useClient } from "@/providers/ClientProvider";
+import { useVersionCheck } from "@/providers/VersionCheckProvider";
+import { useUpdateFlow } from "@/providers/UpdateFlowProvider";
import type {
BootstrapResponse,
ChatSummary,
@@ -1139,6 +1141,8 @@ export default function App() {
modelName={state.modelName}
ingressLimits={state.ingressLimits}
webuiCapabilities={state.webuiCapabilities}
+ checkUpdatesOnConnect={state.runtimeSurface !== "native" && state.webuiCapabilities.includes("webui.core.v1")}
+ allowUpdateFlow={state.runtimeSurface !== "native"}
>
<BrowserNotifications client={state.client} />
<RemoteInstances><Shell
@@ -1164,6 +1168,8 @@ function Shell({
}) {
const { t, i18n } = useTranslation();
const remoteConnections = useRemoteConnections();
+ const versionCheck = useVersionCheck();
+ const updateFlow = useUpdateFlow();
const localActive = remoteConnections?.localActive !== false;
const managingConnections = remoteConnections?.managing === true && !remoteConnections?.activeHostId;
const { theme, toggle } = useTheme();
@@ -2772,6 +2778,12 @@ function Shell({
onRequestRenameProject,
onNewChatInProject,
onOpenSettings,
+ onOpenUpdates: () => onOpenSettings("about"),
+ availableUpdate: localActive && !isNativeRuntime(effectiveRuntimeSurface)
+ && versionCheck.result?.type === "update" && versionCheck.result.latestVersion !== versionCheck.dismissedVersion
+ ? { version: versionCheck.result.latestVersion, onDismiss: versionCheck.dismiss, onRequestUpdate: updateFlow.open,
+ installationMethod: updateFlow.pending ? null : versionCheck.installationMethod }
+ : undefined,
onOpenApps,
onOpenAutomations,
onOpenChannels,
diff --git a/webui/src/components/Sidebar.tsx b/webui/src/components/Sidebar.tsx
index d7199e6ed..121ad3487 100644
--- a/webui/src/components/Sidebar.tsx
+++ b/webui/src/components/Sidebar.tsx
@@ -24,6 +24,7 @@ import {
type SidebarPaneGroup,
} from "@/components/ChatList";
import { HostSwitcher } from "@/components/remote/HostSwitcher";
+import { UpdateNotice } from "@/components/UpdateNotice";
import {
SIDEBAR_SELECTION_ACTION_ITEM_CLASS,
SidebarSelectionHighlight,
@@ -35,6 +36,7 @@ import type {
SidebarViewState,
} from "@/lib/types";
import { cn } from "@/lib/utils";
+import type { UpdateMethod } from "@/lib/api";
import { sidebarShortcutAria, sidebarShortcutLabel } from "@/lib/sidebar-shortcuts";
interface SidebarProps {
@@ -66,6 +68,8 @@ interface SidebarProps {
onRequestRenameProject: (projectKey: string, label: string) => void;
onNewChatInProject: (projectPath: string, projectName: string) => void;
onOpenSettings: () => void;
+ onOpenUpdates?: () => void;
+ availableUpdate?: { version: string; onDismiss: () => void; onRequestUpdate?: () => void; installationMethod?: UpdateMethod | null };
onOpenApps: () => void;
onOpenSkills: () => void;
onOpenAutomations: () => void;
@@ -313,6 +317,11 @@ export function Sidebar(props: SidebarProps) {
/>
)}
</div>
+ {props.onOpenUpdates && props.availableUpdate && (
+ <UpdateNotice version={props.availableUpdate.version} collapsed={collapsed}
+ onOpen={props.onOpenUpdates} onDismiss={props.availableUpdate.onDismiss}
+ onRequestUpdate={props.availableUpdate.onRequestUpdate} installationMethod={props.availableUpdate.installationMethod} />
+ )}
<div
className={cn(
"flex items-center justify-between gap-1 bg-sidebar/55 px-2.5 py-3 text-xs",
diff --git a/webui/src/components/UpdateGuide.tsx b/webui/src/components/UpdateGuide.tsx
new file mode 100644
index 000000000..3fc402adf
--- /dev/null
+++ b/webui/src/components/UpdateGuide.tsx
@@ -0,0 +1,78 @@
+import { useEffect, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { ChevronDown } from "lucide-react";
+
+import { Button } from "@/components/ui/button";
+import { Textarea } from "@/components/ui/textarea";
+import { Disclosure } from "@/components/ui/disclosure";
+import { fetchSettings, type UpdateGuide as Guide } from "@/lib/api";
+import { copyTextToClipboard } from "@/lib/clipboard";
+
+function Command({ command, label, collapsed = false }: { command: string; label: string; collapsed?: boolean }) {
+ const { t } = useTranslation();
+ const [copy, setCopy] = useState<"idle" | "pending" | "copied" | "failed">("idle");
+ const content = <div className="space-y-1.5">
+ <div className="flex items-center justify-between gap-2">
+ <span className="text-xs font-medium">{label}</span>
+ <Button size="sm" variant="ghost" disabled={copy === "pending"} aria-busy={copy === "pending"} className="h-7 px-2 text-xs" onClick={async () => {
+ setCopy("pending");
+ setCopy(await copyTextToClipboard(command) ? "copied" : "failed");
+ }}>{t(copy === "copied" ? "remote.pair.copied" : "remote.pair.copy")}</Button>
+ </div>
+ <Textarea aria-label={label} readOnly value={command} rows={Math.min(5, command.split("\n").length + 1)}
+ onFocus={event => event.currentTarget.select()} className="resize-none font-mono text-xs leading-5" />
+ <p role="status" className="text-xs text-muted-foreground">{copy === "failed" ? t("remote.pair.copyFailed") : copy === "copied" ? t("remote.pair.copied") : ""}</p>
+ </div>;
+ return collapsed ? <Disclosure summaryClassName="flex min-h-9 items-center gap-2 rounded-control text-xs text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ summary={<><ChevronDown aria-hidden className="h-3.5 w-3.5 shrink-0 transition-transform group-data-[state=open]/disclosure:rotate-180 motion-reduce:transition-none" />{label}</>}>
+ {content}
+ </Disclosure> : content;
+}
+
+/** Display and copy only. The package manager/deployment remains the owner. */
+export function UpdateGuide({ guide, token, targetVersion }: { guide: Guide; token: string; targetVersion: string }) {
+ const { t } = useTranslation();
+ const active = useRef(true);
+ const [checking, setChecking] = useState(false);
+ const [result, setResult] = useState("");
+ useEffect(() => { active.current = true; return () => { active.current = false; }; }, []);
+ const check = async () => {
+ if (checking) return;
+ setChecking(true);
+ setResult("");
+ const feedback = new Promise(resolve => setTimeout(resolve, 600));
+ try {
+ const settings = await fetchSettings(token).finally(() => feedback);
+ const version = settings.version?.current;
+ if (!version) throw new Error("No running version");
+ if (active.current) setResult(t(version === targetVersion ? "updates.guide.verified" : "updates.guide.observed", { version, target: targetVersion }));
+ } catch {
+ if (active.current) setResult(t("updates.guide.checkFailed"));
+ } finally { if (active.current) setChecking(false); }
+ };
+ return <div className="mt-4 space-y-4 text-sm leading-6">
+ <div className="rounded-control bg-muted/50 p-3">
+ <p className="break-words font-medium">{t("updates.guide.host", { host: guide.host })}</p>
+ <p className="mt-1 text-xs leading-5 text-muted-foreground">{t(guide.method === "container" ? "updates.guide.containerHost" : "updates.guide.where")}</p>
+ <p className="mt-2 break-all font-mono text-xs text-muted-foreground">{guide.environment}</p>
+ </div>
+ <ol className="list-decimal space-y-4 ps-5 marker:text-muted-foreground">
+ <li className="ps-1"><p className="font-medium">{t("updates.guide.beforeTitle")}</p>
+ <p className="text-muted-foreground">{t("updates.guide.before")}</p></li>
+ <li className="space-y-2 ps-1"><p className="font-medium">{t("updates.guide.installTitle", { shell: guide.shell === "powershell" ? "PowerShell" : "sh / bash / zsh" })}</p>
+ <p className="text-muted-foreground">{t(`updates.guide.reasons.${guide.reason}`)}</p>
+ {guide.inspect_command && <Command command={guide.inspect_command} label={t("updates.guide.inspectCommand")} collapsed />}
+ {guide.update_command && <Command command={guide.update_command} label={t("updates.guide.updateCommand")} />}
+ </li>
+ <li className="space-y-2 ps-1"><p className="font-medium">{t("updates.guide.verifyTitle")}</p>
+ <p className="text-muted-foreground">{t("updates.guide.verify", { version: targetVersion })}</p>
+ {guide.verify_command && <Command command={guide.verify_command} label={t("updates.guide.versionCommand")} collapsed />}
+ <Button size="sm" variant="outline" aria-disabled={checking} aria-busy={checking}
+ className={checking ? "opacity-50" : undefined} onClick={() => void check()}>
+ {t(checking ? "settings.about.checking" : "updates.guide.check")}
+ </Button>
+ <p role="status" className="text-xs text-muted-foreground">{result}</p>
+ </li>
+ </ol>
+ </div>;
+}
diff --git a/webui/src/components/UpdateNotice.tsx b/webui/src/components/UpdateNotice.tsx
new file mode 100644
index 000000000..7c9496ca6
--- /dev/null
+++ b/webui/src/components/UpdateNotice.tsx
@@ -0,0 +1,57 @@
+import { Download } from "lucide-react";
+import { useId, useState } from "react";
+import { useTranslation } from "react-i18next";
+
+import { Button } from "@/components/ui/button";
+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
+import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
+import { cn } from "@/lib/utils";
+import type { UpdateMethod } from "@/lib/api";
+
+export function UpdateNotice({ version, collapsed = false, onOpen, onDismiss, onRequestUpdate, installationMethod }: {
+ version: string;
+ collapsed?: boolean;
+ onOpen: () => void;
+ onDismiss: () => void;
+ /** Opens the host's update confirmation, never installs from the entry itself. */
+ onRequestUpdate?: () => void;
+ installationMethod?: UpdateMethod | null;
+}) {
+ const { t } = useTranslation();
+ const [open, setOpen] = useState(false);
+ const titleId = useId();
+ const methodLabel = installationMethod && installationMethod !== "managed"
+ ? t("updates.guide.entry", { method: t(`updates.guide.methods.${installationMethod}`) }) : null;
+ const label = [t("settings.about.updateAvailable", { version }), methodLabel].filter(Boolean).join(" · ");
+ const button = <Button type="button" variant="ghost" aria-label={label} onClick={onRequestUpdate}
+ className={cn(
+ "touch-target h-8 min-w-0 gap-2 rounded-control text-blue-600 shadow-none hover:bg-blue-500/[0.08] data-[state=open]:bg-blue-500/[0.08] focus-visible:ring-blue-500 dark:text-blue-400 dark:hover:bg-blue-400/10 dark:data-[state=open]:bg-blue-400/10",
+ collapsed ? "w-8 p-0" : "w-full justify-start px-2 text-[13px] font-medium",
+ )}>
+ <Download className="h-4 w-4 shrink-0" strokeWidth={1.75} aria-hidden />
+ {!collapsed && <span className="truncate">{methodLabel ?? t("settings.about.updateNotice")}</span>}
+ </Button>;
+
+ return <div className={cn("flex shrink-0 items-center", collapsed ? "w-14 justify-center pb-1" : "px-2.5")}>
+ {onRequestUpdate ? <TooltipProvider><Tooltip>
+ <TooltipTrigger asChild>{button}</TooltipTrigger>
+ <TooltipContent side="right">{label}</TooltipContent>
+ </Tooltip></TooltipProvider> : <Popover open={open} onOpenChange={setOpen}>
+ {collapsed ? <TooltipProvider><Tooltip>
+ <TooltipTrigger asChild><PopoverTrigger asChild>{button}</PopoverTrigger></TooltipTrigger>
+ {!open && <TooltipContent side="right">{label}</TooltipContent>}
+ </Tooltip></TooltipProvider> : <PopoverTrigger asChild>{button}</PopoverTrigger>}
+ <PopoverContent side="top" align="start" sideOffset={8} collisionPadding={12}
+ aria-labelledby={titleId} className="w-64 max-w-[calc(100vw-1.5rem)] p-3.5">
+ <h2 id={titleId} className="text-[13px] font-medium">{label}</h2>
+ <div className="mt-3 flex flex-wrap items-center justify-end gap-1.5">
+ <Button type="button" variant="ghost" size="sm" className="touch-target h-8 px-2.5 text-xs text-muted-foreground"
+ onClick={() => { setOpen(false); onDismiss(); }}>{t("settings.about.dismissUpdate")}</Button>
+ <Button type="button" size="sm" variant="accent"
+ className="touch-target h-8 px-2.5 text-xs"
+ onClick={() => { setOpen(false); onOpen(); }}>{t("settings.about.viewUpdateDetails")}</Button>
+ </div>
+ </PopoverContent>
+ </Popover>}
+ </div>;
+}
diff --git a/webui/src/components/settings/overview/AboutSettingsView.tsx b/webui/src/components/settings/overview/AboutSettingsView.tsx
index c2532bc2f..59622c0a4 100644
--- a/webui/src/components/settings/overview/AboutSettingsView.tsx
+++ b/webui/src/components/settings/overview/AboutSettingsView.tsx
@@ -4,6 +4,22 @@ import { useTranslation } from "react-i18next";
import { SettingsGroup } from "@/components/settings/shared/SettingsControls";
+export function AboutSettingsLayout({ versionCheck, links, starLink }: {
+ versionCheck: ReactNode;
+ links: ReactNode;
+ starLink: ReactNode;
+}) {
+ return <div className="flex flex-1 flex-col gap-5">
+ <div className="flex flex-col items-center gap-3 py-6 text-center">
+ <img src="/brand/nanobot_mark.svg" alt="" className="h-16 w-16 select-none" draggable={false} />
+ <h1><img src="/brand/nanobot_wordmark.svg" alt="nanobot" width={800} height={164} className="h-auto w-40 select-none dark:brightness-150" draggable={false} /></h1>
+ </div>
+ {versionCheck}
+ {links}
+ <div className="mt-auto pt-8 text-center">{starLink}</div>
+ </div>;
+}
+
export function AboutSettingsView({ reportIssueUrl, versionCheck, starLink }: {
reportIssueUrl: string;
versionCheck: ReactNode;
@@ -16,12 +32,7 @@ export function AboutSettingsView({ reportIssueUrl, versionCheck, starLink }: {
{ key: "reportIssue", icon: MessageCircle, href: reportIssueUrl },
];
return (
- <div className="flex flex-1 flex-col gap-5">
- <div className="flex flex-col items-center gap-4 py-6 text-center">
- <img src="/brand/nanobot_mark.svg" alt="" className="h-16 w-16 select-none" draggable={false} />
- <h1><img src="/brand/nanobot_wordmark.svg" alt="nanobot" className="h-auto w-40 select-none dark:brightness-150" draggable={false} /></h1>
- {versionCheck}
- </div>
+ <AboutSettingsLayout versionCheck={versionCheck} starLink={starLink} links={
<SettingsGroup>
{links.map(({ key, icon: Icon, href }) => (
<a key={key} href={href} target="_blank" rel="noopener noreferrer"
@@ -32,9 +43,6 @@ export function AboutSettingsView({ reportIssueUrl, versionCheck, starLink }: {
</a>
))}
</SettingsGroup>
- <div className="mt-auto pt-8 text-center">
- {starLink}
- </div>
- </div>
+ } />
);
}
diff --git a/webui/src/components/settings/overview/OverviewSettings.tsx b/webui/src/components/settings/overview/OverviewSettings.tsx
index c1c95dc78..545d500e4 100644
--- a/webui/src/components/settings/overview/OverviewSettings.tsx
+++ b/webui/src/components/settings/overview/OverviewSettings.tsx
@@ -4,7 +4,7 @@ import {
ImageGenerationIcon,
VoiceIcon,
} from "@/components/icons/product-icons";
-import { useContext, useState, type Dispatch, type SetStateAction } from "react";
+import { useContext, useEffect, type Dispatch, type SetStateAction } from "react";
import {
ChevronRight,
type LucideIcon,
@@ -15,7 +15,7 @@ import { HostNavigationContext } from "@/components/remote/HostSwitcher";
import { StarLink } from "@/components/StarPrompt";
import { AboutSettingsView } from "./AboutSettingsView";
import { AppearanceSettingsView } from "./AppearanceSettingsView";
-import { VersionCheckRowView, type VersionCheckState, type VersionInfoProps } from "./VersionCheckRowView";
+import { VersionCheckRowView, type VersionInfoProps } from "./VersionCheckRowView";
import { DEFAULT_TRANSCRIPTION_SETTINGS } from "@/components/settings/capabilities/TranscriptionSettings";
import type { SettingsSectionKey } from "@/components/settings/contracts";
import { settingsProviderConfigured } from "@/components/settings/shared/ModelControls";
@@ -25,14 +25,14 @@ import {
} from "@/components/settings/shared/SettingsControls";
import { TokenUsageCard } from "@/components/settings/TokenUsageCard";
import { useLogoFallback } from "@/hooks/useLogoFallback";
-import { checkVersion } from "@/lib/api";
import type {
LocalPreferences,
} from "@/lib/local-preferences";
import { providerBrand, providerDisplayLabel } from "@/lib/provider-brand";
import type { SettingsPayload } from "@/lib/types";
import { cn } from "@/lib/utils";
-import { useClient } from "@/providers/ClientProvider";
+import { useUpdateFlow } from "@/providers/UpdateFlowProvider";
+import { useVersionCheck } from "@/providers/VersionCheckProvider";
export function OverviewSettings({
settings,
@@ -127,8 +127,10 @@ export function OverviewSettings({
);
}
-export function AboutSettings({ settings }: { settings: SettingsPayload }) {
+export function AboutSettings({ settings, onRequestUpdate: requestUpdate }: { settings: SettingsPayload; onRequestUpdate?: () => void }) {
const hostPicker = useContext(HostNavigationContext);
+ const flow = useUpdateFlow();
+ const onRequestUpdate = requestUpdate ?? flow.open;
const currentVersion = settings.version?.current;
const currentCommit = settings.version?.commit;
const environment = settings.environment;
@@ -152,38 +154,22 @@ export function AboutSettings({ settings }: { settings: SettingsPayload }) {
reportIssueUrl.searchParams.set("connection", hostPicker?.kind === "embedded"
? "Remote host" : hostPicker ? "Local host" : "Direct WebUI");
return <AboutSettingsView reportIssueUrl={reportIssueUrl.href}
- versionCheck={<VersionCheckRow currentVersion={currentVersion} currentCommit={currentCommit} />}
+ versionCheck={<VersionCheckRow currentVersion={currentVersion} currentCommit={currentCommit}
+ onRequestUpdate={onRequestUpdate} hasPendingUpdate={flow.pending} />}
starLink={<StarLink />} />;
}
-function VersionCheckRow({ currentVersion, currentCommit }: VersionInfoProps) {
- const { token } = useClient();
- const [checking, setChecking] = useState(false);
- const [result, setResult] = useState<VersionCheckState>(null);
-
- const handleCheck = async () => {
- setChecking(true);
- setResult(null);
- try {
- const res = await checkVersion(token);
- if (res.updateAvailable) {
- setResult({
- type: "update",
- latestVersion: res.updateAvailable.latestVersion,
- pypiUrl: res.updateAvailable.pypiUrl,
- });
- } else {
- setResult({ type: "up-to-date" });
- }
- } catch (err) {
- setResult({ type: "error", message: (err as Error).message });
- } finally {
- setChecking(false);
- }
- };
+function VersionCheckRow({ currentVersion, currentCommit, onRequestUpdate, hasPendingUpdate }: VersionInfoProps) {
+ const { checking, result, check, releaseStatus, canChangeChannel,
+ changingChannel, channelError, changeChannel, installationMethod } = useVersionCheck();
+ useEffect(() => { void check(); }, [check]);
return <VersionCheckRowView currentVersion={currentVersion} currentCommit={currentCommit}
- checking={checking} result={result} onCheck={() => void handleCheck()} />;
+ checking={checking} result={result} onCheck={() => void check()}
+ onRequestUpdate={onRequestUpdate} hasPendingUpdate={hasPendingUpdate}
+ installationMethod={installationMethod}
+ releaseStatus={releaseStatus} canChangeChannel={canChangeChannel} changingChannel={changingChannel}
+ channelError={channelError} onChangeChannel={changeChannel} />;
}
export function AppearanceSettings({ theme, onToggleTheme, localPrefs, onChangeLocalPrefs }: {
diff --git a/webui/src/components/settings/overview/VersionCheckRowView.tsx b/webui/src/components/settings/overview/VersionCheckRowView.tsx
index d51cc1b0a..45327ed1f 100644
--- a/webui/src/components/settings/overview/VersionCheckRowView.tsx
+++ b/webui/src/components/settings/overview/VersionCheckRowView.tsx
@@ -1,32 +1,49 @@
-import { ArrowUpCircle, Check, ExternalLink, Loader2 } from "lucide-react";
+import { useId } from "react";
+import { Check, ExternalLink, Loader2 } from "lucide-react";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
+import { SettingsGroup, SettingsRow } from "@/components/settings/shared/SettingsControls";
+import { ToggleButton } from "@/components/ui/toggle-button";
+import type { ReleaseStatus, UpdateChannel, UpdateMethod } from "@/lib/api";
+import type { VersionResult } from "@/providers/VersionCheckProvider";
-export type VersionInfoProps = { currentVersion?: string; currentCommit?: string | null };
-export type VersionCheckState =
- | { type: "up-to-date" }
- | { type: "update"; latestVersion: string; pypiUrl?: string }
- | { type: "error"; message: string }
- | null;
+export type VersionInfoProps = {
+ currentVersion?: string;
+ currentCommit?: string | null;
+ onRequestUpdate?: () => void;
+ hasPendingUpdate?: boolean;
+ installationMethod?: UpdateMethod | null;
+};
+export type VersionCheckState = VersionResult;
-export function VersionCheckRowView({ currentVersion, currentCommit, checking, result, onCheck }: VersionInfoProps & {
+export function VersionCheckRowView({
+ currentVersion, currentCommit, checking, result, onCheck,
+ onRequestUpdate, hasPendingUpdate, installationMethod,
+ releaseStatus, canChangeChannel, changingChannel, channelError, onChangeChannel,
+}: VersionInfoProps & {
checking: boolean;
result: VersionCheckState;
onCheck: () => void;
+ releaseStatus?: ReleaseStatus | null;
+ canChangeChannel?: boolean;
+ changingChannel?: boolean;
+ channelError?: string;
+ onChangeChannel?: (channel: UpdateChannel) => Promise<void>;
}) {
const { t } = useTranslation();
- const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });
+ const previewHelp = useId();
+ const previewToggle = useId();
+ const available = result?.type === "update" ? result : null;
+ const actionClass = "h-auto min-h-9 max-w-full whitespace-normal break-words text-start";
return (
- <div className="flex flex-col items-center gap-4">
- <div className="min-w-0">
- <div className="sr-only">
- {tx("settings.about.version", "Version")}
- </div>
- <div className="mt-0.5 text-[12px] leading-5 text-muted-foreground">
- {currentVersion ? `v${currentVersion}` : "nanobot"}
- {currentCommit && (
- <>
+ <SettingsGroup>
+ <SettingsRow title={<>
+ <span>{t("settings.about.version")}</span>
+ <div className="mt-1 flex flex-wrap items-baseline gap-x-2 text-[13px] font-normal leading-5 tabular-nums text-muted-foreground">
+ <span className="min-w-0 break-all">
+ {currentVersion ? `v${currentVersion}` : "nanobot"}
+ {currentCommit && <>
<span aria-hidden> (</span>
<a href={`https://github.com/HKUDS/nanobot/commit/${currentCommit}`}
target="_blank" rel="noopener noreferrer" title={currentCommit}
@@ -34,57 +51,73 @@ export function VersionCheckRowView({ currentVersion, currentCommit, checking, r
{currentCommit.slice(0, 7)}
</a>
<span aria-hidden>)</span>
- </>
- )}
- </div>
- </div>
- <div className="flex shrink-0 flex-col items-center gap-2">
- <Button
- size="sm"
- variant="outline"
- onClick={onCheck}
- disabled={checking}
- className="rounded-full"
- >
- {checking ? (
- <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" aria-hidden />
- ) : (
- <ArrowUpCircle className="mr-1.5 h-3.5 w-3.5" aria-hidden />
- )}
- {checking
- ? tx("settings.about.checking", "Checking...")
- : tx("settings.about.checkForUpdates", "Check for updates")}
- </Button>
- {result?.type === "up-to-date" ? (
- <span className="inline-flex items-center gap-1.5 text-[12px] text-emerald-600 dark:text-emerald-300">
- <Check className="h-3 w-3" aria-hidden />
- {tx("settings.about.upToDate", "You're up to date")}
+ </>}
</span>
- ) : null}
- {result?.type === "update" ? (
- <span className="inline-flex items-center gap-1.5 text-[12px] text-blue-600 dark:text-blue-300">
- <ArrowUpCircle className="h-3 w-3" aria-hidden />
- {t("settings.about.updateAvailable", {
- defaultValue: "Update available v{{version}}",
- version: result.latestVersion,
- })}
- {result.pypiUrl ? (
- <a
- href={result.pypiUrl}
- target="_blank"
- rel="noopener noreferrer"
- className="inline-flex items-center gap-0.5 underline-offset-2 hover:underline"
- >
- PyPI
- <ExternalLink className="h-2.5 w-2.5" aria-hidden />
+ {available && !checking && <span className="min-w-0 break-all" role="status">
+ <span aria-hidden>→ </span><span className="sr-only">{t("settings.about.updateNotice")} </span>
+ <span>v{available.latestVersion}</span>
+ </span>}
+ </div>
+ {!checking && available && releaseStatus?.state === "withdrawn" &&
+ <p role="alert" className="mt-1 text-[13px] font-normal leading-5 text-destructive">{t("updates.channel.withdrawn")}</p>}
+ {available && !checking && !onRequestUpdate &&
+ <p className="mt-1 text-[13px] font-normal leading-5 text-muted-foreground">{t("settings.about.updateInstructions")}</p>}
+ </>}>
+ <div className="settings-version-actions flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1">
+ {(checking || (result && !available)) && <span role="status" aria-atomic="true" className={`min-w-0 text-[13px] leading-5 [overflow-wrap:anywhere] ${result?.type === "error" && !checking ? "text-destructive" : "text-muted-foreground"}`}>
+ {checking ? <span className="inline-flex items-center gap-1.5">
+ <Loader2 className="h-3.5 w-3.5 shrink-0 animate-spin motion-reduce:animate-none" aria-hidden />
+ {t("settings.about.checking")}
+ </span> : result?.type === "up-to-date" ? <span className="inline-flex items-center gap-1.5">
+ <Check className="h-3 w-3 shrink-0" aria-hidden />{t("settings.about.upToDate")}
+ </span> : result?.type === "release-status" ? t(`updates.channel.${result.state}`)
+ : result?.type === "error" ? result.message : null}
+ </span>}
+ {hasPendingUpdate && onRequestUpdate ? (
+ <Button size="sm" variant="outline" className={actionClass} onClick={onRequestUpdate}>
+ {t("settings.about.viewUpdateDetails")}
+ </Button>
+ ) : checking ? null : available ? <>
+ {onRequestUpdate ? <Button size="sm" variant="outline" className={actionClass} onClick={onRequestUpdate} disabled={changingChannel}>
+ {installationMethod && installationMethod !== "managed"
+ ? t("updates.guide.entry", { method: t(`updates.guide.methods.${installationMethod}`) })
+ : t("settings.about.updateNow")}
+ </Button> : <Button size="sm" variant="outline" className={actionClass} asChild>
+ <a href="https://github.com/HKUDS/nanobot#-install" target="_blank" rel="noopener noreferrer">
+ {t("settings.about.installationGuide")}<ExternalLink className="ms-1.5 h-3 w-3 shrink-0" aria-hidden />
+ </a>
+ </Button>}
+ {available.releaseUrl || available.pypiUrl ? (
+ <a href={available.releaseUrl || available.pypiUrl} target="_blank" rel="noopener noreferrer"
+ className="inline-flex min-h-9 items-center gap-1 rounded-control text-[13px] text-muted-foreground underline-offset-2 hover:text-foreground hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
+ {available.releaseUrl ? t("updates.channel.releaseNotes") : "PyPI"}
+ <ExternalLink className="h-3 w-3 shrink-0" aria-hidden />
</a>
) : null}
+ </> : <Button size="sm" variant="ghost" className={`${actionClass} px-2 text-muted-foreground`} onClick={onCheck} disabled={changingChannel}>
+ {result?.type === "error" ? t("common.retry") : result ? t("updates.checkAgain") : t("settings.about.checkForUpdates")}
+ </Button>}
+ </div>
+ </SettingsRow>
+ {releaseStatus && onChangeChannel && <div className="border-t border-border/50">
+ <SettingsRow title={<>
+ <label htmlFor={previewToggle}>{t("updates.channel.receivePreview")}</label>
+ <p id={previewHelp} className="mt-1 text-[13px] font-normal leading-5 text-muted-foreground">
+ {t("updates.channel.hint")}
+ {!canChangeChannel && <span className="mt-2 block">{t("updates.blocked.permission")}</span>}
+ </p>
+ </>}>
+ <ToggleButton id={previewToggle} checked={releaseStatus.channel === "preview"}
+ onChange={enabled => { void onChangeChannel(enabled ? "preview" : "stable"); }}
+ disabled={!canChangeChannel || changingChannel || checking}
+ label={t("updates.channel.receivePreview")} aria-describedby={previewHelp} />
+ </SettingsRow>
+ <p role="status" className={`settings-list-inset text-[13px] leading-5 ${channelError ? "text-destructive" : "text-muted-foreground"}`}>
+ <span className={changingChannel || channelError ? "block pb-3" : undefined}>
+ {changingChannel ? t("updates.channel.saving") : channelError}
</span>
- ) : null}
- {result?.type === "error" ? (
- <span className="text-[12px] text-destructive">{result.message}</span>
- ) : null}
- </div>
- </div>
+ </p>
+ </div>}
+ </SettingsGroup>
);
}
diff --git a/webui/src/components/settings/shared/SettingsSectionSkeleton.tsx b/webui/src/components/settings/shared/SettingsSectionSkeleton.tsx
index cd0e21897..5ca9d8f34 100644
--- a/webui/src/components/settings/shared/SettingsSectionSkeleton.tsx
+++ b/webui/src/components/settings/shared/SettingsSectionSkeleton.tsx
@@ -2,7 +2,8 @@ import type { ReactNode } from "react";
import { useTranslation } from "react-i18next";
import { isCapabilitySection, type SettingsSectionKey } from "@/components/settings/contracts";
-import { SettingsGroup } from "@/components/settings/shared/SettingsControls";
+import { AboutSettingsLayout } from "@/components/settings/overview/AboutSettingsView";
+import { SettingsGroup, SettingsRow } from "@/components/settings/shared/SettingsControls";
import { SkeletonStatus } from "@/components/settings/shared/SkeletonStatus";
import { RUNTIME_CONFIG_FIELDS, RUNTIME_CONFIG_GROUPS, type RuntimeConfigPage } from "@/components/settings/system/runtime-config-fields";
import { cn } from "@/lib/utils";
@@ -94,14 +95,14 @@ export function SettingsSectionSkeleton({ section, showRestart = false }: { sect
content = <RuntimeGroups page="advanced" />;
break;
case "about":
- content = <>
- <div className="flex flex-col items-center gap-4 py-6">
- <img src="/brand/nanobot_mark.svg" alt="" className="h-16 w-16" />
- <img src="/brand/nanobot_wordmark.svg" alt="" className="h-auto w-40 dark:brightness-150" />
- <div className="flex flex-col items-center gap-4"><div className="mt-0.5 flex h-5 items-center"><div className={cn(block, "h-3 w-20")} /></div><div className={cn(block, "h-9 w-36 rounded-full")} /></div>
- </div>
+ content = <AboutSettingsLayout starLink={null} versionCheck={
+ <SettingsGroup><SettingsRow title={<>
+ <div className="flex h-5 items-center"><div className={cn(block, "h-3.5 w-20")} /></div>
+ <div className="mt-1 flex h-5 items-center"><div className={cn(block, "h-3 w-24")} /></div>
+ </>}><div className={cn(block, "settings-version-actions h-9 w-36 rounded-control")} /></SettingsRow></SettingsGroup>
+ } links={
<SettingsGroup>{[0, 1, 2].map((index) => <div key={index} className="settings-list-row flex items-center gap-3"><div className={cn(block, "h-4 w-4")} /><div className={cn(block, "h-3.5 w-28")} /></div>)}</SettingsGroup>
- </>;
+ } />;
break;
}
return <SkeletonStatus label={t("settings.status.loading")} className="settings-stack">{content}</SkeletonStatus>;
diff --git a/webui/src/components/settings/useSettingsController.ts b/webui/src/components/settings/useSettingsController.ts
index 3323f1390..0d71cbd3f 100644
--- a/webui/src/components/settings/useSettingsController.ts
+++ b/webui/src/components/settings/useSettingsController.ts
@@ -156,6 +156,11 @@ export function useSettingsController({
const runtimeConfigState = useRuntimeConfigSettings(settings, client, applyPayload);
+ const markUpdateInstalled = useCallback(() => {
+ setPendingRestartSections((current) => ({ ...current, runtime: true }));
+ setSettings((current) => current ? { ...current, requires_restart: true } : current);
+ }, []);
+
const closeProviderOAuthFlow = useCallback((cancelPending = true) => {
const flow = providerOAuthFlowRef.current;
providerOAuthFlowRef.current = null;
@@ -456,6 +461,7 @@ export function useSettingsController({
systemState,
systemActions,
activeSection,
+ markUpdateInstalled,
runtimeConfigState,
closeProviderOAuthFlow,
error,
diff --git a/webui/src/components/ui/button.tsx b/webui/src/components/ui/button.tsx
index 5c34add37..10632e4be 100644
--- a/webui/src/components/ui/button.tsx
+++ b/webui/src/components/ui/button.tsx
@@ -10,6 +10,7 @@ const buttonVariants = cva(
variants: {
variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/90",
+ accent: "bg-blue-600 text-white hover:bg-blue-700 dark:bg-blue-400 dark:text-slate-950 dark:hover:bg-blue-300",
destructive:
"bg-destructive text-destructive-foreground hover:bg-destructive/90",
outline:
diff --git a/webui/src/dev/gallery/foundations.tsx b/webui/src/dev/gallery/foundations.tsx
index da87c0469..17acf15ae 100644
--- a/webui/src/dev/gallery/foundations.tsx
+++ b/webui/src/dev/gallery/foundations.tsx
@@ -28,7 +28,7 @@ function Buttons() {
return <div className="space-y-6">
<Sample label={t("controls.button.variants")}>
<div className="flex flex-wrap items-center gap-3">
- {(["default", "secondary", "outline", "ghost", "destructive", "link"] as const).map((variant) =>
+ {(["default", "accent", "secondary", "outline", "ghost", "destructive", "link"] as const).map((variant) =>
<Button key={variant} variant={variant} onClick={() => setClicks((value) => value + 1)}>{variant}</Button>)}
<Button variant="icon" size="icon" aria-label={t("controls.button.add")} onClick={() => setClicks((value) => value + 1)}><Plus className="h-4 w-4" /></Button>
</div>
diff --git a/webui/src/dev/gallery/locales/controls/en.json b/webui/src/dev/gallery/locales/controls/en.json
index bdb45ecac..fd0c55126 100644
--- a/webui/src/dev/gallery/locales/controls/en.json
+++ b/webui/src/dev/gallery/locales/controls/en.json
@@ -481,7 +481,10 @@
"options": "AboutSettingsView accepts composed version and support links. VersionCheckRowView displays checking/result and requests checks through onCheck. The feature entry owns actual checks and diagnostic link data.",
"error": "Could not get version information. Try again.",
"state": "Version state",
- "selectedLink": "GitHub link selected"
+ "selectedLink": "GitHub link selected",
+ "preferenceSaved": "Sample preference saved; nothing will be installed or restarted.",
+ "updateRequested": "Update review selected; this preview does not install or restart anything.",
+ "dismissed": "Update notice dismissed"
},
"appearance": {
"title": "Appearance preferences",
diff --git a/webui/src/dev/gallery/locales/controls/es.json b/webui/src/dev/gallery/locales/controls/es.json
index 4bf7fdddc..151ed1453 100644
--- a/webui/src/dev/gallery/locales/controls/es.json
+++ b/webui/src/dev/gallery/locales/controls/es.json
@@ -481,7 +481,10 @@
"options": "AboutSettingsView acepta una composición de enlaces de versión y soporte. VersionCheckRowView muestra checking/result y solicita comprobaciones con onCheck. El punto de entrada gestiona las comprobaciones reales y los enlaces de diagnóstico.",
"error": "No se pudo obtener la versión. Inténtalo de nuevo.",
"state": "Estado de versión",
- "selectedLink": "Enlace de GitHub seleccionado"
+ "selectedLink": "Enlace de GitHub seleccionado",
+ "preferenceSaved": "Preferencia de ejemplo guardada; no se instalará ni reiniciará nada.",
+ "updateRequested": "Revisión de la actualización seleccionada; esta vista previa no instala ni reinicia nada.",
+ "dismissed": "Aviso de actualización ocultado"
},
"appearance": {
"title": "Preferencias de apariencia",
diff --git a/webui/src/dev/gallery/locales/controls/fr.json b/webui/src/dev/gallery/locales/controls/fr.json
index 29fb6b8c7..c6a488adf 100644
--- a/webui/src/dev/gallery/locales/controls/fr.json
+++ b/webui/src/dev/gallery/locales/controls/fr.json
@@ -481,7 +481,10 @@
"options": "AboutSettingsView accepte la composition des liens de version et d’assistance. VersionCheckRowView affiche checking/result et demande une vérification via onCheck. Le point d’entrée gère les vérifications réelles et les liens de diagnostic.",
"error": "Impossible d’obtenir la version. Réessayez.",
"state": "État de la version",
- "selectedLink": "Lien GitHub sélectionné"
+ "selectedLink": "Lien GitHub sélectionné",
+ "preferenceSaved": "Préférence d’exemple enregistrée ; rien ne sera installé ni redémarré.",
+ "updateRequested": "Examen de la mise à jour sélectionné ; cet aperçu n’installe ni ne redémarre rien.",
+ "dismissed": "Avis de mise à jour masqué"
},
"appearance": {
"title": "Préférences d’apparence",
diff --git a/webui/src/dev/gallery/locales/controls/id.json b/webui/src/dev/gallery/locales/controls/id.json
index 990adc7ca..6c82643fc 100644
--- a/webui/src/dev/gallery/locales/controls/id.json
+++ b/webui/src/dev/gallery/locales/controls/id.json
@@ -481,7 +481,10 @@
"options": "AboutSettingsView menerima gabungan tautan versi dan dukungan. VersionCheckRowView menampilkan checking/result dan meminta pemeriksaan melalui onCheck. Titik masuk fitur mengelola pemeriksaan sebenarnya serta data tautan diagnostik.",
"error": "Tidak dapat mengambil informasi versi. Coba lagi.",
"state": "Status versi",
- "selectedLink": "Tautan GitHub dipilih"
+ "selectedLink": "Tautan GitHub dipilih",
+ "preferenceSaved": "Preferensi contoh disimpan; tidak ada yang akan diinstal atau dimulai ulang.",
+ "updateRequested": "Peninjauan pembaruan dipilih; pratinjau ini tidak menginstal atau memulai ulang apa pun.",
+ "dismissed": "Pemberitahuan pembaruan ditutup"
},
"appearance": {
"title": "Preferensi tampilan",
diff --git a/webui/src/dev/gallery/locales/controls/ja.json b/webui/src/dev/gallery/locales/controls/ja.json
index e394cfec3..7ef84cc54 100644
--- a/webui/src/dev/gallery/locales/controls/ja.json
+++ b/webui/src/dev/gallery/locales/controls/ja.json
@@ -481,7 +481,10 @@
"options": "AboutSettingsView はバージョンとサポートリンクの組み合わせを受け取ります。VersionCheckRowView は checking/result を表示し、onCheck で確認を要求します。実際の確認と診断リンクのデータは機能の入口が管理します。",
"error": "バージョン情報を取得できませんでした。再試行してください。",
"state": "バージョンの状態",
- "selectedLink": "GitHub リンクを選択しました"
+ "selectedLink": "GitHub リンクを選択しました",
+ "preferenceSaved": "サンプル設定を保存しました。インストールや再起動は行いません。",
+ "updateRequested": "更新の確認を選択しました。このプレビューではインストールや再起動は行いません。",
+ "dismissed": "更新通知を閉じました"
},
"appearance": {
"title": "表示設定",
diff --git a/webui/src/dev/gallery/locales/controls/ko.json b/webui/src/dev/gallery/locales/controls/ko.json
index bf8bec922..d1d349474 100644
--- a/webui/src/dev/gallery/locales/controls/ko.json
+++ b/webui/src/dev/gallery/locales/controls/ko.json
@@ -481,7 +481,10 @@
"options": "AboutSettingsView는 버전과 지원 링크 조합을 받습니다. VersionCheckRowView는 checking/result를 표시하며 onCheck로 검사를 요청합니다. 실제 검사와 진단 링크 데이터는 기능 진입점이 담당합니다.",
"error": "버전 정보를 가져올 수 없습니다. 다시 시도하세요.",
"state": "버전 상태",
- "selectedLink": "GitHub 링크를 선택했습니다"
+ "selectedLink": "GitHub 링크를 선택했습니다",
+ "preferenceSaved": "예시 설정을 저장했습니다. 설치하거나 다시 시작하지 않습니다.",
+ "updateRequested": "업데이트 검토를 선택했습니다. 이 미리보기에서는 설치하거나 다시 시작하지 않습니다.",
+ "dismissed": "업데이트 알림을 닫았습니다"
},
"appearance": {
"title": "화면 환경설정",
diff --git a/webui/src/dev/gallery/locales/controls/pt-BR.json b/webui/src/dev/gallery/locales/controls/pt-BR.json
index c98a8830d..7790f7b9a 100644
--- a/webui/src/dev/gallery/locales/controls/pt-BR.json
+++ b/webui/src/dev/gallery/locales/controls/pt-BR.json
@@ -481,7 +481,10 @@
"options": "AboutSettingsView aceita uma composição de links de versão e suporte. VersionCheckRowView exibe checking/result e solicita verificações por onCheck. O ponto de entrada gerencia as verificações reais e os dados dos links de diagnóstico.",
"error": "Não foi possível obter a versão. Tente novamente.",
"state": "Estado da versão",
- "selectedLink": "Link do GitHub selecionado"
+ "selectedLink": "Link do GitHub selecionado",
+ "preferenceSaved": "Preferência de exemplo salva; nada será instalado ou reiniciado.",
+ "updateRequested": "Revisão da atualização selecionada; esta prévia não instala nem reinicia nada.",
+ "dismissed": "Aviso de atualização dispensado"
},
"appearance": {
"title": "Preferências de aparência",
diff --git a/webui/src/dev/gallery/locales/controls/vi.json b/webui/src/dev/gallery/locales/controls/vi.json
index 36c1f9417..16ac885a4 100644
--- a/webui/src/dev/gallery/locales/controls/vi.json
+++ b/webui/src/dev/gallery/locales/controls/vi.json
@@ -481,7 +481,10 @@
"options": "AboutSettingsView nhận tổ hợp liên kết phiên bản và hỗ trợ. VersionCheckRowView hiển thị checking/result và yêu cầu kiểm tra qua onCheck. Điểm vào tính năng quản lý kiểm tra thực tế và dữ liệu liên kết chẩn đoán.",
"error": "Không thể lấy thông tin phiên bản. Hãy thử lại.",
"state": "Trạng thái phiên bản",
- "selectedLink": "Đã chọn liên kết GitHub"
+ "selectedLink": "Đã chọn liên kết GitHub",
+ "preferenceSaved": "Đã lưu tùy chọn mẫu; sẽ không cài đặt hay khởi động lại.",
+ "updateRequested": "Đã chọn xem xét bản cập nhật; bản xem trước này không cài đặt hay khởi động lại.",
+ "dismissed": "Đã ẩn thông báo cập nhật"
},
"appearance": {
"title": "Tùy chọn giao diện",
diff --git a/webui/src/dev/gallery/locales/controls/zh-CN.json b/webui/src/dev/gallery/locales/controls/zh-CN.json
index d3e06c5a7..ca3c500d4 100644
--- a/webui/src/dev/gallery/locales/controls/zh-CN.json
+++ b/webui/src/dev/gallery/locales/controls/zh-CN.json
@@ -481,7 +481,10 @@
"options": "AboutSettingsView 接受版本与支持链接的组合。VersionCheckRowView 展示 checking/result,并通过 onCheck 请求检查。真实检查与诊断链接数据由功能入口负责。",
"error": "无法获取版本信息,请重试。",
"state": "版本状态",
- "selectedLink": "选择了 GitHub 链接"
+ "selectedLink": "选择了 GitHub 链接",
+ "preferenceSaved": "已保存示例偏好;不会安装或重启。",
+ "updateRequested": "已选择查看更新;组件预览不会安装或重启。",
+ "dismissed": "已收起更新提示"
},
"appearance": {
"title": "外观选项",
diff --git a/webui/src/dev/gallery/locales/controls/zh-TW.json b/webui/src/dev/gallery/locales/controls/zh-TW.json
index 08cf945b0..7417a2771 100644
--- a/webui/src/dev/gallery/locales/controls/zh-TW.json
+++ b/webui/src/dev/gallery/locales/controls/zh-TW.json
@@ -481,7 +481,10 @@
"options": "AboutSettingsView 接受版本與支援連結的組合。VersionCheckRowView 顯示 checking/result,並透過 onCheck 請求檢查。實際檢查與診斷連結資料由功能入口負責。",
"error": "無法取得版本資訊,請重試。",
"state": "版本狀態",
- "selectedLink": "已選取 GitHub 連結"
+ "selectedLink": "已選取 GitHub 連結",
+ "preferenceSaved": "已儲存範例偏好;不會安裝或重新啟動。",
+ "updateRequested": "已選擇查看更新;元件預覽不會安裝或重新啟動。",
+ "dismissed": "已收起更新提示"
},
"appearance": {
"title": "外觀選項",
diff --git a/webui/src/dev/gallery/runtime-settings.tsx b/webui/src/dev/gallery/runtime-settings.tsx
index 70b7e8ce1..9032f8648 100644
--- a/webui/src/dev/gallery/runtime-settings.tsx
+++ b/webui/src/dev/gallery/runtime-settings.tsx
@@ -9,6 +9,7 @@ import { AutomationRunDialogView, type AutomationRunResult } from "@/components/
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { DEFAULT_LOCAL_PREFS } from "@/lib/local-preferences";
+import type { UpdateChannel } from "@/lib/api";
import type { AutomationChatsPayload, SessionAutomationJob } from "@/lib/types";
import { StatePicker, type ComponentExample } from "./example";
import { useGalleryTranslation } from "./i18n";
@@ -68,17 +69,25 @@ function ChatBindingPreview() {
function AboutPreview() {
const { t } = useGalleryTranslation();
- const [mode, setMode] = useState<"ready" | "checking" | "up-to-date" | "update" | "error">("ready");
- const [selectedLink, setSelectedLink] = useState(false);
+ const [mode, setMode] = useState<"ready" | "checking" | "up-to-date" | "update" | "preview" | "error">("ready");
+ const [notice, setNotice] = useState<"updateRequested" | "selectedLink" | null>(null);
+ const [channel, setChannel] = useState<UpdateChannel>("stable");
const result: VersionCheckState = mode === "up-to-date" ? { type: mode }
: mode === "update" ? { type: mode, latestVersion: "0.3.6", pypiUrl: "https://pypi.org/project/nanobot-ai/" }
+ : mode === "preview" ? { type: "update", latestVersion: "0.3.7.dev2026101501",
+ releaseUrl: "https://github.com/HKUDS/nanobot/releases" }
: mode === "error" ? { type: mode, message: t("controls.about.error") } : null;
- return <><StatePicker label={t("controls.about.state")} value={mode} options={["ready", "checking", "up-to-date", "update", "error"]} onChange={setMode} />
+ return <><StatePicker label={t("controls.about.state")} value={mode} options={["ready", "checking", "up-to-date", "update", "preview", "error"]} onChange={setMode} />
<AboutSettingsView reportIssueUrl="https://github.com/HKUDS/nanobot/issues/new?template=bug_report.yml"
versionCheck={<VersionCheckRowView currentVersion="0.3.5" currentCommit="abcdef1234567890" checking={mode === "checking"}
- result={result} onCheck={() => setMode("update")} />}
- starLink={<StarLinkView onActivate={() => setSelectedLink(true)} />} />
- {selectedLink ? <p role="status" className="mt-4 text-xs text-muted-foreground">{t("controls.about.selectedLink")}</p> : null}</>;
+ result={result} onCheck={() => setMode("update")}
+ releaseStatus={{ channel, revision: 0, currentVersion: "0.3.5", state: "current" }}
+ canChangeChannel onChangeChannel={async (value) => {
+ setChannel(value);
+ }}
+ onRequestUpdate={mode === "preview" ? () => setNotice("updateRequested") : undefined} />}
+ starLink={<StarLinkView onActivate={() => setNotice("selectedLink")} />} />
+ {notice ? <p role="status" className="mt-4 text-xs text-muted-foreground">{t(`controls.about.${notice}`)}</p> : null}</>;
}
function AppearancePreview() {
diff --git a/webui/src/globals.css b/webui/src/globals.css
index bac91df17..db905ebfd 100644
--- a/webui/src/globals.css
+++ b/webui/src/globals.css
@@ -1669,8 +1669,8 @@
.settings-grid .settings-row > :nth-child(2),
.settings-grid .settings-footer > :nth-child(2) { grid-column: 8 / -1; }
.settings-grid .settings-footer-auto > :first-child { grid-column: 1 / -1; }
- .settings-grid .settings-row:has(.segmented-control) > :first-child { grid-column: 1 / 7; }
- .settings-grid .settings-row:has(.segmented-control) > :nth-child(2) { grid-column: 7 / -1; }
+ .settings-grid .settings-row:has(:is(.segmented-control, .settings-version-actions)) > :first-child { grid-column: 1 / 7; }
+ .settings-grid .settings-row:has(:is(.segmented-control, .settings-version-actions)) > :nth-child(2) { grid-column: 7 / -1; }
}
@media (min-width: 768px) {
.settings-grid { --settings-inset: 24px; }
diff --git a/webui/src/i18n/locales/en/common.json b/webui/src/i18n/locales/en/common.json
index f7a9b4711..26ef9f6f8 100644
--- a/webui/src/i18n/locales/en/common.json
+++ b/webui/src/i18n/locales/en/common.json
@@ -1,4 +1,106 @@
{
+ "updates": {
+ "guide": {
+ "entry": "Update via {{method}}",
+ "methods": {
+ "managed": "nanobot installer",
+ "uv": "uv",
+ "pipx": "pipx",
+ "pip": "pip",
+ "source": "source checkout",
+ "container": "container deployment",
+ "system": "system package manager"
+ },
+ "host": "Gateway: {{host}}",
+ "where": "Use a terminal on this computer, signed in as the original installation user. For a remote gateway, connect by SSH or its server console—not your browser’s computer. Commands only copy; this page does not run them.",
+ "containerHost": "This is the container’s name and internal path, not the deployment host. Use the server or hosting dashboard that manages this container; do not update inside the running container.",
+ "beforeTitle": "Prepare and stop",
+ "before": "Finish tasks and back up configuration, chats and workspace data. Stop all gateways using this installation through their original launcher or service manager. Keep their profile paths and launch settings.",
+ "installTitle": "Update in {{shell}}",
+ "inspectCommand": "Inspect this installation",
+ "updateCommand": "Update command",
+ "versionCommand": "Installed version",
+ "reasons": {
+ "restart": "The target package is already installed. Do not install it again. Stop the old gateway and restart with the original launcher and profile, then check its running version.",
+ "registry": "Use the original registry and credentials. Manager upgrades keep recorded extras and constraints and may select a different allowed stable version than the notice. Check the command output; do not force a failed update.",
+ "preview": "Preview packages are distributed on GitHub, not necessarily your package index. Select this release’s wheel for the gateway’s Python/platform, verify its checksum, then install it through the original owner with the same extras. A generic upgrade command cannot guarantee this Preview.",
+ "policy": "The receipt has a pin, lock, fixed source, version constraint or unrecognized options. Inspect it below and update through that original workflow, preserving extras and injected packages. Do not remove restrictions just to update.",
+ "extras": "This pip environment does not record the extras originally requested. Inspect the package below, then reuse the original pip requirement with --upgrade and the intended version, keeping its extras and index options. No guessed install command is provided.",
+ "manager": "The package-manager executable or its environment layout could not be confirmed. Use the original installation account and manager settings to target the path above; do not use another pip or nanobot from PATH.",
+ "source": "Inspect this checkout first. Preserve local changes and confirm the intended branch/ref, then update it and rebuild dependencies, WebUI and TUI using the repository workflow. Do not replace an editable checkout with a PyPI package.",
+ "container": "Choose the intended image tag/digest in the existing Compose project or hosting dashboard, pull/build it and recreate only the nanobot service with its existing mounts, secrets and ports. Back up data volumes; never remove them to update.",
+ "system": "Use the operating system’s package manager or ask this server’s administrator. Do not use sudo pip or override an externally managed Python environment.",
+ "review": "The installation or update review is no longer current. Close this dialog and check again before copying an update command."
+ },
+ "verifyTitle": "Restart and verify",
+ "verify": "Start using the same launcher and profile. The terminal command checks installed files only. Reconnect to this same gateway, check its running version against v{{version}}, and confirm your chats and settings are still present.",
+ "check": "Check running gateway",
+ "verified": "Confirmed: this gateway is running v{{version}}.",
+ "observed": "This gateway reports v{{version}}, not the notice’s v{{target}}. Check the installer output and restart the same installation; an installed package alone does not update a running process.",
+ "checkFailed": "Could not read the running version. Reconnect to this same gateway and try again; no update success has been confirmed."
+ },
+ "automaticRecovery": "If the update fails, nanobot will try to restore service, using the previous program when safe. Your chat data will not be rolled back.",
+ "restored": "Previous version restored",
+ "restoredDescription": "The update did not finish. v{{version}} is running again. Your configuration and chats were not rolled back.",
+ "recoveryBeforeInstall": "The update stopped before installation. No package files were changed. Recover the saved update to continue.",
+ "channel": {
+ "settings": "Update settings",
+ "receivePreview": "Receive preview updates",
+ "previewWarning": "This is a preview release and may have bugs.",
+ "preview": "Preview",
+ "hint": "Try new features early.",
+ "saving": "Saving…",
+ "saved": "Update preference saved",
+ "ahead": "This version is ahead of the selected channel. No downgrade will be installed.",
+ "waiting_stable": "Preview updates are off. Keep using this version until a newer stable release is available.",
+ "withdrawn": "This preview was withdrawn. Update to a newer release when available; do not downgrade over your current data.",
+ "unavailable": "Could not verify this channel. It may not be available yet. Check your connection and try again.",
+ "publishing": "The release is still being published. Check again later.",
+ "unsupported": "No compatible update is available for this Python version and platform.",
+ "releaseNotes": "Release notes"
+ },
+ "reviewAgain": "Review update",
+ "reviewAgainDescription": "No package files were changed. Review the update again before confirming installation and restart.",
+ "settleFailed": "The previous update could not be cleared safely. Check its status again or follow the recovery instructions.",
+ "ownerGuide": "Update instructions for your installation",
+ "recoveryTitle": "Recover on the gateway computer",
+ "recoveryDescription": "Run this command in a terminal on the computer running nanobot. It reviews the saved job before asking to repair. Keep the original backup.",
+ "confirm": "Update nanobot now?",
+ "reviewingTitle": "Checking the update…",
+ "preparing": "Downloading the update…",
+ "installing": "Installing the update…",
+ "working": "Updating nanobot…",
+ "reconnecting": "Reconnecting…",
+ "done": "Update complete",
+ "failed": "Update did not finish",
+ "confirmDescription": "Updating to v{{version}} will restart nanobot on {{host}}. Finish running tasks before continuing.",
+ "reviewing": "Checking the installation and exact target. No files are being changed.",
+ "workingDescription": "Preparing verified files, then backing up and restarting the selected gateway.",
+ "reconnectingDescription": "Waiting for the updated gateway to reconnect. Do not start another update.",
+ "delayed": "Reconnection is taking longer than expected. Progress is saved; you can close this window and check again.",
+ "doneDescription": "Now running v{{version}}.",
+ "preparationFailed": "Preparation or shutdown failed. No package files were changed. Finish any active tasks and check again.",
+ "repairRequired": "Installation or restart failed. The saved backup and update record are retained. Use the update recovery workflow; do not start a different installation.",
+ "reviewFailed": "Could not verify this update. Check the connection and ensure the gateway runs with its installation owner’s supported background launcher.",
+ "confirmationUnknown": "The request may have been accepted. Checking saved progress before another action.",
+ "statusFailed": "Could not read the saved update. Reconnect to the same gateway and check again.",
+ "sharedInstallation": "This shared installation will restart {{count}} running gateways.",
+ "cancel": "Cancel",
+ "close": "Close",
+ "hide": "Hide",
+ "return": "Done",
+ "wait": "Please wait",
+ "checkAgain": "Check again",
+ "apply": "Update & restart",
+ "blocked": {
+ "review_changed": "This review changed or expired. Close it and check again.",
+ "not_upgrade": "This target is not an upgrade. No files will be changed.",
+ "installation_owner": "Update this installation with its original package manager or deployment tool.",
+ "installation_policy": "This installation’s source, extras or version constraints require its original installation workflow.",
+ "external_restart": "This gateway cannot be restarted here. Use its original launch or deployment tool to stop, update and restart it.",
+ "permission": "Open this gateway on localhost or allow remote package installation before updating."
+ }
+ },
"remote": {
"compatibility": {
"title": "Version check",
@@ -942,10 +1044,16 @@
"installedCount_other": "{{count}} CLIs installed"
},
"about": {
+ "updateNotice": "Update available",
+ "viewUpdateDetails": "View details",
+ "updateNow": "Update",
+ "dismissUpdate": "Dismiss update notice",
+ "updateInstructions": "Update on the computer running nanobot, using your original installation method. This page won’t install or restart anything.",
+ "installationGuide": "Installation guide",
"documentation": "Documentation",
"sourceCode": "Source code",
"reportIssue": "Report an issue",
- "version": "Version",
+ "version": "Version & updates",
"checking": "Checking...",
"checkForUpdates": "Check for updates",
"upToDate": "You're up to date",
diff --git a/webui/src/i18n/locales/es/common.json b/webui/src/i18n/locales/es/common.json
index f481dcb65..159d257c8 100644
--- a/webui/src/i18n/locales/es/common.json
+++ b/webui/src/i18n/locales/es/common.json
@@ -1,4 +1,106 @@
{
+ "updates": {
+ "guide": {
+ "entry": "Actualizar mediante {{method}}",
+ "methods": {
+ "managed": "el instalador de nanobot",
+ "uv": "uv",
+ "pipx": "pipx",
+ "pip": "pip",
+ "source": "el código fuente",
+ "container": "el despliegue del contenedor",
+ "system": "el gestor del sistema"
+ },
+ "host": "Gateway: {{host}}",
+ "where": "Usa un terminal de este equipo con la cuenta que hizo la instalación. Para un gateway remoto, usa SSH o su consola, no el equipo del navegador. Los comandos solo se copian; esta página no los ejecuta.",
+ "containerHost": "Este nombre y ruta pertenecen al contenedor, no al host de despliegue. Usa el servidor o panel que lo administra; no actualices dentro del contenedor en ejecución.",
+ "beforeTitle": "Preparar y detener",
+ "before": "Termina las tareas y respalda configuración, chats y espacios de trabajo. Detén todos los gateways de esta instalación con su lanzador o gestor de servicios original. Conserva las rutas de perfil y los parámetros de inicio.",
+ "installTitle": "Actualizar en {{shell}}",
+ "inspectCommand": "Inspeccionar esta instalación",
+ "updateCommand": "Comando de actualización",
+ "versionCommand": "Versión instalada",
+ "reasons": {
+ "restart": "El paquete objetivo ya está instalado. No lo reinstales. Detén el gateway antiguo, inicia con el lanzador y perfil originales y comprueba la versión activa.",
+ "registry": "Mantén el registro y las credenciales originales. El gestor conserva extras y restricciones, por lo que puede elegir otra versión estable permitida distinta del aviso. Revisa la salida; no fuerces una actualización fallida.",
+ "preview": "Las Preview se distribuyen en GitHub, no necesariamente en tu índice. Elige el wheel de esta versión para el Python y la plataforma del gateway, verifica su checksum e instálalo con el gestor y extras originales. Un upgrade genérico no garantiza esta Preview.",
+ "policy": "Hay una versión fijada, archivo de bloqueo, origen fijo, restricción u opciones desconocidas. Inspecciona y sigue el proceso original, conservando extras y paquetes inyectados. No elimines las restricciones.",
+ "extras": "Este entorno pip no registra los extras originales. Inspecciona el paquete y reutiliza el comando pip original con --upgrade y la versión deseada, manteniendo extras y opciones del índice. No se ofrece un comando supuesto.",
+ "manager": "No se pudo confirmar el gestor o la estructura del entorno. Usa la cuenta y configuración originales para apuntar a la ruta indicada; no uses otro pip o nanobot del PATH.",
+ "source": "Inspecciona el repositorio, conserva los cambios locales y confirma la rama o revisión. Sigue el flujo del repositorio para actualizar código, dependencias y builds WebUI/TUI. No sustituyas una instalación editable por PyPI.",
+ "container": "En el proyecto Compose o panel original, elige la etiqueta o digest, descarga o construye la imagen y recrea solo el servicio nanobot con sus montajes, secretos y puertos existentes. Respalda los volúmenes; nunca los elimines.",
+ "system": "Usa el gestor de paquetes del sistema o contacta al administrador. No uses sudo pip ni eludas la gestión del Python del sistema.",
+ "review": "La instalación o revisión cambió. Cierra y vuelve a comprobar antes de copiar un comando."
+ },
+ "verifyTitle": "Reiniciar y verificar",
+ "verify": "Inicia con el mismo lanzador y perfil. El comando solo comprueba archivos instalados. Reconecta al mismo gateway, compara su versión activa con v{{version}} y verifica que sigan tus chats y ajustes.",
+ "check": "Comprobar gateway en ejecución",
+ "verified": "Confirmado: este gateway ejecuta v{{version}}.",
+ "observed": "El gateway informa v{{version}}, no v{{target}}. Revisa la salida y reinicia la misma instalación; actualizar archivos no actualiza un proceso en ejecución.",
+ "checkFailed": "No se pudo leer la versión activa. Reconecta al mismo gateway e inténtalo de nuevo; no se ha confirmado el éxito."
+ },
+ "automaticRecovery": "Si la actualización falla, nanobot intentará recuperar el servicio con el programa anterior cuando sea seguro. Los datos de los chats no se revertirán.",
+ "restored": "Versión anterior restaurada",
+ "restoredDescription": "La actualización no se completó. v{{version}} vuelve a funcionar. No se han restaurado copias anteriores de tu configuración ni de tus chats.",
+ "recoveryBeforeInstall": "La actualización se detuvo antes de instalar. No se modificaron archivos del paquete. Recupera la actualización guardada para continuar.",
+ "channel": {
+ "settings": "Ajustes de actualización",
+ "receivePreview": "Recibir versiones preliminares",
+ "previewWarning": "Esta versión preliminar puede tener errores.",
+ "preview": "Preliminar",
+ "hint": "Prueba las novedades antes.",
+ "saving": "Guardando…",
+ "saved": "Preferencia de actualización guardada",
+ "ahead": "Esta versión es más reciente que la del canal seleccionado. No se instalará una versión anterior.",
+ "waiting_stable": "Las actualizaciones preliminares están desactivadas. Usa esta versión hasta que haya una versión estable más reciente.",
+ "withdrawn": "Esta versión preliminar fue retirada. Actualiza cuando haya una versión más reciente; no instales una anterior sobre tus datos actuales.",
+ "unavailable": "No se pudo verificar este canal. Puede que aún no esté disponible. Comprueba la conexión y vuelve a intentarlo.",
+ "publishing": "La versión aún se está publicando. Vuelve a comprobarlo más tarde.",
+ "unsupported": "No hay una actualización compatible con esta versión de Python y plataforma.",
+ "releaseNotes": "Notas de la versión"
+ },
+ "reviewAgain": "Revisar actualización",
+ "reviewAgainDescription": "No se modificaron archivos del paquete. Revisa la actualización antes de confirmar la instalación y el reinicio.",
+ "settleFailed": "No se pudo cerrar la actualización anterior de forma segura. Vuelve a comprobar su estado o sigue las instrucciones de recuperación.",
+ "ownerGuide": "Instrucciones de actualización según tu instalación",
+ "recoveryTitle": "Recuperar en el equipo del gateway",
+ "recoveryDescription": "Ejecuta este comando en el terminal del equipo que ejecuta nanobot. Muestra la actualización guardada antes de pedir confirmación para repararla. Conserva la copia original.",
+ "confirm": "¿Actualizar nanobot ahora?",
+ "reviewingTitle": "Comprobando actualización…",
+ "preparing": "Descargando actualización…",
+ "installing": "Instalando actualización…",
+ "working": "Actualizando nanobot…",
+ "reconnecting": "Reconectando…",
+ "done": "Actualización completada",
+ "failed": "La actualización no terminó",
+ "confirmDescription": "Actualizar a v{{version}} reiniciará nanobot en {{host}}. Finaliza las tareas activas antes de continuar.",
+ "reviewing": "Comprobando la instalación y la versión exacta. No se modifican archivos.",
+ "workingDescription": "Preparando y verificando archivos; después se hará una copia y se reiniciará el gateway seleccionado.",
+ "reconnectingDescription": "Esperando la reconexión del gateway actualizado. No inicies otra actualización.",
+ "delayed": "La reconexión está tardando. El progreso está guardado; puedes cerrar y comprobar más tarde.",
+ "doneDescription": "Ahora se ejecuta v{{version}}.",
+ "preparationFailed": "Falló la preparación o la detención del gateway. No se cambiaron paquetes. Finaliza las tareas y vuelve a comprobar.",
+ "repairRequired": "Falló la instalación o el reinicio. Se conservan la copia y el registro. Usa el procedimiento de recuperación; no inicies otra instalación.",
+ "reviewFailed": "No se pudo verificar la actualización. Comprueba la conexión y el inicio en segundo plano admitido por la instalación original.",
+ "confirmationUnknown": "La solicitud podría haberse aceptado. Comprobando el progreso guardado antes de otra acción.",
+ "statusFailed": "No se pudo leer el registro. Reconecta al mismo gateway y comprueba de nuevo.",
+ "sharedInstallation": "Se reiniciarán los {{count}} gateways activos que comparten esta instalación.",
+ "cancel": "Cancelar",
+ "close": "Cerrar",
+ "hide": "Ocultar",
+ "return": "Listo",
+ "wait": "Espera",
+ "checkAgain": "Comprobar de nuevo",
+ "apply": "Actualizar y reiniciar",
+ "blocked": {
+ "review_changed": "La revisión cambió o caducó. Ciérrala y vuelve a comprobar.",
+ "not_upgrade": "El destino no es una actualización. No se cambiarán archivos.",
+ "installation_owner": "Actualiza con el gestor de paquetes o herramienta de despliegue original.",
+ "installation_policy": "El origen, los extras o las restricciones de versión requieren actualizar con el método de instalación original.",
+ "external_restart": "Esta puerta de enlace no puede reiniciarse aquí. Usa la herramienta de inicio o despliegue original para detenerla, actualizarla y reiniciarla.",
+ "permission": "Abre localhost en el gateway o permite instalar paquetes remotamente."
+ }
+ },
"remote": {
"compatibility": {
"title": "Comprobar versión",
@@ -983,10 +1085,16 @@
"noDescription": "Sin descripción disponible."
},
"about": {
+ "updateNotice": "Actualización disponible",
+ "viewUpdateDetails": "Ver detalles",
+ "updateNow": "Actualizar",
+ "dismissUpdate": "Ocultar aviso",
+ "updateInstructions": "Actualiza en el equipo que ejecuta nanobot con el método de instalación original. Esta página no instala ni reinicia nada.",
+ "installationGuide": "Guía de instalación",
"documentation": "Documentación",
"sourceCode": "Código fuente",
"reportIssue": "Informar de un problema",
- "version": "Versión",
+ "version": "Versión y actualizaciones",
"checking": "Buscando actualizaciones...",
"checkForUpdates": "Buscar actualizaciones",
"upToDate": "Estás al día",
diff --git a/webui/src/i18n/locales/fr/common.json b/webui/src/i18n/locales/fr/common.json
index f79ee66e8..a3350c4e4 100644
--- a/webui/src/i18n/locales/fr/common.json
+++ b/webui/src/i18n/locales/fr/common.json
@@ -1,4 +1,106 @@
{
+ "updates": {
+ "guide": {
+ "entry": "Mettre à jour via {{method}}",
+ "methods": {
+ "managed": "l’installateur nanobot",
+ "uv": "uv",
+ "pipx": "pipx",
+ "pip": "pip",
+ "source": "le code source",
+ "container": "le déploiement du conteneur",
+ "system": "le gestionnaire système"
+ },
+ "host": "Passerelle : {{host}}",
+ "where": "Utilisez le terminal de cette machine avec le compte ayant effectué l’installation. Pour un serveur distant, utilisez SSH ou sa console, pas l’ordinateur du navigateur. Ces commandes sont à copier, jamais exécutées par cette page.",
+ "containerHost": "Ce nom et ce chemin appartiennent au conteneur, pas à son hôte. Utilisez le serveur ou la console qui gère le déploiement ; ne mettez pas à jour dans le conteneur actif.",
+ "beforeTitle": "Préparer et arrêter",
+ "before": "Terminez les tâches et sauvegardez configuration, conversations et espaces de travail. Arrêtez toutes les passerelles partageant cette installation avec leur lanceur ou gestionnaire de services. Conservez les chemins des profils et les paramètres de lancement.",
+ "installTitle": "Mettre à jour dans {{shell}}",
+ "inspectCommand": "Inspecter cette installation",
+ "updateCommand": "Commande de mise à jour",
+ "versionCommand": "Version installée",
+ "reasons": {
+ "restart": "Le paquet cible est déjà installé. Ne le réinstallez pas. Arrêtez l’ancienne passerelle, relancez avec le même lanceur et profil, puis vérifiez la version active.",
+ "registry": "Conservez le registre et les identifiants d’origine. Le gestionnaire conserve les extras et contraintes ; il peut choisir une autre version stable autorisée que celle annoncée. Vérifiez la sortie et ne forcez pas une mise à jour en échec.",
+ "preview": "Les Preview sont distribuées sur GitHub, pas nécessairement dans votre index. Choisissez le wheel adapté au Python et à la plateforme de la passerelle, vérifiez sa somme de contrôle, puis utilisez l’outil d’origine avec les mêmes extras. Une commande upgrade générique ne garantit pas cette Preview.",
+ "policy": "L’installation comporte un épinglage, un verrou, une source fixe, des contraintes ou des options inconnues. Inspectez-la et suivez son processus d’origine, en conservant extras et paquets injectés. Ne supprimez pas les restrictions.",
+ "extras": "Cet environnement pip ne mémorise pas les extras demandés. Inspectez le paquet, puis reprenez la commande pip d’origine avec --upgrade et la version souhaitée, en conservant extras et options d’index. Aucune commande devinée n’est fournie.",
+ "manager": "Le gestionnaire ou la disposition de son environnement n’a pas pu être confirmé. Retrouvez le chemin ci-dessus avec le compte et les réglages d’origine ; n’utilisez pas un autre pip ou nanobot du PATH.",
+ "source": "Inspectez ce dépôt, préservez vos modifications et confirmez la branche ou révision. Suivez ensuite le processus du dépôt pour actualiser code, dépendances et builds WebUI/TUI. Ne remplacez pas une installation éditable par un paquet PyPI.",
+ "container": "Dans le projet Compose ou la console d’origine, choisissez le tag ou digest de l’image, récupérez-la ou construisez-la, puis recréez uniquement le service nanobot avec ses volumes, secrets et ports existants. Sauvegardez les volumes ; ne les supprimez jamais.",
+ "system": "Utilisez le gestionnaire de paquets du système ou contactez l’administrateur. N’utilisez pas sudo pip et ne contournez pas la gestion du Python système.",
+ "review": "L’installation ou la vérification a changé. Fermez cette fenêtre et vérifiez à nouveau avant de copier une commande."
+ },
+ "verifyTitle": "Redémarrer et vérifier",
+ "verify": "Relancez avec le même lanceur et profil. La commande ne vérifie que les fichiers installés. Reconnectez-vous à cette passerelle, comparez sa version active à v{{version}} et vérifiez conversations et réglages.",
+ "check": "Vérifier la passerelle active",
+ "verified": "Confirmé : cette passerelle exécute v{{version}}.",
+ "observed": "La passerelle indique v{{version}}, pas v{{target}}. Vérifiez la sortie d’installation et redémarrez la même installation ; un paquet actualisé ne remplace pas un processus actif.",
+ "checkFailed": "Version active illisible. Reconnectez-vous à la même passerelle et réessayez ; la réussite n’est pas confirmée."
+ },
+ "automaticRecovery": "Si la mise à jour échoue, nanobot tentera de rétablir le service avec le programme précédent si cela est sûr. Les discussions ne seront pas remplacées par une sauvegarde.",
+ "restored": "Version précédente rétablie",
+ "restoredDescription": "La mise à jour a échoué. La version v{{version}} fonctionne à nouveau. Vos paramètres et discussions n’ont pas été remplacés par une sauvegarde.",
+ "recoveryBeforeInstall": "La mise à jour s’est arrêtée avant l’installation. Aucun fichier du paquet n’a été modifié. Reprenez la mise à jour enregistrée pour continuer.",
+ "channel": {
+ "settings": "Réglages des mises à jour",
+ "receivePreview": "Recevoir les préversions",
+ "previewWarning": "Cette préversion peut contenir des erreurs.",
+ "preview": "Préversion",
+ "hint": "Essayez les nouveautés en avance.",
+ "saving": "Enregistrement…",
+ "saved": "Préférence de mise à jour enregistrée",
+ "ahead": "Cette version est plus récente que celle du canal choisi. Aucune version antérieure ne sera installée.",
+ "waiting_stable": "Les préversions sont désactivées. Conservez cette version en attendant une version stable plus récente.",
+ "withdrawn": "Cette préversion a été retirée. Installez une version plus récente dès sa disponibilité ; ne rétrogradez pas avec vos données actuelles.",
+ "unavailable": "Impossible de vérifier ce canal. Il n’est peut-être pas encore disponible. Vérifiez votre connexion et réessayez.",
+ "publishing": "La publication est en cours. Réessayez plus tard.",
+ "unsupported": "Aucune mise à jour compatible avec cette version de Python et cette plateforme.",
+ "releaseNotes": "Notes de version"
+ },
+ "reviewAgain": "Examiner la mise à jour",
+ "reviewAgainDescription": "Aucun fichier du paquet n’a été modifié. Examinez à nouveau la mise à jour avant de confirmer l’installation et le redémarrage.",
+ "settleFailed": "La mise à jour précédente n’a pas pu être clôturée en toute sécurité. Vérifiez à nouveau son état ou suivez les instructions de récupération.",
+ "ownerGuide": "Instructions de mise à jour de votre installation",
+ "recoveryTitle": "Récupérer sur l’ordinateur de la passerelle",
+ "recoveryDescription": "Exécutez cette commande dans un terminal sur l’ordinateur qui héberge nanobot. Elle affiche la mise à jour enregistrée avant de demander confirmation. Conservez la sauvegarde d’origine.",
+ "confirm": "Mettre à jour nanobot ?",
+ "reviewingTitle": "Vérification de la mise à jour…",
+ "preparing": "Téléchargement…",
+ "installing": "Installation…",
+ "working": "Mise à jour de nanobot…",
+ "reconnecting": "Reconnexion…",
+ "done": "Mise à jour terminée",
+ "failed": "Mise à jour inachevée",
+ "confirmDescription": "La mise à jour vers v{{version}} redémarrera nanobot sur {{host}}. Terminez les tâches en cours avant de continuer.",
+ "reviewing": "Vérification de l’installation et de la version exacte. Aucun fichier n’est modifié.",
+ "workingDescription": "Préparation et vérification des fichiers, puis sauvegarde et redémarrage de la passerelle sélectionnée.",
+ "reconnectingDescription": "En attente de reconnexion à la passerelle mise à jour. Ne lancez pas une autre mise à jour.",
+ "delayed": "La reconnexion prend du temps. La progression est enregistrée ; vous pouvez fermer et revérifier plus tard.",
+ "doneDescription": "La version v{{version}} est maintenant exécutée.",
+ "preparationFailed": "La préparation ou l’arrêt a échoué. Aucun paquet n’a été modifié. Terminez les tâches puis revérifiez.",
+ "repairRequired": "L’installation ou le redémarrage a échoué. Sauvegarde et journal sont conservés. Suivez la procédure de récupération, sans lancer une autre installation.",
+ "reviewFailed": "Impossible de vérifier la mise à jour. Vérifiez la connexion et le lancement en arrière-plan pris en charge par l’installation d’origine.",
+ "confirmationUnknown": "La demande a peut-être été acceptée. Vérification de la progression avant toute nouvelle action.",
+ "statusFailed": "Impossible de lire le journal. Reconnectez-vous à la même passerelle puis revérifiez.",
+ "sharedInstallation": "Les {{count}} passerelles actives partageant cette installation seront redémarrées.",
+ "cancel": "Annuler",
+ "close": "Fermer",
+ "hide": "Masquer",
+ "return": "Terminé",
+ "wait": "Patientez",
+ "checkAgain": "Revérifier",
+ "apply": "Mettre à jour et redémarrer",
+ "blocked": {
+ "review_changed": "Cette vérification a changé ou expiré. Fermez puis revérifiez.",
+ "not_upgrade": "La cible n’est pas une mise à niveau. Aucun fichier ne sera modifié.",
+ "installation_owner": "Utilisez le gestionnaire de paquets ou l’outil de déploiement d’origine.",
+ "installation_policy": "La source, les options ou les contraintes de version nécessitent la méthode d’installation d’origine.",
+ "external_restart": "Cette passerelle ne peut pas redémarrer ici. Utilisez son outil de lancement ou de déploiement d’origine pour l’arrêter, la mettre à jour et la redémarrer.",
+ "permission": "Ouvrez localhost sur la passerelle ou autorisez l’installation distante de paquets."
+ }
+ },
"remote": {
"compatibility": {
"title": "Vérification de version",
@@ -983,10 +1085,16 @@
"noDescription": "Aucune description disponible."
},
"about": {
+ "updateNotice": "Mise à jour disponible",
+ "viewUpdateDetails": "Voir les détails",
+ "updateNow": "Mettre à jour",
+ "dismissUpdate": "Masquer cet avis",
+ "updateInstructions": "Mettez à jour sur l’ordinateur qui exécute nanobot, avec la méthode d’installation d’origine. Cette page n’installe ni ne redémarre rien.",
+ "installationGuide": "Guide d’installation",
"documentation": "Documentation",
"sourceCode": "Code source",
"reportIssue": "Signaler un problème",
- "version": "Version",
+ "version": "Version et mises à jour",
"checking": "Recherche de mises à jour...",
"checkForUpdates": "Rechercher les mises à jour",
"upToDate": "Vous êtes à jour",
diff --git a/webui/src/i18n/locales/id/common.json b/webui/src/i18n/locales/id/common.json
index eca6b34d7..74f9a66dc 100644
--- a/webui/src/i18n/locales/id/common.json
+++ b/webui/src/i18n/locales/id/common.json
@@ -1,4 +1,106 @@
{
+ "updates": {
+ "guide": {
+ "entry": "Perbarui melalui {{method}}",
+ "methods": {
+ "managed": "penginstal nanobot",
+ "uv": "uv",
+ "pipx": "pipx",
+ "pip": "pip",
+ "source": "kode sumber",
+ "container": "deployment container",
+ "system": "pengelola paket sistem"
+ },
+ "host": "Gateway: {{host}}",
+ "where": "Gunakan terminal di mesin ini dengan akun instalasi awal. Untuk gateway jarak jauh, gunakan SSH atau konsol server, bukan komputer browser. Perintah hanya disalin; halaman ini tidak menjalankannya.",
+ "containerHost": "Nama dan jalur ini milik bagian dalam container, bukan host deployment. Gunakan server atau panel yang mengelolanya; jangan memperbarui di dalam container yang sedang berjalan.",
+ "beforeTitle": "Siapkan dan hentikan",
+ "before": "Selesaikan tugas dan cadangkan konfigurasi, percakapan, serta data workspace. Hentikan semua gateway yang memakai instalasi ini melalui peluncur atau pengelola layanan awal. Pertahankan jalur profil dan pengaturan peluncuran.",
+ "installTitle": "Perbarui di {{shell}}",
+ "inspectCommand": "Periksa instalasi ini",
+ "updateCommand": "Perintah pembaruan",
+ "versionCommand": "Versi terpasang",
+ "reasons": {
+ "restart": "Paket tujuan sudah terpasang. Jangan instal ulang. Hentikan gateway lama, mulai dengan peluncur dan profil awal, lalu periksa versi yang berjalan.",
+ "registry": "Gunakan sumber paket dan kredensial awal. Pengelola mempertahankan extras dan batasan versi sehingga dapat memilih versi stabil lain dari pemberitahuan. Periksa hasilnya; jangan paksa pembaruan yang gagal.",
+ "preview": "Preview didistribusikan di GitHub dan mungkin tidak tersedia di indeks paket. Pilih wheel yang sesuai dengan Python dan platform gateway, verifikasi checksum lalu instal dengan pengelola awal dan extras yang sama. Perintah upgrade umum tidak menjamin Preview ini.",
+ "policy": "Ada versi yang dipatok, berkas lock, sumber tetap, batasan, atau opsi tak dikenal. Periksa lalu ikuti alur awal dengan mempertahankan extras dan paket yang diinjeksi. Jangan hapus batasannya.",
+ "extras": "Lingkungan pip ini tidak mencatat extras awal. Periksa paket lalu gunakan kembali perintah pip awal dengan --upgrade dan versi tujuan, serta pertahankan extras dan opsi indeks. Tidak ada perintah instalasi hasil tebakan.",
+ "manager": "Program pengelola atau struktur lingkungan tidak dapat dikonfirmasi. Gunakan akun dan pengaturan awal untuk menargetkan jalur di atas; jangan memakai pip atau nanobot lain dari PATH.",
+ "source": "Periksa repositori, pertahankan perubahan lokal dan pastikan branch atau revisi tujuan. Ikuti alur repositori untuk memperbarui kode, dependensi, dan build WebUI/TUI. Jangan ganti instalasi editable dengan paket PyPI.",
+ "container": "Di proyek Compose atau panel awal, pilih tag/digest, tarik atau build image lalu buat ulang hanya layanan nanobot dengan mount, rahasia, dan port yang sama. Cadangkan volume data; jangan pernah menghapusnya.",
+ "system": "Gunakan pengelola paket OS atau hubungi administrator server. Jangan gunakan sudo pip atau lewati pembatasan Python yang dikelola sistem.",
+ "review": "Instalasi atau hasil pemeriksaan telah berubah. Tutup dan periksa lagi sebelum menyalin perintah."
+ },
+ "verifyTitle": "Mulai ulang dan verifikasi",
+ "verify": "Jalankan dengan peluncur dan profil yang sama. Perintah hanya memeriksa berkas terpasang. Sambungkan kembali ke gateway yang sama, bandingkan versi aktif dengan v{{version}}, dan pastikan percakapan serta pengaturan tetap ada.",
+ "check": "Periksa gateway yang berjalan",
+ "verified": "Terkonfirmasi: gateway ini menjalankan v{{version}}.",
+ "observed": "Gateway melaporkan v{{version}}, bukan v{{target}}. Periksa keluaran instalasi dan mulai ulang lingkungan yang sama; pembaruan paket saja tidak memperbarui proses aktif.",
+ "checkFailed": "Versi aktif tidak dapat dibaca. Sambungkan kembali ke gateway yang sama lalu coba lagi; keberhasilan belum dikonfirmasi."
+ },
+ "automaticRecovery": "Jika pembaruan gagal, nanobot akan mencoba memulihkan layanan dengan program sebelumnya jika aman. Data chat tidak akan dikembalikan ke versi lama.",
+ "restored": "Versi sebelumnya dipulihkan",
+ "restoredDescription": "Pembaruan belum selesai. v{{version}} berjalan kembali. Konfigurasi dan chat Anda tidak dikembalikan ke data lama.",
+ "recoveryBeforeInstall": "Pembaruan berhenti sebelum instalasi. Tidak ada berkas paket yang diubah. Pulihkan pembaruan tersimpan untuk melanjutkan.",
+ "channel": {
+ "settings": "Pengaturan pembaruan",
+ "receivePreview": "Terima pembaruan pratinjau",
+ "previewWarning": "Ini adalah versi pratinjau dan mungkin memiliki bug.",
+ "preview": "Pratinjau",
+ "hint": "Coba fitur baru lebih awal.",
+ "saving": "Menyimpan…",
+ "saved": "Preferensi pembaruan disimpan",
+ "ahead": "Versi ini lebih baru dari saluran yang dipilih. Versi lama tidak akan diinstal.",
+ "waiting_stable": "Pembaruan pratinjau dinonaktifkan. Gunakan versi ini sampai versi stabil yang lebih baru tersedia.",
+ "withdrawn": "Pratinjau ini ditarik. Perbarui saat versi baru tersedia; jangan turunkan versi dengan data saat ini.",
+ "unavailable": "Saluran ini belum dapat diverifikasi dan mungkin belum tersedia. Periksa koneksi lalu coba lagi.",
+ "publishing": "Versi masih diterbitkan. Periksa lagi nanti.",
+ "unsupported": "Tidak ada pembaruan yang cocok untuk versi Python dan platform ini.",
+ "releaseNotes": "Catatan rilis"
+ },
+ "reviewAgain": "Tinjau pembaruan",
+ "reviewAgainDescription": "Tidak ada berkas paket yang diubah. Tinjau kembali pembaruan sebelum menyetujui instalasi dan mulai ulang.",
+ "settleFailed": "Pembaruan sebelumnya belum dapat diakhiri dengan aman. Periksa statusnya lagi atau ikuti petunjuk pemulihan.",
+ "ownerGuide": "Petunjuk pembaruan untuk instalasi Anda",
+ "recoveryTitle": "Pulihkan di komputer gateway",
+ "recoveryDescription": "Jalankan perintah ini di terminal komputer yang menjalankan nanobot. Pembaruan tersimpan akan ditampilkan sebelum meminta konfirmasi perbaikan. Simpan cadangan asli.",
+ "confirm": "Perbarui nanobot sekarang?",
+ "reviewingTitle": "Memeriksa pembaruan…",
+ "preparing": "Mengunduh pembaruan…",
+ "installing": "Memasang pembaruan…",
+ "working": "Memperbarui nanobot…",
+ "reconnecting": "Menghubungkan kembali…",
+ "done": "Pembaruan selesai",
+ "failed": "Pembaruan belum selesai",
+ "confirmDescription": "Pembaruan ke v{{version}} akan memulai ulang nanobot di {{host}}. Selesaikan tugas yang berjalan sebelum melanjutkan.",
+ "reviewing": "Memeriksa instalasi dan versi tujuan yang tepat. Tidak ada berkas yang diubah.",
+ "workingDescription": "Menyiapkan dan memverifikasi berkas, lalu mencadangkan dan memulai ulang gateway terpilih.",
+ "reconnectingDescription": "Menunggu gateway yang diperbarui terhubung kembali. Jangan mulai pembaruan lain.",
+ "delayed": "Penyambungan memerlukan waktu lebih lama. Progres tersimpan; Anda dapat menutup dan memeriksa lagi nanti.",
+ "doneDescription": "Kini menjalankan v{{version}}.",
+ "preparationFailed": "Persiapan atau penghentian gateway gagal. Paket belum diubah. Selesaikan tugas lalu periksa kembali.",
+ "repairRequired": "Instalasi atau mulai ulang gagal. Cadangan dan catatan disimpan. Ikuti prosedur pemulihan; jangan mulai instalasi lain.",
+ "reviewFailed": "Pembaruan tidak dapat diverifikasi. Periksa koneksi dan peluncur latar belakang yang didukung instalasi asal.",
+ "confirmationUnknown": "Permintaan mungkin telah diterima. Memeriksa progres tersimpan sebelum tindakan berikutnya.",
+ "statusFailed": "Catatan pembaruan tidak dapat dibaca. Sambungkan kembali ke gateway yang sama lalu periksa.",
+ "sharedInstallation": "{{count}} gateway aktif yang berbagi instalasi ini akan dimulai ulang.",
+ "cancel": "Batal",
+ "close": "Tutup",
+ "hide": "Sembunyikan",
+ "return": "Selesai",
+ "wait": "Tunggu",
+ "checkAgain": "Periksa lagi",
+ "apply": "Perbarui dan mulai ulang",
+ "blocked": {
+ "review_changed": "Tinjauan berubah atau kedaluwarsa. Tutup lalu periksa lagi.",
+ "not_upgrade": "Versi tujuan bukan peningkatan. Berkas tidak akan diubah.",
+ "installation_owner": "Perbarui dengan pengelola paket atau alat penerapan asal.",
+ "installation_policy": "Sumber, ekstra, atau batasan versi memerlukan pembaruan melalui metode pemasangan asal.",
+ "external_restart": "Gateway ini tidak dapat dimulai ulang di sini. Gunakan alat peluncuran atau penerapan asal untuk menghentikan, memperbarui, dan memulainya ulang.",
+ "permission": "Buka localhost pada gateway atau izinkan pemasangan paket jarak jauh."
+ }
+ },
"remote": {
"compatibility": {
"title": "Periksa versi",
@@ -983,10 +1085,16 @@
"noDescription": "Tidak ada deskripsi."
},
"about": {
+ "updateNotice": "Pembaruan tersedia",
+ "viewUpdateDetails": "Lihat detail",
+ "updateNow": "Perbarui",
+ "dismissUpdate": "Tutup pemberitahuan",
+ "updateInstructions": "Perbarui di komputer yang menjalankan nanobot dengan metode instalasi semula. Halaman ini tidak akan memasang atau memulai ulang apa pun.",
+ "installationGuide": "Panduan instalasi",
"documentation": "Dokumentasi",
"sourceCode": "Kode sumber",
"reportIssue": "Laporkan masalah",
- "version": "Versi",
+ "version": "Versi & pembaruan",
"checking": "Memeriksa pembaruan...",
"checkForUpdates": "Periksa pembaruan",
"upToDate": "Anda sudah menggunakan versi terbaru",
diff --git a/webui/src/i18n/locales/ja/common.json b/webui/src/i18n/locales/ja/common.json
index 63cc66b39..170037325 100644
--- a/webui/src/i18n/locales/ja/common.json
+++ b/webui/src/i18n/locales/ja/common.json
@@ -1,4 +1,106 @@
{
+ "updates": {
+ "guide": {
+ "entry": "{{method}}で更新",
+ "methods": {
+ "managed": "nanobot インストーラー",
+ "uv": "uv",
+ "pipx": "pipx",
+ "pip": "pip",
+ "source": "ソースコード",
+ "container": "コンテナーのデプロイ",
+ "system": "システムパッケージ管理"
+ },
+ "host": "ゲートウェイ:{{host}}",
+ "where": "このマシンのターミナルで、元のインストールユーザーとして操作してください。リモートの場合は SSH またはサーバーのコンソールを使います。ブラウザー側のマシンではありません。コマンドはコピー専用で、自動実行されません。",
+ "containerHost": "これはコンテナー内の名前とパスであり、デプロイ先ホストではありません。管理サーバーやホスティング画面で操作し、稼働中のコンテナー内で更新しないでください。",
+ "beforeTitle": "準備して停止",
+ "before": "タスクを終了し、設定・チャット・ワークスペースをバックアップします。同じ環境を使うすべてのゲートウェイを元のランチャーやサービス管理から停止し、プロファイルのパスと起動設定を保持してください。",
+ "installTitle": "{{shell}} で更新",
+ "inspectCommand": "インストールを確認",
+ "updateCommand": "更新コマンド",
+ "versionCommand": "インストール済みバージョン",
+ "reasons": {
+ "restart": "対象バージョンはインストール済みです。再インストールせず、古いゲートウェイを停止して元のランチャーとプロファイルで再起動し、実行中のバージョンを確認してください。",
+ "registry": "元のレジストリと認証情報を使います。管理ツールは記録された extras とバージョン制約を保持するため、通知とは異なる安定版を選ぶ場合があります。出力を確認し、失敗時に強制更新しないでください。",
+ "preview": "Preview は GitHub で配布され、パッケージ索引にはない場合があります。ゲートウェイの Python・プラットフォームに合う wheel を選び、チェックサムを検証して、元のツールと同じ extras でインストールしてください。一般的な upgrade ではこの Preview を保証できません。",
+ "policy": "固定バージョン、ロック、固定ソース、制約、または不明な設定があります。以下を確認し、extras と追加パッケージを保持して元の手順で更新してください。制約を勝手に解除しないでください。",
+ "extras": "この pip 環境には元の extras が記録されていません。パッケージを確認し、元の pip コマンドに --upgrade と対象バージョンを指定して、extras と索引設定を保持してください。推測した更新コマンドは表示しません。",
+ "manager": "管理ツールまたは環境の構成を確認できません。元のアカウントと設定で上記のパスを指定してください。PATH 上の別の pip や nanobot は使わないでください。",
+ "source": "変更を保持して対象ブランチ・リビジョンを確認後、リポジトリの手順でコード、依存関係、WebUI/TUI を更新・ビルドしてください。編集可能な環境を PyPI パッケージで置き換えないでください。",
+ "container": "元の Compose プロジェクトや管理画面で対象イメージを選び、取得・ビルド後、既存のマウント・秘密情報・ポートを維持して nanobot サービスだけを再作成します。データボリュームをバックアップし、削除しないでください。",
+ "system": "OS のパッケージ管理を使うか管理者に依頼してください。sudo pip やシステム Python の管理制限の回避はしないでください。",
+ "review": "環境または更新の確認内容が変わりました。閉じて再確認してからコマンドをコピーしてください。"
+ },
+ "verifyTitle": "同じ方法で起動・確認",
+ "verify": "同じランチャーとプロファイルで起動します。コマンドはインストール済みファイルだけを確認します。同じゲートウェイに再接続し、実行中のバージョンを v{{version}} と比較してチャットと設定を確認してください。",
+ "check": "実行中のゲートウェイを確認",
+ "verified": "確認済み:v{{version}} が稼働中です。",
+ "observed": "稼働中は v{{version}} で、通知の v{{target}} とは異なります。インストール結果を確認し、同じ環境を再起動してください。ファイルの更新だけではプロセスは更新されません。",
+ "checkFailed": "実行中のバージョンを取得できません。同じゲートウェイに再接続して再試行してください。更新成功は未確認です。"
+ },
+ "automaticRecovery": "更新に失敗した場合、安全であれば以前のプログラムを使ってサービスの自動復旧を試みます。チャットデータは巻き戻しません。",
+ "restored": "以前のバージョンに復旧しました",
+ "restoredDescription": "更新は完了しませんでした。v{{version}} が再び動作しています。設定やチャットのデータは巻き戻していません。",
+ "recoveryBeforeInstall": "インストール前に更新が停止しました。パッケージのファイルは変更されていません。保存済みの更新を復旧して続行してください。",
+ "channel": {
+ "settings": "更新設定",
+ "receivePreview": "プレビュー更新を受け取る",
+ "previewWarning": "これはプレビュー版です。不具合がある場合があります。",
+ "preview": "プレビュー版",
+ "hint": "新機能をいち早く体験。",
+ "saving": "保存中…",
+ "saved": "更新設定を保存しました",
+ "ahead": "現在のバージョンは選択したチャンネルより新しいため、旧バージョンはインストールしません。",
+ "waiting_stable": "プレビュー更新を停止しました。新しい安定版が公開されるまで現在のバージョンを利用できます。",
+ "withdrawn": "このプレビュー版は撤回されました。修正版が公開されたら更新してください。現在のデータに旧版を上書きしないでください。",
+ "unavailable": "チャンネルを確認できません。まだ公開されていない可能性があります。接続を確認して再試行してください。",
+ "publishing": "リリースの公開中です。しばらくしてから再確認してください。",
+ "unsupported": "この Python バージョンとプラットフォームに対応する更新はありません。",
+ "releaseNotes": "リリースノート"
+ },
+ "reviewAgain": "更新内容を再確認",
+ "reviewAgainDescription": "パッケージのファイルは変更されていません。更新内容を再確認してから、インストールと再起動を承認してください。",
+ "settleFailed": "前回の更新を安全に終了できませんでした。状態を再確認するか、復旧手順に従ってください。",
+ "ownerGuide": "インストール方法別の更新手順",
+ "recoveryTitle": "ゲートウェイのコンピュータで復旧",
+ "recoveryDescription": "nanobot を実行しているコンピュータの端末で実行してください。保存済みの更新を表示し、修復前に確認します。元のバックアップを保持してください。",
+ "confirm": "nanobot を更新しますか?",
+ "reviewingTitle": "更新を確認中…",
+ "preparing": "更新をダウンロード中…",
+ "installing": "更新をインストール中…",
+ "working": "nanobot を更新中…",
+ "reconnecting": "再接続中…",
+ "done": "更新完了",
+ "failed": "更新が完了しませんでした",
+ "confirmDescription": "v{{version}} に更新すると {{host}} の nanobot が再起動します。実行中のタスクを終了してから続けてください。",
+ "reviewing": "インストール環境と対象バージョンを確認しています。ファイルは変更しません。",
+ "workingDescription": "ファイルを準備・検証し、バックアップ後に選択したゲートウェイを再起動します。",
+ "reconnectingDescription": "更新したゲートウェイへの再接続を待っています。更新を重複して開始しないでください。",
+ "delayed": "再接続に時間がかかっています。進行状況は保存済みです。閉じて後で確認できます。",
+ "doneDescription": "現在 v{{version}} が動作しています。",
+ "preparationFailed": "準備またはゲートウェイの停止に失敗しました。パッケージは未変更です。タスクを終了して再確認してください。",
+ "repairRequired": "インストールまたは再起動に失敗しました。バックアップと記録は保持されています。別の更新を開始せず、復旧手順に従ってください。",
+ "reviewFailed": "更新を検証できませんでした。接続と、元のインストール環境が対応するバックグラウンド起動方法を確認してください。",
+ "confirmationUnknown": "要求は受理済みの可能性があります。再実行前に保存済みの進行状況を確認しています。",
+ "statusFailed": "更新記録を読めません。同じゲートウェイに再接続して確認してください。",
+ "sharedInstallation": "このインストールを共有する実行中のゲートウェイ {{count}} 個を再起動します。",
+ "cancel": "キャンセル",
+ "close": "閉じる",
+ "hide": "隠す",
+ "return": "完了",
+ "wait": "お待ちください",
+ "checkAgain": "再確認",
+ "apply": "更新して再起動",
+ "blocked": {
+ "review_changed": "確認内容が変わったか期限切れです。閉じて再確認してください。",
+ "not_upgrade": "対象はアップグレードではありません。ファイルは変更しません。",
+ "installation_owner": "元のパッケージ管理・デプロイツールで更新してください。",
+ "installation_policy": "インストール元、追加依存関係、バージョン制約に従い、元の方法で更新してください。",
+ "external_restart": "このゲートウェイはここでは再起動できません。元の起動方法またはデプロイツールで停止・更新・再起動してください。",
+ "permission": "ゲートウェイの localhost を開くか、リモートパッケージインストールを許可してください。"
+ }
+ },
"remote": {
"compatibility": {
"title": "バージョン確認",
@@ -983,10 +1085,16 @@
"noDescription": "説明はありません。"
},
"about": {
+ "updateNotice": "アップデートがあります",
+ "viewUpdateDetails": "詳細を見る",
+ "updateNow": "更新",
+ "dismissUpdate": "更新通知を閉じる",
+ "updateInstructions": "nanobot を実行しているコンピューターで、元のインストール方法を使って更新してください。このページではインストールや再起動は行いません。",
+ "installationGuide": "インストールガイド",
"documentation": "公式ドキュメント",
"sourceCode": "ソースコード",
"reportIssue": "問題を報告",
- "version": "バージョン",
+ "version": "バージョンと更新",
"checking": "確認中...",
"checkForUpdates": "アップデートを確認",
"upToDate": "最新の状態です",
diff --git a/webui/src/i18n/locales/ko/common.json b/webui/src/i18n/locales/ko/common.json
index a9a81dedd..8364132d8 100644
--- a/webui/src/i18n/locales/ko/common.json
+++ b/webui/src/i18n/locales/ko/common.json
@@ -1,4 +1,106 @@
{
+ "updates": {
+ "guide": {
+ "entry": "{{method}}로 업데이트",
+ "methods": {
+ "managed": "nanobot 설치 프로그램",
+ "uv": "uv",
+ "pipx": "pipx",
+ "pip": "pip",
+ "source": "소스 코드",
+ "container": "컨테이너 배포",
+ "system": "시스템 패키지 관리자"
+ },
+ "host": "게이트웨이: {{host}}",
+ "where": "이 컴퓨터의 터미널에서 원래 설치 계정으로 실행하세요. 원격 게이트웨이는 브라우저 컴퓨터가 아닌 SSH 또는 서버 콘솔을 사용하세요. 명령은 복사만 하며 자동 실행되지 않습니다.",
+ "containerHost": "컨테이너 내부의 이름과 경로이며 배포 호스트가 아닙니다. 이를 관리하는 서버나 호스팅 콘솔에서 작업하세요. 실행 중인 컨테이너 안에서 업데이트하지 마세요.",
+ "beforeTitle": "준비하고 서비스 중지",
+ "before": "작업을 마치고 설정, 채팅, 작업 공간 데이터를 백업하세요. 같은 설치를 쓰는 모든 게이트웨이를 기존 실행기나 서비스 관리자로 중지하세요. 프로필 경로와 실행 설정은 유지하세요.",
+ "installTitle": "{{shell}}에서 업데이트",
+ "inspectCommand": "설치 확인",
+ "updateCommand": "업데이트 명령",
+ "versionCommand": "설치된 버전",
+ "reasons": {
+ "restart": "대상 패키지는 이미 설치되어 있습니다. 다시 설치하지 마세요. 이전 게이트웨이를 중지하고 기존 실행기와 프로필로 재시작한 뒤 실행 버전을 확인하세요.",
+ "registry": "기존 저장소와 인증 정보를 사용하세요. 관리자는 기록된 extras와 버전 제한을 유지하므로 알림과 다른 안정 버전을 선택할 수 있습니다. 출력을 확인하고 실패한 업데이트를 강제하지 마세요.",
+ "preview": "Preview는 GitHub로 배포되며 패키지 저장소에 없을 수 있습니다. 게이트웨이의 Python과 플랫폼에 맞는 wheel을 선택하고 체크섬을 검증한 뒤 기존 도구와 extras로 설치하세요. 일반 upgrade 명령으로 해당 Preview를 보장할 수 없습니다.",
+ "policy": "버전 고정, 잠금 파일, 고정 소스, 버전 제한 또는 알 수 없는 옵션이 있습니다. 아래에서 확인하고 extras 및 주입된 패키지를 유지하며 기존 절차로 업데이트하세요. 제한을 임의로 해제하지 마세요.",
+ "extras": "이 pip 환경은 원래 extras를 기록하지 않습니다. 패키지를 확인한 뒤 기존 pip 명령에 --upgrade와 대상 버전을 추가하고 extras 및 저장소 옵션을 유지하세요. 추측한 설치 명령은 제공하지 않습니다.",
+ "manager": "패키지 관리자나 환경 구조를 확인하지 못했습니다. 원래 계정과 설정으로 위 경로를 지정하세요. PATH의 다른 pip나 nanobot을 사용하지 마세요.",
+ "source": "로컬 변경을 보존하고 대상 브랜치나 리비전을 확인한 뒤 저장소 절차에 따라 코드, 의존성, WebUI/TUI를 업데이트하고 빌드하세요. 편집 가능한 환경을 PyPI 패키지로 대체하지 마세요.",
+ "container": "기존 Compose 프로젝트나 관리 콘솔에서 이미지 태그 또는 다이제스트를 선택하고 가져오거나 빌드한 뒤 기존 마운트, 비밀 정보, 포트를 유지해 nanobot 서비스만 재생성하세요. 데이터 볼륨은 백업하고 삭제하지 마세요.",
+ "system": "OS 패키지 관리자를 사용하거나 서버 관리자에게 요청하세요. sudo pip나 시스템 Python 관리 제한 우회는 사용하지 마세요.",
+ "review": "설치 또는 검토 내용이 변경되었습니다. 창을 닫고 다시 확인한 뒤 명령을 복사하세요."
+ },
+ "verifyTitle": "재시작하고 검증",
+ "verify": "같은 실행기와 프로필로 시작하세요. 명령은 설치 파일만 확인합니다. 동일한 게이트웨이에 재접속해 실행 버전을 v{{version}}과 비교하고 채팅 및 설정이 남아 있는지 확인하세요.",
+ "check": "실행 중인 게이트웨이 확인",
+ "verified": "확인됨: 이 게이트웨이는 v{{version}} 실행 중입니다.",
+ "observed": "게이트웨이는 알림의 v{{target}}이 아닌 v{{version}}을 보고합니다. 설치 출력을 확인하고 동일한 환경을 재시작하세요. 패키지 업데이트만으로 실행 프로세스는 바뀌지 않습니다.",
+ "checkFailed": "실행 버전을 읽지 못했습니다. 동일한 게이트웨이에 재접속하고 다시 시도하세요. 업데이트 성공은 아직 확인되지 않았습니다."
+ },
+ "automaticRecovery": "업데이트 실패 시 안전한 경우 이전 프로그램으로 서비스를 자동 복구합니다. 채팅 데이터는 이전 상태로 되돌리지 않습니다.",
+ "restored": "이전 버전 복구됨",
+ "restoredDescription": "업데이트가 완료되지 않아 v{{version}}이 다시 실행 중입니다. 설정과 채팅 기록은 이전 데이터로 되돌리지 않았습니다.",
+ "recoveryBeforeInstall": "설치 전에 업데이트가 중단되었습니다. 패키지 파일은 변경되지 않았습니다. 저장된 업데이트를 복구하여 계속하세요.",
+ "channel": {
+ "settings": "업데이트 설정",
+ "receivePreview": "미리 보기 업데이트 받기",
+ "previewWarning": "미리 보기 버전이며 오류가 있을 수 있습니다.",
+ "preview": "미리 보기",
+ "hint": "새 기능을 미리 사용해 보세요.",
+ "saving": "저장 중…",
+ "saved": "업데이트 설정 저장됨",
+ "ahead": "현재 버전이 선택한 채널보다 최신입니다. 이전 버전을 설치하지 않습니다.",
+ "waiting_stable": "미리 보기 업데이트를 중단했습니다. 더 새로운 안정판이 나올 때까지 현재 버전을 사용하세요.",
+ "withdrawn": "이 미리 보기 버전은 철회되었습니다. 새 버전이 나오면 업데이트하세요. 현재 데이터에 이전 버전을 덮어쓰지 마세요.",
+ "unavailable": "채널을 확인할 수 없습니다. 아직 제공되지 않을 수 있습니다. 연결을 확인하고 다시 시도하세요.",
+ "publishing": "릴리스를 게시 중입니다. 나중에 다시 확인하세요.",
+ "unsupported": "이 Python 버전과 플랫폼에 맞는 업데이트가 없습니다.",
+ "releaseNotes": "릴리스 노트"
+ },
+ "reviewAgain": "업데이트 다시 검토",
+ "reviewAgainDescription": "패키지 파일은 변경되지 않았습니다. 설치 및 재시작을 승인하기 전에 업데이트를 다시 검토하세요.",
+ "settleFailed": "이전 업데이트를 안전하게 종료하지 못했습니다. 상태를 다시 확인하거나 복구 안내를 따르세요.",
+ "ownerGuide": "설치 방식별 업데이트 안내",
+ "recoveryTitle": "게이트웨이 컴퓨터에서 복구",
+ "recoveryDescription": "nanobot이 실행 중인 컴퓨터의 터미널에서 실행하세요. 저장된 업데이트를 표시한 후 복구 여부를 확인합니다. 원본 백업을 보관하세요.",
+ "confirm": "nanobot을 업데이트할까요?",
+ "reviewingTitle": "업데이트 확인 중…",
+ "preparing": "업데이트 다운로드 중…",
+ "installing": "업데이트 설치 중…",
+ "working": "nanobot 업데이트 중…",
+ "reconnecting": "다시 연결 중…",
+ "done": "업데이트 완료",
+ "failed": "업데이트를 완료하지 못했습니다",
+ "confirmDescription": "v{{version}} 업데이트 후 {{host}}의 nanobot이 다시 시작됩니다. 진행 중인 작업을 먼저 끝내세요.",
+ "reviewing": "설치 환경과 대상 버전을 확인합니다. 파일은 변경하지 않습니다.",
+ "workingDescription": "파일을 준비하고 검증한 뒤 백업하고 선택한 게이트웨이를 다시 시작합니다.",
+ "reconnectingDescription": "업데이트된 게이트웨이에 다시 연결하고 있습니다. 업데이트를 중복 실행하지 마세요.",
+ "delayed": "다시 연결하는 데 시간이 걸립니다. 진행 상황은 저장되어 있으니 닫고 나중에 확인할 수 있습니다.",
+ "doneDescription": "현재 v{{version}}이 실행 중입니다.",
+ "preparationFailed": "준비 또는 게이트웨이 종료에 실패했습니다. 패키지 파일은 변경되지 않았습니다. 작업을 마친 후 다시 확인하세요.",
+ "repairRequired": "설치 또는 재시작에 실패했습니다. 백업과 기록은 보존됩니다. 다른 설치를 시작하지 말고 업데이트 복구 절차를 따르세요.",
+ "reviewFailed": "업데이트를 검증하지 못했습니다. 연결과 원래 설치 환경이 지원하는 백그라운드 실행 방식을 확인하세요.",
+ "confirmationUnknown": "요청이 수락되었을 수 있습니다. 다시 실행하기 전에 저장된 진행 상황을 확인합니다.",
+ "statusFailed": "업데이트 기록을 읽지 못했습니다. 같은 게이트웨이에 다시 연결해 확인하세요.",
+ "sharedInstallation": "이 설치를 공유하는 실행 중인 게이트웨이 {{count}}개가 다시 시작됩니다.",
+ "cancel": "취소",
+ "close": "닫기",
+ "hide": "접기",
+ "return": "완료",
+ "wait": "잠시 기다려 주세요",
+ "checkAgain": "다시 확인",
+ "apply": "업데이트 및 재시작",
+ "blocked": {
+ "review_changed": "검토 내용이 바뀌었거나 만료되었습니다. 닫고 다시 확인하세요.",
+ "not_upgrade": "대상 버전은 업그레이드가 아닙니다. 파일을 변경하지 않습니다.",
+ "installation_owner": "원래 패키지 관리자 또는 배포 도구로 업데이트하세요.",
+ "installation_policy": "설치 출처, 추가 종속성 또는 버전 제약에 따라 원래 설치 방식으로 업데이트하세요.",
+ "external_restart": "이 게이트웨이는 여기서 재시작할 수 없습니다. 원래 실행 방식이나 배포 도구로 중지, 업데이트 및 재시작하세요.",
+ "permission": "게이트웨이의 localhost를 열거나 원격 패키지 설치를 허용하세요."
+ }
+ },
"remote": {
"compatibility": {
"title": "버전 확인",
@@ -983,10 +1085,16 @@
"noDescription": "설명이 없습니다."
},
"about": {
+ "updateNotice": "업데이트가 있습니다",
+ "viewUpdateDetails": "자세히 보기",
+ "updateNow": "업데이트",
+ "dismissUpdate": "업데이트 알림 닫기",
+ "updateInstructions": "nanobot이 실행 중인 컴퓨터에서 기존 설치 방법으로 업데이트하세요. 이 페이지에서는 설치하거나 다시 시작하지 않습니다.",
+ "installationGuide": "설치 안내",
"documentation": "공식 문서",
"sourceCode": "소스 코드",
"reportIssue": "문제 신고",
- "version": "버전",
+ "version": "버전 및 업데이트",
"checking": "확인 중...",
"checkForUpdates": "업데이트 확인",
"upToDate": "최신 버전입니다",
diff --git a/webui/src/i18n/locales/pt-BR/common.json b/webui/src/i18n/locales/pt-BR/common.json
index 7df31efbc..f03117d9c 100644
--- a/webui/src/i18n/locales/pt-BR/common.json
+++ b/webui/src/i18n/locales/pt-BR/common.json
@@ -1,4 +1,106 @@
{
+ "updates": {
+ "guide": {
+ "entry": "Atualizar via {{method}}",
+ "methods": {
+ "managed": "instalador do nanobot",
+ "uv": "uv",
+ "pipx": "pipx",
+ "pip": "pip",
+ "source": "código-fonte",
+ "container": "implantação do contêiner",
+ "system": "gerenciador do sistema"
+ },
+ "host": "Gateway: {{host}}",
+ "where": "Use o terminal desta máquina com a conta da instalação original. Para um gateway remoto, use SSH ou o console do servidor, não o computador do navegador. Os comandos são apenas copiados; esta página não os executa.",
+ "containerHost": "Este nome e caminho pertencem ao contêiner, não ao host de implantação. Use o servidor ou painel que o gerencia; não atualize dentro do contêiner em execução.",
+ "beforeTitle": "Preparar e parar",
+ "before": "Conclua as tarefas e faça backup das configurações, conversas e espaços de trabalho. Pare todos os gateways desta instalação pelo iniciador ou gerenciador de serviços original. Preserve os caminhos de perfil e parâmetros de início.",
+ "installTitle": "Atualizar no {{shell}}",
+ "inspectCommand": "Inspecionar esta instalação",
+ "updateCommand": "Comando de atualização",
+ "versionCommand": "Versão instalada",
+ "reasons": {
+ "restart": "O pacote de destino já está instalado. Não reinstale. Pare o gateway antigo, reinicie com o iniciador e perfil originais e confira a versão em execução.",
+ "registry": "Use o registro e as credenciais originais. O gerenciador preserva extras e restrições e pode selecionar outra versão estável permitida, diferente do aviso. Confira a saída e não force uma atualização com falha.",
+ "preview": "As Preview são distribuídas no GitHub, não necessariamente no seu índice. Selecione o wheel adequado ao Python e à plataforma do gateway, verifique o checksum e instale pelo gerenciador original com os mesmos extras. Um upgrade genérico não garante esta Preview.",
+ "policy": "Há versão fixada, arquivo de trava, origem fixa, restrição ou opções desconhecidas. Inspecione e siga o fluxo original, preservando extras e pacotes injetados. Não remova as restrições.",
+ "extras": "Este ambiente pip não registra os extras originais. Inspecione o pacote e reutilize o comando pip original com --upgrade e a versão desejada, preservando extras e opções do índice. Não fornecemos um comando adivinhado.",
+ "manager": "Não foi possível confirmar o gerenciador ou a estrutura do ambiente. Use a conta e as configurações originais para acessar o caminho acima; não use outro pip ou nanobot do PATH.",
+ "source": "Inspecione o repositório, preserve alterações locais e confirme a branch ou revisão. Siga o fluxo do repositório para atualizar código, dependências e builds WebUI/TUI. Não substitua uma instalação editável por PyPI.",
+ "container": "No projeto Compose ou painel original, escolha a tag ou digest, baixe ou construa a imagem e recrie apenas o serviço nanobot com os mesmos volumes, segredos e portas. Faça backup dos volumes; nunca os exclua.",
+ "system": "Use o gerenciador de pacotes do sistema ou contate o administrador. Não use sudo pip nem contorne o gerenciamento do Python do sistema.",
+ "review": "A instalação ou revisão mudou. Feche e verifique novamente antes de copiar um comando."
+ },
+ "verifyTitle": "Reiniciar e verificar",
+ "verify": "Inicie com o mesmo iniciador e perfil. O comando só verifica arquivos instalados. Reconecte ao mesmo gateway, compare a versão em execução com v{{version}} e confira as conversas e configurações.",
+ "check": "Verificar gateway em execução",
+ "verified": "Confirmado: este gateway executa v{{version}}.",
+ "observed": "O gateway informa v{{version}}, não v{{target}}. Confira a saída e reinicie a mesma instalação; atualizar arquivos não atualiza o processo em execução.",
+ "checkFailed": "Não foi possível ler a versão em execução. Reconecte ao mesmo gateway e tente novamente; o sucesso não foi confirmado."
+ },
+ "automaticRecovery": "Se a atualização falhar, o nanobot tentará restaurar o serviço com o programa anterior, quando for seguro. Os dados das conversas não serão revertidos.",
+ "restored": "Versão anterior restaurada",
+ "restoredDescription": "A atualização não foi concluída. A v{{version}} está funcionando novamente. Suas configurações e conversas não foram revertidas.",
+ "recoveryBeforeInstall": "A atualização parou antes da instalação. Nenhum arquivo do pacote foi alterado. Recupere a atualização salva para continuar.",
+ "channel": {
+ "settings": "Configurações de atualização",
+ "receivePreview": "Receber versões prévias",
+ "previewWarning": "Esta é uma versão prévia e pode conter erros.",
+ "preview": "Prévia",
+ "hint": "Experimente novidades antes.",
+ "saving": "Salvando…",
+ "saved": "Preferência de atualização salva",
+ "ahead": "Esta versão é mais recente que a do canal escolhido. Nenhuma versão anterior será instalada.",
+ "waiting_stable": "As atualizações prévias estão desativadas. Use esta versão até que haja uma versão estável mais recente.",
+ "withdrawn": "Esta prévia foi retirada. Atualize quando houver uma versão mais recente; não instale uma versão anterior sobre seus dados atuais.",
+ "unavailable": "Não foi possível verificar este canal. Ele pode ainda não estar disponível. Verifique a conexão e tente novamente.",
+ "publishing": "A versão ainda está sendo publicada. Verifique novamente mais tarde.",
+ "unsupported": "Não há atualização compatível com esta versão do Python e plataforma.",
+ "releaseNotes": "Notas da versão"
+ },
+ "reviewAgain": "Revisar atualização",
+ "reviewAgainDescription": "Nenhum arquivo do pacote foi alterado. Revise a atualização antes de confirmar a instalação e a reinicialização.",
+ "settleFailed": "Não foi possível encerrar a atualização anterior com segurança. Verifique o status novamente ou siga as instruções de recuperação.",
+ "ownerGuide": "Instruções de atualização para sua instalação",
+ "recoveryTitle": "Recuperar no computador do gateway",
+ "recoveryDescription": "Execute este comando no terminal do computador que executa o nanobot. Ele mostra a atualização salva antes de pedir confirmação para repará-la. Preserve o backup original.",
+ "confirm": "Atualizar nanobot agora?",
+ "reviewingTitle": "Verificando atualização…",
+ "preparing": "Baixando atualização…",
+ "installing": "Instalando atualização…",
+ "working": "Atualizando nanobot…",
+ "reconnecting": "Reconectando…",
+ "done": "Atualização concluída",
+ "failed": "A atualização não terminou",
+ "confirmDescription": "Atualizar para v{{version}} reiniciará o nanobot em {{host}}. Termine as tarefas em execução antes de continuar.",
+ "reviewing": "Verificando a instalação e a versão exata. Nenhum arquivo será alterado.",
+ "workingDescription": "Preparando e verificando arquivos; depois será feito backup e o gateway selecionado será reiniciado.",
+ "reconnectingDescription": "Aguardando a reconexão do gateway atualizado. Não inicie outra atualização.",
+ "delayed": "A reconexão está demorando. O progresso foi salvo; você pode fechar e verificar depois.",
+ "doneDescription": "Agora executando v{{version}}.",
+ "preparationFailed": "Falha na preparação ou na parada do gateway. Nenhum pacote foi alterado. Termine as tarefas e verifique novamente.",
+ "repairRequired": "Falha na instalação ou reinicialização. O backup e o registro foram mantidos. Siga o processo de recuperação; não inicie outra instalação.",
+ "reviewFailed": "Não foi possível verificar a atualização. Confira a conexão e a inicialização em segundo plano compatível com a instalação original.",
+ "confirmationUnknown": "A solicitação pode ter sido aceita. Verificando o progresso salvo antes de outra ação.",
+ "statusFailed": "Não foi possível ler o registro. Reconecte ao mesmo gateway e verifique novamente.",
+ "sharedInstallation": "Os {{count}} gateways ativos que compartilham esta instalação serão reiniciados.",
+ "cancel": "Cancelar",
+ "close": "Fechar",
+ "hide": "Recolher",
+ "return": "Concluído",
+ "wait": "Aguarde",
+ "checkAgain": "Verificar novamente",
+ "apply": "Atualizar e reiniciar",
+ "blocked": {
+ "review_changed": "A revisão mudou ou expirou. Feche e verifique novamente.",
+ "not_upgrade": "O destino não é uma atualização. Nenhum arquivo será alterado.",
+ "installation_owner": "Atualize usando o gerenciador de pacotes ou a ferramenta de implantação original.",
+ "installation_policy": "A origem, os extras ou as restrições de versão exigem o método de instalação original.",
+ "external_restart": "Este gateway não pode ser reiniciado aqui. Use a ferramenta de inicialização ou implantação original para pará-lo, atualizá-lo e reiniciá-lo.",
+ "permission": "Abra localhost no gateway ou permita a instalação remota de pacotes."
+ }
+ },
"remote": {
"compatibility": {
"title": "Verificar versão",
@@ -756,10 +858,16 @@
"noDescription": "Nenhuma descrição disponível."
},
"about": {
+ "updateNotice": "Atualização disponível",
+ "viewUpdateDetails": "Ver detalhes",
+ "updateNow": "Atualizar",
+ "dismissUpdate": "Ocultar aviso",
+ "updateInstructions": "Atualize no computador que executa o nanobot usando o método de instalação original. Esta página não instala nem reinicia nada.",
+ "installationGuide": "Guia de instalação",
"documentation": "Documentação",
"sourceCode": "Código-fonte",
"reportIssue": "Relatar um problema",
- "version": "Versão",
+ "version": "Versão e atualizações",
"checking": "Verificando...",
"checkForUpdates": "Verificar atualizações",
"upToDate": "O nanobot está atualizado",
diff --git a/webui/src/i18n/locales/vi/common.json b/webui/src/i18n/locales/vi/common.json
index a211affa5..5434511c5 100644
--- a/webui/src/i18n/locales/vi/common.json
+++ b/webui/src/i18n/locales/vi/common.json
@@ -1,4 +1,106 @@
{
+ "updates": {
+ "guide": {
+ "entry": "Cập nhật qua {{method}}",
+ "methods": {
+ "managed": "trình cài đặt nanobot",
+ "uv": "uv",
+ "pipx": "pipx",
+ "pip": "pip",
+ "source": "mã nguồn",
+ "container": "triển khai container",
+ "system": "trình quản lý gói hệ thống"
+ },
+ "host": "Gateway: {{host}}",
+ "where": "Dùng terminal trên máy này với tài khoản đã cài đặt ban đầu. Với gateway từ xa, dùng SSH hoặc bảng điều khiển máy chủ, không phải máy đang mở trình duyệt. Lệnh chỉ để sao chép, trang này không thực thi.",
+ "containerHost": "Đây là tên và đường dẫn bên trong container, không phải máy triển khai. Dùng máy chủ hoặc bảng quản trị container; không cập nhật bên trong container đang chạy.",
+ "beforeTitle": "Chuẩn bị và dừng dịch vụ",
+ "before": "Hoàn tất tác vụ, sao lưu cấu hình, hội thoại và dữ liệu workspace. Dừng mọi gateway dùng chung bản cài đặt qua trình khởi chạy hoặc quản lý dịch vụ ban đầu. Giữ đường dẫn hồ sơ và tham số khởi chạy.",
+ "installTitle": "Cập nhật trong {{shell}}",
+ "inspectCommand": "Kiểm tra bản cài đặt",
+ "updateCommand": "Lệnh cập nhật",
+ "versionCommand": "Phiên bản đã cài",
+ "reasons": {
+ "restart": "Gói đích đã được cài. Không cài lại. Dừng gateway cũ, khởi động bằng trình khởi chạy và hồ sơ ban đầu, rồi kiểm tra phiên bản đang chạy.",
+ "registry": "Dùng nguồn gói và thông tin xác thực ban đầu. Trình quản lý giữ extras và giới hạn phiên bản, nên có thể chọn bản ổn định khác với thông báo. Kiểm tra đầu ra; không ép cập nhật khi lỗi.",
+ "preview": "Preview được phát hành trên GitHub, có thể chưa có trên nguồn gói. Chọn wheel phù hợp Python và nền tảng của gateway, kiểm tra checksum rồi cài bằng công cụ ban đầu và cùng extras. Lệnh upgrade chung không đảm bảo cài đúng Preview này.",
+ "policy": "Có ghim phiên bản, tệp khóa, nguồn cố định, giới hạn hoặc tùy chọn chưa nhận diện. Kiểm tra và theo quy trình ban đầu, giữ extras và gói được thêm vào. Không tự bỏ giới hạn.",
+ "extras": "Môi trường pip này không ghi lại extras ban đầu. Kiểm tra gói rồi dùng lại lệnh pip gốc với --upgrade và phiên bản mong muốn, giữ extras và tùy chọn nguồn. Không cung cấp lệnh cài đặt phỏng đoán.",
+ "manager": "Không xác nhận được chương trình quản lý hoặc cấu trúc môi trường. Dùng tài khoản và thiết lập ban đầu để trỏ tới đường dẫn trên; không dùng pip hay nanobot khác trong PATH.",
+ "source": "Kiểm tra kho mã, giữ thay đổi cục bộ và xác nhận nhánh hoặc phiên bản. Theo quy trình của kho để cập nhật mã, phụ thuộc và build WebUI/TUI. Không thay bản cài editable bằng gói PyPI.",
+ "container": "Trong dự án Compose hoặc bảng quản trị gốc, chọn tag/digest, tải hoặc build ảnh rồi chỉ tạo lại dịch vụ nanobot với mount, bí mật và cổng cũ. Sao lưu volume dữ liệu; tuyệt đối không xóa chúng.",
+ "system": "Dùng trình quản lý gói của hệ điều hành hoặc liên hệ quản trị viên. Không dùng sudo pip hay vượt qua giới hạn Python do hệ thống quản lý.",
+ "review": "Bản cài đặt hoặc kết quả kiểm tra đã thay đổi. Đóng và kiểm tra lại trước khi sao chép lệnh."
+ },
+ "verifyTitle": "Khởi động lại và xác minh",
+ "verify": "Dùng cùng trình khởi chạy và hồ sơ. Lệnh chỉ kiểm tra tệp đã cài. Kết nối lại đúng gateway, so sánh phiên bản đang chạy với v{{version}} và kiểm tra hội thoại, cấu hình còn nguyên.",
+ "check": "Kiểm tra gateway đang chạy",
+ "verified": "Đã xác nhận: gateway đang chạy v{{version}}.",
+ "observed": "Gateway báo v{{version}}, không phải v{{target}}. Kiểm tra đầu ra cài đặt và khởi động lại cùng môi trường; cập nhật gói không thay đổi tiến trình đang chạy.",
+ "checkFailed": "Không đọc được phiên bản đang chạy. Kết nối lại đúng gateway và thử lại; chưa xác nhận cập nhật thành công."
+ },
+ "automaticRecovery": "Nếu cập nhật thất bại, nanobot sẽ thử khôi phục dịch vụ bằng chương trình trước đó khi an toàn. Dữ liệu trò chuyện sẽ không bị hoàn nguyên.",
+ "restored": "Đã khôi phục phiên bản trước",
+ "restoredDescription": "Cập nhật chưa hoàn tất. v{{version}} đã chạy lại. Cấu hình và cuộc trò chuyện không bị hoàn nguyên về dữ liệu cũ.",
+ "recoveryBeforeInstall": "Bản cập nhật đã dừng trước khi cài đặt. Chưa có tệp gói nào bị thay đổi. Khôi phục bản cập nhật đã lưu để tiếp tục.",
+ "channel": {
+ "settings": "Cài đặt cập nhật",
+ "receivePreview": "Nhận bản cập nhật xem trước",
+ "previewWarning": "Đây là bản xem trước và có thể có lỗi.",
+ "preview": "Xem trước",
+ "hint": "Trải nghiệm tính năng mới sớm.",
+ "saving": "Đang lưu…",
+ "saved": "Đã lưu tùy chọn cập nhật",
+ "ahead": "Phiên bản này mới hơn kênh đã chọn. Sẽ không cài đặt phiên bản cũ hơn.",
+ "waiting_stable": "Đã tắt cập nhật xem trước. Tiếp tục dùng phiên bản này cho đến khi có bản ổn định mới hơn.",
+ "withdrawn": "Bản xem trước này đã bị thu hồi. Hãy cập nhật khi có phiên bản mới hơn; không hạ cấp đè lên dữ liệu hiện tại.",
+ "unavailable": "Không thể xác minh kênh này. Kênh có thể chưa được mở. Kiểm tra kết nối rồi thử lại.",
+ "publishing": "Phiên bản đang được phát hành. Vui lòng kiểm tra lại sau.",
+ "unsupported": "Không có bản cập nhật tương thích với phiên bản Python và nền tảng này.",
+ "releaseNotes": "Ghi chú phát hành"
+ },
+ "reviewAgain": "Xem lại bản cập nhật",
+ "reviewAgainDescription": "Chưa có tệp gói nào bị thay đổi. Hãy xem lại bản cập nhật trước khi xác nhận cài đặt và khởi động lại.",
+ "settleFailed": "Chưa thể kết thúc an toàn lần cập nhật trước. Hãy kiểm tra lại trạng thái hoặc làm theo hướng dẫn khôi phục.",
+ "ownerGuide": "Hướng dẫn cập nhật cho cách cài đặt của bạn",
+ "recoveryTitle": "Khôi phục trên máy tính gateway",
+ "recoveryDescription": "Chạy lệnh này trong terminal trên máy tính đang chạy nanobot. Lệnh sẽ hiển thị bản cập nhật đã lưu trước khi yêu cầu xác nhận sửa chữa. Giữ lại bản sao lưu gốc.",
+ "confirm": "Cập nhật nanobot ngay?",
+ "reviewingTitle": "Đang kiểm tra bản cập nhật…",
+ "preparing": "Đang tải bản cập nhật…",
+ "installing": "Đang cài bản cập nhật…",
+ "working": "Đang cập nhật nanobot…",
+ "reconnecting": "Đang kết nối lại…",
+ "done": "Cập nhật hoàn tất",
+ "failed": "Cập nhật chưa hoàn tất",
+ "confirmDescription": "Cập nhật lên v{{version}} sẽ khởi động lại nanobot trên {{host}}. Hãy hoàn thành các tác vụ đang chạy trước khi tiếp tục.",
+ "reviewing": "Đang kiểm tra bản cài và phiên bản đích chính xác. Không thay đổi tệp.",
+ "workingDescription": "Đang chuẩn bị và xác minh tệp, sau đó sao lưu và khởi động lại gateway đã chọn.",
+ "reconnectingDescription": "Đang chờ kết nối lại gateway đã cập nhật. Đừng bắt đầu cập nhật khác.",
+ "delayed": "Kết nối lại mất nhiều thời gian. Tiến trình đã lưu; bạn có thể đóng và kiểm tra sau.",
+ "doneDescription": "Hiện đang chạy v{{version}}.",
+ "preparationFailed": "Chuẩn bị hoặc dừng gateway thất bại. Chưa thay đổi gói. Hãy kết thúc tác vụ rồi kiểm tra lại.",
+ "repairRequired": "Cài đặt hoặc khởi động lại thất bại. Bản sao lưu và nhật ký được giữ lại. Hãy làm theo quy trình khôi phục, đừng bắt đầu cài đặt khác.",
+ "reviewFailed": "Không thể xác minh bản cập nhật. Hãy kiểm tra kết nối và cách khởi chạy nền được bản cài gốc hỗ trợ.",
+ "confirmationUnknown": "Yêu cầu có thể đã được nhận. Đang kiểm tra tiến trình đã lưu trước thao tác tiếp theo.",
+ "statusFailed": "Không đọc được nhật ký. Hãy kết nối lại cùng gateway rồi kiểm tra.",
+ "sharedInstallation": "Sẽ khởi động lại {{count}} gateway đang chạy dùng chung bản cài này.",
+ "cancel": "Hủy",
+ "close": "Đóng",
+ "hide": "Thu gọn",
+ "return": "Xong",
+ "wait": "Vui lòng chờ",
+ "checkAgain": "Kiểm tra lại",
+ "apply": "Cập nhật và khởi động lại",
+ "blocked": {
+ "review_changed": "Thông tin đã đổi hoặc hết hạn. Đóng rồi kiểm tra lại.",
+ "not_upgrade": "Phiên bản đích không phải nâng cấp. Không thay đổi tệp.",
+ "installation_owner": "Hãy cập nhật bằng trình quản lý gói hoặc công cụ triển khai ban đầu.",
+ "installation_policy": "Nguồn cài đặt, phần bổ sung hoặc ràng buộc phiên bản yêu cầu cập nhật bằng phương thức cài đặt ban đầu.",
+ "external_restart": "Không thể khởi động lại gateway này tại đây. Hãy dùng công cụ khởi chạy hoặc triển khai ban đầu để dừng, cập nhật và khởi động lại.",
+ "permission": "Mở localhost trên gateway hoặc cho phép cài gói từ xa."
+ }
+ },
"remote": {
"compatibility": {
"title": "Kiểm tra phiên bản",
@@ -983,10 +1085,16 @@
"noDescription": "Không có mô tả."
},
"about": {
+ "updateNotice": "Có bản cập nhật",
+ "viewUpdateDetails": "Xem chi tiết",
+ "updateNow": "Cập nhật",
+ "dismissUpdate": "Ẩn thông báo cập nhật",
+ "updateInstructions": "Hãy cập nhật trên máy tính đang chạy nanobot bằng phương thức cài đặt ban đầu. Trang này không tự cài đặt hoặc khởi động lại.",
+ "installationGuide": "Hướng dẫn cài đặt",
"documentation": "Tài liệu",
"sourceCode": "Mã nguồn",
"reportIssue": "Báo cáo sự cố",
- "version": "Phiên bản",
+ "version": "Phiên bản & cập nhật",
"checking": "Đang kiểm tra...",
"checkForUpdates": "Kiểm tra bản cập nhật",
"upToDate": "Bạn đang dùng phiên bản mới nhất",
diff --git a/webui/src/i18n/locales/zh-CN/common.json b/webui/src/i18n/locales/zh-CN/common.json
index cc42040e0..22dce406f 100644
--- a/webui/src/i18n/locales/zh-CN/common.json
+++ b/webui/src/i18n/locales/zh-CN/common.json
@@ -1,4 +1,106 @@
{
+ "updates": {
+ "guide": {
+ "entry": "通过{{method}}更新",
+ "methods": {
+ "managed": "nanobot 安装器",
+ "uv": "uv",
+ "pipx": "pipx",
+ "pip": "pip",
+ "source": "源码",
+ "container": "容器部署",
+ "system": "系统包管理器"
+ },
+ "host": "网关:{{host}}",
+ "where": "请在这台机器的终端,用原安装账户操作。远程网关请通过 SSH 或服务器控制台连接,不是在浏览器所在的电脑上操作。这里的命令只供复制,不会自动执行。",
+ "containerHost": "这是容器的名称和内部路径,不是部署主机。请在管理此容器的服务器或托管控制台操作,不要在运行中的容器内升级。",
+ "beforeTitle": "准备并停止服务",
+ "before": "完成任务,备份配置、聊天记录和工作区数据。通过原启动器或服务管理器,停止共用此安装的所有网关。保留原配置路径和启动参数。",
+ "installTitle": "在 {{shell}} 中更新",
+ "inspectCommand": "检查此安装",
+ "updateCommand": "更新命令",
+ "versionCommand": "已安装的版本",
+ "reasons": {
+ "restart": "目标版本的文件已安装,无需再次安装。请停止旧网关,用原启动器和配置重新启动,再核对实际运行版本。",
+ "registry": "沿用原软件源和凭据。包管理器会保留记录的可选依赖和版本约束,实际选中的稳定版可能与提示不同。请检查命令输出,失败时不要强制覆盖。",
+ "preview": "Preview 通过 GitHub 分发,不一定在你的软件源中。选择本次发布中适合网关 Python 和平台的 wheel,校验文件后用原安装工具安装,并保留可选依赖。普通 upgrade 命令不能保证装到此 Preview。",
+ "policy": "安装记录包含固定版本、锁文件、固定来源、版本约束或无法识别的选项。请先检查,再沿用原流程更新,保留可选依赖和注入的包。不要为了更新直接解除限制。",
+ "extras": "此 pip 环境未记录最初选择的可选依赖。请先检查下面的包信息,再给原 pip 安装命令加上 --upgrade 和目标版本,保留可选依赖与软件源参数。这里不会猜测安装命令。",
+ "manager": "未能确认包管理器程序或环境布局。请用原安装账户和管理器设置,定位上面的安装路径;不要使用 PATH 中其他环境的 pip 或 nanobot。",
+ "source": "先检查此工作区,保留本地修改并确认目标分支或版本,再按仓库流程更新代码、依赖及 WebUI/TUI 构建。不要用 PyPI 安装覆盖可编辑源码环境。",
+ "container": "在原 Compose 项目或托管控制台中选择目标镜像标签或摘要,拉取或构建后,只重建 nanobot 服务,保留原挂载、凭据和端口。先备份数据卷,切勿为更新删除它们。",
+ "system": "通过操作系统的包管理器更新,或请服务器管理员处理。不要使用 sudo pip,也不要绕过系统 Python 的托管限制。",
+ "review": "安装环境或更新检查已变化。请关闭弹窗重新检查,再复制更新命令。"
+ },
+ "verifyTitle": "原方式启动并验证",
+ "verify": "使用原启动器和配置启动。终端命令仅检查已安装文件;请重新连接同一网关,核对运行版本是否为 v{{version}},并确认聊天记录和设置仍在。",
+ "check": "检查运行中的网关",
+ "verified": "已确认:此网关正在运行 v{{version}}。",
+ "observed": "此网关报告 v{{version}},与提示的 v{{target}} 不同。请检查安装输出,并重启同一安装环境;包已更新不代表运行中的进程已更新。",
+ "checkFailed": "无法读取运行版本。请重新连接同一网关后重试,目前尚未确认更新成功。"
+ },
+ "automaticRecovery": "更新失败时,nanobot 会尝试自动恢复服务,安全时恢复原程序。聊天数据不会回退。",
+ "restored": "已恢复原版本",
+ "restoredDescription": "更新未完成,已重新运行 v{{version}}。配置和聊天记录未被回退。",
+ "recoveryBeforeInstall": "更新在安装前停止,尚未修改安装文件。请恢复原更新以继续。",
+ "channel": {
+ "settings": "更新设置",
+ "receivePreview": "接收预览更新",
+ "previewWarning": "这是预览版,可能存在问题。",
+ "preview": "预览版",
+ "hint": "提前体验新功能。",
+ "saving": "正在保存…",
+ "saved": "更新偏好已保存",
+ "ahead": "当前版本领先于所选频道,不会安装更旧的版本。",
+ "waiting_stable": "已退出预览更新。保留当前版本,等待更新的正式版。",
+ "withdrawn": "当前预览版已撤回。请在修复版可用时升级,不要直接降级覆盖当前数据。",
+ "unavailable": "暂时无法验证此频道,可能尚未开放。请检查网络后重试。",
+ "publishing": "新版本仍在发布中,请稍后再检查。",
+ "unsupported": "此 Python 版本或平台暂无兼容更新。",
+ "releaseNotes": "更新说明"
+ },
+ "reviewAgain": "重新确认更新",
+ "reviewAgainDescription": "尚未修改安装文件。请重新查看更新内容,再确认安装并重启。",
+ "settleFailed": "暂时无法安全结束上次更新。请重新检查状态,或按更新恢复说明处理。",
+ "ownerGuide": "查看此安装方式的更新说明",
+ "recoveryTitle": "在网关电脑上恢复",
+ "recoveryDescription": "在运行 nanobot 的电脑上打开终端并运行此命令。它会先显示原更新记录,再询问是否恢复。请保留原备份。",
+ "confirm": "现在更新 nanobot?",
+ "reviewingTitle": "正在检查更新…",
+ "preparing": "正在下载更新…",
+ "installing": "正在安装更新…",
+ "working": "正在更新 nanobot…",
+ "reconnecting": "正在重新连接…",
+ "done": "更新完成",
+ "failed": "更新未完成",
+ "confirmDescription": "更新至 v{{version}} 后将重启 {{host}} 上的 nanobot。请先结束正在运行的任务。",
+ "reviewing": "正在核对安装环境和目标版本,不会修改文件。",
+ "workingDescription": "正在准备并校验文件,随后备份并重启所选网关。",
+ "reconnectingDescription": "正在等待更新后的网关重新连接,请勿重复发起更新。",
+ "delayed": "重连时间较长。进度已保存,你可以关闭此窗口,稍后再检查。",
+ "doneDescription": "当前已运行 v{{version}}。",
+ "preparationFailed": "准备或停止网关时失败,尚未修改安装文件。请结束正在运行的任务后重新检查。",
+ "repairRequired": "安装或重启失败,备份和更新记录已保留。请按更新恢复流程处理,不要发起另一次安装。",
+ "reviewFailed": "无法核实这次更新。请检查连接,并确认网关由原安装环境支持的后台启动方式运行。",
+ "confirmationUnknown": "请求可能已被接收,正在核对已保存的进度,请勿重复提交。",
+ "statusFailed": "无法读取更新记录。请重新连接同一个网关后检查。",
+ "sharedInstallation": "此安装由 {{count}} 个运行中的网关共用,它们都会重启。",
+ "cancel": "取消",
+ "close": "关闭",
+ "hide": "收起",
+ "return": "完成",
+ "wait": "请稍候",
+ "checkAgain": "重新检查",
+ "apply": "更新并重启",
+ "blocked": {
+ "review_changed": "更新方案已变化或过期,请关闭后重新检查。",
+ "not_upgrade": "目标版本无需升级,不会修改文件。",
+ "installation_owner": "请使用原包管理器或部署工具更新此安装。",
+ "installation_policy": "此安装的来源、可选依赖或版本设置需要通过原安装方式更新。",
+ "external_restart": "此网关无法在这里重启。请通过原启动方式或部署工具停止、更新并重启。",
+ "permission": "请在网关本机打开 localhost,或允许远程安装后更新。"
+ }
+ },
"remote": {
"compatibility": {
"title": "版本检查",
@@ -942,10 +1044,16 @@
"noDescription": "暂无描述。"
},
"about": {
+ "updateNotice": "有可用更新",
+ "viewUpdateDetails": "查看详情",
+ "updateNow": "更新",
+ "dismissUpdate": "暂时收起提示",
+ "updateInstructions": "请在运行 nanobot 的电脑上,使用原安装方式更新。此页面不会自动安装或重启。",
+ "installationGuide": "安装指南",
"documentation": "官方文档",
"sourceCode": "代码仓库",
"reportIssue": "问题反馈",
- "version": "版本",
+ "version": "版本与更新",
"checking": "正在检查...",
"checkForUpdates": "检查更新",
"upToDate": "已是最新版本",
diff --git a/webui/src/i18n/locales/zh-TW/common.json b/webui/src/i18n/locales/zh-TW/common.json
index 94de97792..17c0a8c87 100644
--- a/webui/src/i18n/locales/zh-TW/common.json
+++ b/webui/src/i18n/locales/zh-TW/common.json
@@ -1,4 +1,106 @@
{
+ "updates": {
+ "guide": {
+ "entry": "透過{{method}}更新",
+ "methods": {
+ "managed": "nanobot 安裝程式",
+ "uv": "uv",
+ "pipx": "pipx",
+ "pip": "pip",
+ "source": "原始碼",
+ "container": "容器部署",
+ "system": "系統套件管理員"
+ },
+ "host": "閘道:{{host}}",
+ "where": "請在這台機器的終端機,以原安裝帳戶操作。遠端閘道請透過 SSH 或伺服器主控台連線,不是在瀏覽器所在的電腦上操作。指令僅供複製,不會自動執行。",
+ "containerHost": "這是容器名稱與內部路徑,不是部署主機。請在管理此容器的伺服器或託管主控台操作,不要在執行中的容器內升級。",
+ "beforeTitle": "準備並停止服務",
+ "before": "完成工作,備份設定、聊天記錄及工作區資料。透過原啟動器或服務管理員停止共用此安裝的所有閘道。保留設定路徑與啟動參數。",
+ "installTitle": "在 {{shell}} 中更新",
+ "inspectCommand": "檢查此安裝",
+ "updateCommand": "更新指令",
+ "versionCommand": "已安裝版本",
+ "reasons": {
+ "restart": "目標版本的檔案已安裝,無須再次安裝。請停止舊閘道,以原啟動器與設定重新啟動,再核對執行版本。",
+ "registry": "沿用原套件來源與憑證。套件管理員會保留記錄的選用依賴與版本限制,實際選取的穩定版可能與提示不同。請檢查輸出,失敗時不要強制覆寫。",
+ "preview": "Preview 透過 GitHub 分發,不一定在套件來源中。選擇適合閘道 Python 與平台的 wheel,驗證檔案後用原工具安裝並保留選用依賴。一般 upgrade 指令無法保證安裝此 Preview。",
+ "policy": "安裝記錄含固定版本、鎖定檔、固定來源、版本限制或不明選項。請先檢查,再沿用原流程更新,保留選用依賴及注入的套件。不要直接解除限制。",
+ "extras": "此 pip 環境未記錄原先的選用依賴。檢查套件資訊後,在原 pip 安裝指令加上 --upgrade 與目標版本,保留依賴及來源參數。不提供猜測的安裝指令。",
+ "manager": "無法確認套件管理程式或環境配置。請以原帳戶及管理員設定定位上述路徑,不要使用 PATH 中其他環境的 pip 或 nanobot。",
+ "source": "先檢查工作區,保留本機修改並確認目標分支或版本,再依倉庫流程更新程式碼、依賴及 WebUI/TUI 建置。不要用 PyPI 套件覆蓋可編輯環境。",
+ "container": "在原 Compose 專案或託管主控台選擇目標映像標籤或摘要,拉取或建置後只重建 nanobot 服務,保留掛載、憑證與連接埠。先備份資料卷,切勿刪除。",
+ "system": "使用作業系統套件管理員更新,或請伺服器管理員處理。不要使用 sudo pip 或繞過系統 Python 的管理限制。",
+ "review": "安裝環境或檢查已變更。請關閉對話框並重新檢查,再複製更新指令。"
+ },
+ "verifyTitle": "原方式啟動並驗證",
+ "verify": "使用原啟動器與設定啟動。終端指令只檢查已安裝檔案;重新連線同一閘道,核對執行版本是否為 v{{version}},並確認聊天與設定仍在。",
+ "check": "檢查執行中的閘道",
+ "verified": "已確認:此閘道正在執行 v{{version}}。",
+ "observed": "此閘道回報 v{{version}},與提示的 v{{target}} 不同。請檢查安裝輸出並重新啟動同一環境;套件更新不代表執行中的程序已更新。",
+ "checkFailed": "無法讀取執行版本。請重新連線同一閘道後再試,目前尚未確認更新成功。"
+ },
+ "automaticRecovery": "更新失敗時,nanobot 會嘗試自動恢復服務,安全時恢復原程式。聊天資料不會回退。",
+ "restored": "已恢復原版本",
+ "restoredDescription": "更新未完成,已重新執行 v{{version}}。設定和聊天記錄未被回復為舊資料。",
+ "recoveryBeforeInstall": "更新在安裝前停止,尚未修改安裝檔案。請復原原更新以繼續。",
+ "channel": {
+ "settings": "更新設定",
+ "receivePreview": "接收預覽更新",
+ "previewWarning": "這是預覽版,可能存在問題。",
+ "preview": "預覽版",
+ "hint": "提前體驗新功能。",
+ "saving": "正在儲存…",
+ "saved": "更新偏好已儲存",
+ "ahead": "目前版本領先於所選頻道,不會安裝較舊版本。",
+ "waiting_stable": "已退出預覽更新。保留目前版本,等待更新的正式版。",
+ "withdrawn": "目前預覽版已撤回。請在修正版可用時升級,不要直接降級覆寫目前資料。",
+ "unavailable": "暫時無法驗證此頻道,可能尚未開放。請檢查網路後重試。",
+ "publishing": "新版本仍在發布中,請稍後再檢查。",
+ "unsupported": "此 Python 版本或平台暫無相容更新。",
+ "releaseNotes": "更新說明"
+ },
+ "reviewAgain": "重新確認更新",
+ "reviewAgainDescription": "尚未修改安裝檔案。請重新查看更新內容,再確認安裝並重新啟動。",
+ "settleFailed": "暫時無法安全結束上次更新。請重新檢查狀態,或依更新復原說明處理。",
+ "ownerGuide": "查看此安裝方式的更新說明",
+ "recoveryTitle": "在閘道電腦上復原",
+ "recoveryDescription": "在執行 nanobot 的電腦上開啟終端機並執行此命令。它會先顯示原更新記錄,再詢問是否復原。請保留原備份。",
+ "confirm": "現在更新 nanobot?",
+ "reviewingTitle": "正在檢查更新…",
+ "preparing": "正在下載更新…",
+ "installing": "正在安裝更新…",
+ "working": "正在更新 nanobot…",
+ "reconnecting": "正在重新連線…",
+ "done": "更新完成",
+ "failed": "更新未完成",
+ "confirmDescription": "更新至 v{{version}} 後將重新啟動 {{host}} 上的 nanobot。請先結束正在執行的工作。",
+ "reviewing": "正在核對安裝環境與目標版本,不會修改檔案。",
+ "workingDescription": "正在準備並驗證檔案,隨後備份並重新啟動所選閘道。",
+ "reconnectingDescription": "正在等待更新後的閘道重新連線,請勿重複發起更新。",
+ "delayed": "重新連線時間較長。進度已儲存,你可以關閉此視窗,稍後再檢查。",
+ "doneDescription": "目前已執行 v{{version}}。",
+ "preparationFailed": "準備或停止閘道時失敗,尚未修改安裝檔案。請結束執行中的工作後重新檢查。",
+ "repairRequired": "安裝或重新啟動失敗,備份與更新記錄已保留。請依更新復原流程處理,不要發起另一次安裝。",
+ "reviewFailed": "無法核實此次更新。請檢查連線,並確認閘道以原安裝環境支援的背景方式啟動。",
+ "confirmationUnknown": "請求可能已被接收,正在核對已儲存的進度,請勿重複提交。",
+ "statusFailed": "無法讀取更新記錄。請重新連線至同一個閘道後檢查。",
+ "sharedInstallation": "此安裝由 {{count}} 個執行中的閘道共用,它們都會重新啟動。",
+ "cancel": "取消",
+ "close": "關閉",
+ "hide": "收起",
+ "return": "完成",
+ "wait": "請稍候",
+ "checkAgain": "重新檢查",
+ "apply": "更新並重啟",
+ "blocked": {
+ "review_changed": "更新方案已變更或過期,請關閉後重新檢查。",
+ "not_upgrade": "目標版本無需升級,不會修改檔案。",
+ "installation_owner": "請使用原套件管理器或部署工具更新此安裝。",
+ "installation_policy": "此安裝的來源、選用依賴或版本設定需要透過原安裝方式更新。",
+ "external_restart": "此閘道無法在這裡重新啟動。請透過原啟動方式或部署工具停止、更新並重新啟動。",
+ "permission": "請在閘道本機開啟 localhost,或允許遠端安裝後更新。"
+ }
+ },
"remote": {
"compatibility": {
"title": "版本檢查",
@@ -983,10 +1085,16 @@
"noDescription": "目前沒有描述。"
},
"about": {
+ "updateNotice": "有可用更新",
+ "viewUpdateDetails": "查看詳情",
+ "updateNow": "更新",
+ "dismissUpdate": "暫時收起提示",
+ "updateInstructions": "請在執行 nanobot 的電腦上,使用原安裝方式更新。此頁面不會自動安裝或重新啟動。",
+ "installationGuide": "安裝指南",
"documentation": "官方文件",
"sourceCode": "程式碼儲存庫",
"reportIssue": "問題回報",
- "version": "版本",
+ "version": "版本與更新",
"checking": "正在檢查…",
"checkForUpdates": "檢查更新",
"upToDate": "已是最新版本",
diff --git a/webui/src/lib/api.ts b/webui/src/lib/api.ts
index 68b3db80c..91a6ea904 100644
--- a/webui/src/lib/api.ts
+++ b/webui/src/lib/api.ts
@@ -763,26 +763,42 @@ export async function fetchSettingsUsage(
);
}
+export type UpdateChannel = "stable" | "preview";
+export interface ReleaseStatus {
+ channel: UpdateChannel;
+ revision: number;
+ currentVersion: string;
+ state: "available" | "current" | "ahead" | "waiting_stable" | "withdrawn" | "unavailable" | "publishing" | "unsupported";
+}
export interface VersionCheckResult {
+ installation_method?: UpdateMethod | null;
+ releaseStatus?: ReleaseStatus;
+ can_change_channel?: boolean;
updateAvailable: {
currentVersion: string;
latestVersion: string;
pypiUrl?: string;
+ releaseUrl?: string;
} | null;
}
export async function checkVersion(
token: string,
base: string = "",
+ channelStatus = false,
): Promise<VersionCheckResult> {
return request<VersionCheckResult>(
- `${base}/api/settings/version-check`,
+ `${base}/api/settings/version-check${channelStatus ? "?channel_status=1" : ""}`,
token,
undefined,
- 10_000,
+ 90_000,
);
}
+export function changeUpdateChannel(transport: WebUIMutationTransport, channel: UpdateChannel, revision: number): Promise<{ channel: UpdateChannel; revision: number }> {
+ return mutation(transport, "settings.nanobot.update.channel", { channel, revision });
+}
+
export async function fetchWorkspaces(
token: string,
base: string = "",
@@ -795,6 +811,73 @@ export async function fetchWorkspaces(
);
}
+export type UpdateMethod = "managed" | "uv" | "pipx" | "pip" | "source" | "container" | "system";
+export interface UpdateGuide {
+ method: UpdateMethod;
+ host: string;
+ environment: string;
+ shell: "sh" | "powershell";
+ inspect_command: string | null;
+ update_command: string | null;
+ verify_command: string | null;
+ reason: "registry" | "preview" | "policy" | "extras" | "manager" | "source" | "container" | "system" | "review" | "restart";
+}
+export interface UpdateReview {
+ id: string;
+ installation_id: string;
+ host: string;
+ running_version: string;
+ target_version: string;
+ channel?: UpdateChannel;
+ action: "upgrade" | "downgrade" | "restart" | "none";
+ validity: "current" | "expired" | "installation_changed" | "profiles_changed" | "channel_changed";
+ execution_blocked_reason: string | null;
+ automatic_recovery?: boolean;
+ guide?: UpdateGuide | null;
+ profiles: { id: string; workspace: string; reviewed_state: string; stop: boolean; restart: boolean }[];
+}
+export interface UpdateReviewResponse {
+ plan: UpdateReview;
+ installation_allowed: boolean;
+ execution_available: boolean;
+}
+export type UpdateJobPhase = "preparation_requested" | "preparing" | "preparation_failed" | "ready"
+ | "checking" | "stopping" | "handoff_failed" | "backing_up" | "installing" | "verifying"
+ | "installed" | "restarting" | "activating" | "finalizing" | "restart_failed" | "succeeded" | "failed" | "cancelled";
+export interface UpdateJob {
+ id: string;
+ installation_id: string;
+ target_version: string;
+ running_version: string;
+ recorded_phase: UpdateJobPhase;
+ recovery_active?: boolean;
+ service_restored?: boolean;
+ automatic_recovery?: boolean;
+ previous_version?: string;
+ mutation_started: boolean;
+ execution_confirmation_id: string | null;
+ recovery_command?: string;
+}
+export function createUpdateReview(transport: WebUIMutationTransport): Promise<UpdateReviewResponse> {
+ return mutation(transport, "settings.nanobot.update.plan", { restart_running: true }, 60_000);
+}
+export function readUpdateReview(token: string, id: string): Promise<UpdateReviewResponse> {
+ return request(`/api/settings/nanobot-update/plan?id=${encodeURIComponent(id)}`, token, undefined, API_READ_TIMEOUT_MS);
+}
+export function readUpdateJob(token: string, id: string): Promise<{ job: UpdateJob }> {
+ return request(`/api/settings/nanobot-update/job?id=${encodeURIComponent(id)}`, token, undefined, API_READ_TIMEOUT_MS);
+}
+export function prepareUpdate(transport: WebUIMutationTransport, id: string): Promise<{ job: UpdateJob }> {
+ return mutation(transport, "settings.nanobot.update.prepare", { id });
+}
+export function settleUpdate(transport: WebUIMutationTransport, id: string): Promise<{ job: UpdateJob }> {
+ return mutation(transport, "settings.nanobot.update.settle", { id });
+}
+export function executeUpdate(transport: WebUIMutationTransport, id: string, previousConfirmation?: string): Promise<{ job: UpdateJob }> {
+ return mutation(transport, previousConfirmation ? "settings.nanobot.update.retry" : "settings.nanobot.update.execute",
+ { id, confirm_restart: true, ...(previousConfirmation ? { previous_confirmation_id: previousConfirmation } : {}) });
+}
+
export async function fetchWorkspaceDirectories(
token: string,
path: string,
diff --git a/webui/src/providers/ClientProvider.tsx b/webui/src/providers/ClientProvider.tsx
index 8e16ed3f0..18a11923d 100644
--- a/webui/src/providers/ClientProvider.tsx
+++ b/webui/src/providers/ClientProvider.tsx
@@ -9,6 +9,8 @@ import {
import type { NanobotClient } from "@/lib/nanobot-client";
import type { WebUIIngressLimits } from "@/lib/types";
+import { VersionCheckProvider } from "@/providers/VersionCheckProvider";
+import { UpdateFlowProvider } from "@/providers/UpdateFlowProvider";
interface ClientContextValue {
client: NanobotClient;
@@ -27,6 +29,8 @@ export function ClientProvider({
modelName = null,
ingressLimits = null,
webuiCapabilities = [],
+ checkUpdatesOnConnect = false,
+ allowUpdateFlow = true,
children,
}: {
client: NanobotClient;
@@ -34,6 +38,8 @@ export function ClientProvider({
modelName?: string | null;
ingressLimits?: WebUIIngressLimits | null;
webuiCapabilities?: string[];
+ checkUpdatesOnConnect?: boolean;
+ allowUpdateFlow?: boolean;
children: ReactNode;
}) {
const tokenRef = useRef(token);
@@ -46,7 +52,13 @@ export function ClientProvider({
return (
<ClientContext.Provider value={value}>
- {children}
+ <VersionCheckProvider token={token} client={client} autoCheck={checkUpdatesOnConnect}
+ channels={allowUpdateFlow && webuiCapabilities.includes("webui.update-channels.v1")}>
+ <UpdateFlowProvider client={client} token={token} enabled={allowUpdateFlow && webuiCapabilities.includes("webui.update-flow.v1")}
+ canSettleHandoff={webuiCapabilities.includes("webui.update-jobs.settle-handoff.v1")}>
+ {children}
+ </UpdateFlowProvider>
+ </VersionCheckProvider>
</ClientContext.Provider>
);
}
diff --git a/webui/src/providers/UpdateFlowProvider.tsx b/webui/src/providers/UpdateFlowProvider.tsx
new file mode 100644
index 000000000..2af968557
--- /dev/null
+++ b/webui/src/providers/UpdateFlowProvider.tsx
@@ -0,0 +1,332 @@
+import { createContext, useCallback, useContext, useEffect, useRef, useState, type ReactNode } from "react";
+import { useTranslation } from "react-i18next";
+import { Loader2 } from "lucide-react";
+
+import { AlertDialog, AlertDialogContent, AlertDialogTitle, AlertDialogDescription } from "@/components/ui/alert-dialog";
+import { Button } from "@/components/ui/button";
+import { Textarea } from "@/components/ui/textarea";
+import { UpdateGuide } from "@/components/UpdateGuide";
+import { ApiError, createUpdateReview, readUpdateReview, readUpdateJob, prepareUpdate, executeUpdate, settleUpdate,
+ type UpdateReviewResponse, type UpdateJob } from "@/lib/api";
+import type { NanobotClient } from "@/lib/nanobot-client";
+
+const STORAGE_KEY = "nanobot.pending-update.v1";
+const RECOVERY_KEY = "nanobot.pending-update-recovery.v1";
+const terminal = new Set(["preparation_failed", "handoff_failed", "restart_failed", "succeeded", "failed", "cancelled"]);
+const UpdateFlowContext = createContext<{ open: (() => void) | undefined; pending: boolean }>({ open: undefined, pending: false });
+
+function savedJob(): string | null {
+ try {
+ const id = sessionStorage.getItem(STORAGE_KEY);
+ return id && /^[0-9a-f-]{36}$/.test(id) ? id : null;
+ } catch { return null; }
+}
+function remember(id: string | null) {
+ try { if (id) sessionStorage.setItem(STORAGE_KEY, id); else { sessionStorage.removeItem(STORAGE_KEY); sessionStorage.removeItem(RECOVERY_KEY); } } catch { /* Memory state still works. */ }
+}
+
+export function UpdateFlowProvider({ client, token, enabled, canSettleHandoff = false, children }: {
+ client: NanobotClient; token: string; enabled: boolean; canSettleHandoff?: boolean; children: ReactNode;
+}) {
+ const { t } = useTranslation();
+ const [open, setOpen] = useState(false);
+ const [review, setReview] = useState<UpdateReviewResponse | null>(null);
+ const [job, setJob] = useState<UpdateJob | null>(null);
+ const [pendingId, setPendingId] = useState<string | null>(null);
+ const [submitting, setSubmitting] = useState(false);
+ const [checkingStatus, setCheckingStatus] = useState(false);
+ const [error, setError] = useState("");
+ const [offline, setOffline] = useState(false);
+ const [delayed, setDelayed] = useState(false);
+ const [pollAttempt, setPollAttempt] = useState(0);
+ const [recovery, setRecovery] = useState("");
+ const [automaticRecovery, setAutomaticRecovery] = useState(false);
+ const generation = useRef(0);
+ const approved = useRef<string | null>(null);
+ const trigger = useRef<HTMLElement | null>(null);
+ const heading = useRef<HTMLHeadingElement>(null);
+ const inFlight = useRef(false);
+
+ // Credentials/host changes revoke this client's unconsumed consent. Restoring
+ // a durable job is a read only; READY after refresh needs another button press.
+ useEffect(() => {
+ generation.current++;
+ approved.current = null;
+ inFlight.current = false;
+ setSubmitting(false);
+ setCheckingStatus(false);
+ setReview(null);
+ setJob(null);
+ setError("");
+ const id = enabled ? savedJob() : null;
+ // Retain a plain-text host command for an offline gateway, never consent.
+ // It is displayed, not executed by the browser.
+ try {
+ const saved = JSON.parse(sessionStorage.getItem(RECOVERY_KEY) || "null");
+ setRecovery(saved?.id === id && typeof saved.command === "string" ? saved.command : "");
+ setAutomaticRecovery(saved?.id === id && saved.automatic === true);
+ } catch { setRecovery(""); setAutomaticRecovery(false); }
+ setPendingId(id);
+ setOpen(!!id);
+ }, [client, token, enabled]);
+
+ const execute = useCallback(async (id: string) => {
+ if (inFlight.current) return;
+ inFlight.current = true;
+ setSubmitting(true);
+ const current = generation.current;
+ approved.current = null; // Consume once before the request, including a lost response.
+ try {
+ const response = await executeUpdate(client, id);
+ if (generation.current === current) setJob(response.job);
+ } catch {
+ // The gateway may already be shutting down. Read the journal before
+ // offering a fresh confirmation; never replay execution automatically.
+ if (generation.current === current) setError(t("updates.confirmationUnknown"));
+ } finally {
+ if (generation.current === current) { inFlight.current = false; setSubmitting(false); }
+ }
+ }, [client, t]);
+
+ useEffect(() => {
+ if (!enabled || !pendingId) return;
+ let active = true;
+ let timer: ReturnType<typeof setTimeout>;
+ let missingSince = 0;
+ const reconnecting = () => {
+ missingSince ||= Date.now();
+ setOffline(true);
+ setDelayed(Date.now() - missingSince > 120_000);
+ };
+ const refresh = async (manual = false) => {
+ const feedback = manual ? new Promise(resolve => setTimeout(resolve, 600)) : Promise.resolve();
+ try {
+ // API tokens belong to a gateway process. Let the client's authenticated
+ // reconnect replace them before reading the new process's update journal.
+ if (client.status !== "open") {
+ reconnecting();
+ timer = setTimeout(() => void refresh(), 1500);
+ return;
+ }
+ const { job: next } = await readUpdateJob(token, pendingId).finally(() => feedback);
+ if (!active) return;
+ setJob(next);
+ setAutomaticRecovery(next.automatic_recovery === true);
+ if (next.recovery_command) {
+ setRecovery(next.recovery_command);
+ try { sessionStorage.setItem(RECOVERY_KEY, JSON.stringify({ id: next.id, command: next.recovery_command, automatic: next.automatic_recovery === true })); } catch { /* Still available until reload. */ }
+ }
+ setOffline(false);
+ setDelayed(false);
+ missingSince = 0;
+ setError("");
+ if (next.recorded_phase === "ready" && approved.current === next.id) {
+ await execute(next.id);
+ }
+ if (!active) return;
+ if (!next.recovery_active && terminal.has(next.recorded_phase)
+ && !(next.recorded_phase === "succeeded" && next.running_version !== next.target_version)
+ && !(next.service_restored && next.running_version !== next.previous_version)) return;
+ // A refresh can recover files already staged, but not installation consent.
+ if (next.recorded_phase === "ready" && !next.execution_confirmation_id) {
+ try {
+ const restored = await readUpdateReview(token, next.id);
+ if (active) setReview(restored);
+ } catch { if (active) setError(t("updates.reviewFailed")); }
+ }
+ } catch (reason) {
+ if (!active) return;
+ if (reason instanceof ApiError && ([403, 404, 409].includes(reason.status)
+ || (reason.status === 401 && client.status === "open"))) {
+ // Do not discard an unknown mutation outcome or create a second job.
+ approved.current = null;
+ setOffline(false);
+ setDelayed(false);
+ setError(t("updates.statusFailed"));
+ return;
+ }
+ reconnecting();
+ } finally {
+ if (manual) {
+ // A repeated terminal result still needs a visible acknowledgement.
+ await feedback;
+ if (active) setCheckingStatus(false);
+ }
+ }
+ if (active) timer = setTimeout(() => void refresh(), 1500);
+ };
+ void refresh(pollAttempt > 0);
+ return () => { active = false; clearTimeout(timer); };
+ }, [client, enabled, pendingId, token, execute, t, pollAttempt]);
+
+ const inspect = async (retireId?: string) => {
+ if (inFlight.current) return;
+ inFlight.current = true;
+ const current = ++generation.current;
+ approved.current = null;
+ setSubmitting(true);
+ setError("");
+ let retired = !retireId;
+ try {
+ if (retireId) {
+ // Only the gateway can establish that no old worker can still execute.
+ // A lost/refused response keeps the original job and recovery entry.
+ const response = await settleUpdate(client, retireId);
+ if (generation.current !== current) return;
+ if ((response.job.recorded_phase !== "cancelled" && response.job.recorded_phase !== "preparation_failed")
+ || response.job.mutation_started) throw new Error("Update not settled");
+ retired = true;
+ }
+ setJob(null);
+ setReview(null);
+ setRecovery("");
+ setAutomaticRecovery(false);
+ setPendingId(null);
+ remember(null);
+ const next = await createUpdateReview(client);
+ if (generation.current === current) setReview(next);
+ } catch {
+ if (generation.current === current) setError(t(retired ? "updates.reviewFailed" : "updates.settleFailed"));
+ } finally {
+ if (generation.current === current) { setSubmitting(false); inFlight.current = false; }
+ }
+ };
+ const show = () => {
+ trigger.current = document.activeElement instanceof HTMLElement ? document.activeElement : null;
+ setOpen(true);
+ if (!pendingId) void inspect();
+ };
+ const confirm = async () => {
+ if (inFlight.current || !review?.execution_available || !review.installation_allowed) return;
+ const id = review.plan.id;
+ if (job?.recorded_phase === "ready") {
+ if (job.execution_confirmation_id) return;
+ await execute(id);
+ setPollAttempt(value => value + 1);
+ return;
+ }
+ inFlight.current = true;
+ const current = generation.current;
+ approved.current = id;
+ setSubmitting(true);
+ setError("");
+ remember(id);
+ setAutomaticRecovery(review.plan.automatic_recovery === true);
+ try { sessionStorage.setItem(RECOVERY_KEY, JSON.stringify({ id, automatic: review.plan.automatic_recovery === true })); } catch { /* Memory state still works. */ }
+ try {
+ const response = await prepareUpdate(client, id);
+ if (generation.current === current) { setJob(response.job); setPendingId(id); }
+ } catch (reason) {
+ if (generation.current === current) {
+ approved.current = null;
+ // A completed rejection (for example, a channel change in another tab)
+ // plus a missing journal permits a new review, never automatic retry.
+ // A timeout/lost response or an unreadable/existing job is still unknown.
+ if (reason instanceof ApiError && reason.status >= 400 && reason.status < 500) {
+ try {
+ const response = await readUpdateJob(token, id);
+ if (generation.current === current) setJob(response.job);
+ } catch (readError) {
+ if (generation.current !== current) return;
+ if (readError instanceof ApiError && readError.status === 404) {
+ remember(null);
+ setReview(null);
+ setError(t("updates.reviewAgainDescription"));
+ return;
+ }
+ }
+ }
+ if (generation.current === current) setPendingId(id);
+ }
+ } finally {
+ if (generation.current === current) { setSubmitting(false); inFlight.current = false; }
+ }
+ };
+
+ const phase = job?.recorded_phase;
+ const restored = job?.service_restored && job.running_version === job.previous_version;
+ const done = restored || (phase === "succeeded" && job?.running_version === job?.target_version);
+ const awaitingRestart = phase === "succeeded" && !done;
+ const failed = !job?.recovery_active && !job?.service_restored && !!phase && terminal.has(phase) && phase !== "succeeded";
+ // Backup can fail after shutdown/admission but before any package mutation.
+ // That saved job still needs the standalone recovery path, not another update.
+ const needsRecovery = failed && (job?.mutation_started || phase === "failed");
+ const preparing = phase === "preparation_requested" || phase === "preparing";
+ // The base update flow can settle preparation, but only the gateway's leases
+ // establish abandonment. Keep this tab's confirmed preparation uninterrupted.
+ const reviewAgain = job && !job.mutation_started && ((enabled && preparing && approved.current !== job.id)
+ || (canSettleHandoff && (phase === "handoff_failed" || phase === "cancelled"
+ || (phase === "ready" && review && review.plan.validity !== "current"))));
+ const restoringReview = !!pendingId && phase === "ready" && !job?.execution_confirmation_id && !review && !error;
+ const reviewing = (submitting && (!review || !!reviewAgain)) || restoringReview;
+ const busy = checkingStatus || submitting || restoringReview || (!!pendingId && !reviewAgain && !error && !failed && !done && (phase !== "ready" || !!job?.execution_confirmation_id));
+ const title = restored ? "restored" : done ? "done" : offline || awaitingRestart ? "reconnecting" : reviewing ? "reviewingTitle" : busy ? preparing ? "preparing" : phase === "installing" ? "installing" : "working" : failed ? "failed" : "confirm";
+ const blocked = !reviewAgain && !job?.execution_confirmation_id && review && (!review.installation_allowed ? "permission" : review.plan.execution_blocked_reason);
+ const guide = blocked && !busy && !error && !pendingId && review && ["upgrade", "restart"].includes(review.plan.action)
+ && review.plan.validity === "current" ? review.plan.guide : null;
+ const description = delayed ? t(automaticRecovery ? "updates.automaticRecovery" : "updates.delayed") : error || (restored ? t("updates.restoredDescription", { version: job?.previous_version }) : done ? t("updates.doneDescription", { version: job?.target_version })
+ : offline || awaitingRestart ? t("updates.reconnectingDescription") : reviewing ? t("updates.reviewing")
+ : reviewAgain ? t("updates.reviewAgainDescription") : failed ? t(job?.mutation_started ? "updates.repairRequired" : needsRecovery ? "updates.recoveryBeforeInstall" : "updates.preparationFailed")
+ : busy ? t("updates.workingDescription") : guide?.reason === "restart" ? t("updates.guide.reasons.restart") : blocked ? t(`updates.blocked.${blocked}`)
+ : review ? t("updates.confirmDescription", { version: review.plan.target_version, host: review.plan.host }) : t("updates.reviewing"));
+ const startAgain = !pendingId || (failed && !needsRecovery && !job?.execution_confirmation_id);
+ const primary = () => {
+ if (checkingStatus) return;
+ if (done) close();
+ else if (reviewAgain && !error) {
+ void inspect(job.id);
+ } else if (error || failed) {
+ if (startAgain) void inspect();
+ else { setCheckingStatus(true); setPollAttempt(value => value + 1); }
+ } else void confirm();
+ };
+ const close = () => { setOpen(false); if (done) { remember(null); setPendingId(null); window.location.reload(); } };
+ const ownerInstructions = <a className="mt-3 block rounded-control text-sm text-muted-foreground underline-offset-4 hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring" href="https://github.com/HKUDS/nanobot/blob/main/docs/updating.md#installation-owners"
+ target="_blank" rel="noreferrer">{t("updates.ownerGuide")}</a>;
+
+ return <UpdateFlowContext.Provider value={{ open: enabled ? show : undefined, pending: enabled && !!pendingId }}>
+ {children}
+ <AlertDialog open={open} onOpenChange={setOpen}>
+ <AlertDialogContent className={`max-h-[calc(100dvh-2rem)] ${guide ? "flex max-w-lg flex-col overflow-hidden" : "max-w-[384px] overflow-y-auto"} gap-0 rounded-panel p-6 motion-reduce:animate-none`}
+ onOpenAutoFocus={(event) => { event.preventDefault(); heading.current?.focus(); }}
+ onCloseAutoFocus={(event) => { event.preventDefault(); if (trigger.current?.isConnected) trigger.current.focus(); }}>
+ <div aria-live="polite" aria-atomic="true">
+ <img src="/brand/nanobot_mark.svg" alt="" draggable={false} className="mb-4 h-11 w-11 select-none" />
+ <AlertDialogTitle ref={heading} tabIndex={-1} className="text-lg font-semibold leading-7 tracking-tight outline-none">{guide
+ ? guide.reason === "restart" ? t("updates.guide.verifyTitle") : t("updates.guide.entry", { method: t(`updates.guide.methods.${guide.method}`) })
+ : t(checkingStatus ? "settings.about.checking" : `updates.${title}`)}</AlertDialogTitle>
+ <AlertDialogDescription className="mt-2 text-sm leading-6">{description}</AlertDialogDescription>
+ {review?.plan.automatic_recovery && !pendingId && !busy && !blocked && !error &&
+ <p className="mt-2 text-xs leading-5 text-muted-foreground">{t("updates.automaticRecovery")}</p>}
+ {review && !busy && !blocked && !done && !failed && !error && /\.dev\d+$/.test(review.plan.target_version) &&
+ <p className="mt-2 text-xs leading-5 text-muted-foreground">{t("updates.channel.previewWarning")}</p>}
+ {review && !busy && !blocked && !done && review.plan.profiles.filter(p => p.restart).length > 1 &&
+ <p className="mt-2 text-xs text-muted-foreground">{t("updates.sharedInstallation", { count: review.plan.profiles.filter(p => p.restart).length })}</p>}
+ </div>
+ {pendingId && recovery && !job?.recovery_active && ((delayed && !automaticRecovery) || needsRecovery) && <div className="mt-4 space-y-2 border-t pt-4">
+ <p className="text-sm font-medium">{t("updates.recoveryTitle")}</p>
+ <p className="text-xs leading-5 text-muted-foreground">{t("updates.recoveryDescription")}</p>
+ <Textarea aria-label={t("updates.recoveryTitle")} readOnly value={recovery} rows={4}
+ onFocus={event => event.currentTarget.select()}
+ className="resize-none font-mono text-xs leading-5" />
+ </div>}
+ {guide && review ? <div className="min-h-0 overflow-y-auto overscroll-contain">
+ <UpdateGuide key={`${token}:${review.plan.id}`} guide={guide} token={token} targetVersion={review.plan.target_version} />
+ {ownerInstructions}
+ </div> : blocked ? ownerInstructions : null}
+ <div className={`mt-6 grid shrink-0 ${done || blocked ? "grid-cols-1" : "grid-cols-2"} gap-2.5`}>
+ {!done && !blocked && <Button variant="secondary" onClick={close}>
+ {t(done || failed || error || blocked ? "updates.close" : busy ? "updates.hide" : "updates.cancel")}
+ </Button>}
+ <Button variant="accent" className="min-w-0 whitespace-normal" disabled={!blocked && busy} aria-busy={busy}
+ onClick={blocked ? close : primary}>
+ {busy && <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin motion-reduce:animate-none" aria-hidden />}
+ {t(checkingStatus ? "settings.about.checking" : blocked ? "updates.close" : done ? "updates.return" : busy ? "updates.wait" : error ? "updates.checkAgain" : reviewAgain ? "updates.reviewAgain" : failed ? "updates.checkAgain" : "updates.apply")}
+ </Button>
+ </div>
+ </AlertDialogContent>
+ </AlertDialog>
+ </UpdateFlowContext.Provider>;
+}
+
+export function useUpdateFlow() { return useContext(UpdateFlowContext); }
diff --git a/webui/src/providers/VersionCheckProvider.tsx b/webui/src/providers/VersionCheckProvider.tsx
new file mode 100644
index 000000000..73d8817cb
--- /dev/null
+++ b/webui/src/providers/VersionCheckProvider.tsx
@@ -0,0 +1,123 @@
+import { createContext, useContext, useEffect, useMemo, useSyncExternalStore, type ReactNode } from "react";
+
+import { checkVersion, changeUpdateChannel, type ReleaseStatus, type UpdateChannel, type UpdateMethod, type WebUIMutationTransport } from "@/lib/api";
+
+export type VersionResult =
+ | { type: "up-to-date" }
+ | { type: "update"; latestVersion: string; pypiUrl?: string; releaseUrl?: string }
+ | { type: "release-status"; state: ReleaseStatus["state"] }
+ | { type: "error"; message: string }
+ | null;
+
+interface VersionCheckState {
+ installationMethod: UpdateMethod | null;
+ result: VersionResult;
+ checking: boolean;
+ dismissedVersion: string | null;
+ check: () => Promise<void>;
+ dismiss: () => void;
+ releaseStatus: ReleaseStatus | null;
+ canChangeChannel: boolean;
+ changingChannel: boolean;
+ channelError: string;
+ changeChannel: (channel: UpdateChannel) => Promise<void>;
+}
+
+const VersionCheckContext = createContext<VersionCheckState | null>(null);
+
+// Per-connection store: old responses can only update their original store.
+// Changing credentials must not remount the application or discard chat drafts.
+function createVersionCheck(token: string, channels: boolean, client?: WebUIMutationTransport) {
+ let snapshot: Omit<VersionCheckState, "check" | "dismiss" | "changeChannel"> = {
+ result: null, checking: false, dismissedVersion: null, installationMethod: null,
+ releaseStatus: null, canChangeChannel: false, changingChannel: false, channelError: "",
+ };
+ let pending: Promise<void> | null = null;
+ let pendingChannel: Promise<void> | null = null;
+ const listeners = new Set<() => void>();
+ const update = (patch: Partial<typeof snapshot>) => {
+ snapshot = { ...snapshot, ...patch };
+ listeners.forEach((listener) => listener());
+ };
+ const check = () => {
+ if (pending) return pending;
+ update({ checking: true });
+ pending = (async () => {
+ try {
+ const response = await checkVersion(token, "", channels);
+ if (channels && !response.releaseStatus) throw new Error("The gateway did not return its update channel. Check again.");
+ const method = response.installation_method;
+ update({ installationMethod: method && ["managed", "uv", "pipx", "pip", "source", "container", "system"].includes(method) ? method : null });
+ if (channels && response.releaseStatus) update({ releaseStatus: response.releaseStatus, canChangeChannel: response.can_change_channel === true });
+ update({ result: response.updateAvailable
+ ? { type: "update", ...response.updateAvailable }
+ : response.releaseStatus && response.releaseStatus.state !== "current"
+ ? { type: "release-status", state: response.releaseStatus.state }
+ : { type: "up-to-date" } });
+ } catch (error) {
+ update({ result: { type: "error", message: (error as Error).message } });
+ } finally {
+ pending = null;
+ update({ checking: false });
+ }
+ })();
+ return pending;
+ };
+ return {
+ // Entering About during a save shares its post-mutation check, not an old-channel read.
+ check: () => pendingChannel ?? check(),
+ changeChannel: (channel: UpdateChannel) => {
+ if (!channels || !client || !snapshot.releaseStatus || !snapshot.canChangeChannel || snapshot.changingChannel || pending) return Promise.resolve();
+ const revision = snapshot.releaseStatus.revision;
+ update({ changingChannel: true, channelError: "" });
+ pendingChannel = (async () => {
+ try {
+ const selection = await changeUpdateChannel(client, channel, revision);
+ update({ releaseStatus: { ...snapshot.releaseStatus!, ...selection }, result: null, dismissedVersion: null });
+ } catch (error) {
+ update({ channelError: (error as Error).message });
+ } finally {
+ // Also resolve a lost mutation response / another tab's newer revision.
+ await check();
+ pendingChannel = null;
+ update({ changingChannel: false });
+ }
+ })();
+ return pendingChannel;
+ },
+ getSnapshot: () => snapshot,
+ subscribe: (listener: () => void) => {
+ listeners.add(listener);
+ return () => { listeners.delete(listener); };
+ },
+ dismiss: () => {
+ if (snapshot.result?.type === "update") update({ dismissedVersion: snapshot.result.latestVersion });
+ },
+ };
+}
+
+export function VersionCheckProvider({ token, autoCheck = false, channels = false, client, children }: {
+ token: string;
+ autoCheck?: boolean;
+ channels?: boolean;
+ client?: WebUIMutationTransport;
+ children: ReactNode;
+}) {
+ const store = useMemo(() => createVersionCheck(token, channels, client), [token, channels, client]);
+ const snapshot = useSyncExternalStore(store.subscribe, store.getSnapshot);
+
+ useEffect(() => {
+ // One quiet check on connection, not a timer or an installation request.
+ if (autoCheck && token) void store.check();
+ }, [autoCheck, store, token]);
+
+ return <VersionCheckContext.Provider value={{ ...snapshot, check: store.check, dismiss: store.dismiss, changeChannel: store.changeChannel }}>
+ {children}
+ </VersionCheckContext.Provider>;
+}
+
+export function useVersionCheck() {
+ const value = useContext(VersionCheckContext);
+ if (!value) throw new Error("useVersionCheck must be used within a VersionCheckProvider");
+ return value;
+}
diff --git a/webui/src/tests/app-layout.test.tsx b/webui/src/tests/app-layout.test.tsx
index 4bc7638c1..c1a76d4e2 100644
--- a/webui/src/tests/app-layout.test.tsx
+++ b/webui/src/tests/app-layout.test.tsx
@@ -402,6 +402,9 @@ describe("App layout", () => {
}] },
});
render(<App />);
+ // Await the lazy module itself; cold Vite transformation is not the task
+ // capability contract exercised by the timed DOM assertions below.
+ await act(async () => { await import("@/components/thread/ThreadShell"); });
await screen.findByRole("textbox", {}, { timeout: 5_000 });
if (supported) await screen.findByRole("button", { name: /Config check Running/ });
else expect(screen.queryByText("Config check")).not.toBeInTheDocument();
@@ -3122,11 +3125,15 @@ describe("App layout", () => {
});
it("opens the settings view from the sidebar footer", async () => {
- mockFetchRoutes({ "/api/settings": baseSettingsPayload() });
+ mockFetchRoutes({
+ "/api/settings": baseSettingsPayload(),
+ "/api/settings/version-check": { updateAvailable: null },
+ });
render(<App />);
await waitFor(() => expect(connectSpy).toHaveBeenCalled());
fireEvent.click(within(screen.getByRole("navigation", { name: "Sidebar navigation" }))
.getByRole("button", { name: "Settings" }));
+ await act(async () => { await import("@/components/settings/SettingsView"); });
const nav = await screen.findByRole("navigation", { name: "Settings sections" });
for (const name of ["Overview", "Appearance", "Models", "Capabilities", "System", "Advanced", "About"]) {
expect(within(nav).getByRole("button", { name })).toBeInTheDocument();
@@ -3138,7 +3145,8 @@ describe("App layout", () => {
fireEvent.click(within(nav).getByRole("button", { name: "Capabilities" }));
expect(screen.getByRole("switch", { name: "Image generation" })).toBeInTheDocument();
fireEvent.click(within(nav).getByRole("button", { name: "About" }));
- expect(await screen.findByRole("button", { name: "Check for updates" })).toBeInTheDocument();
+ expect(await screen.findByText("You're up to date")).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Check again" })).toBeInTheDocument();
});
it("restores the settings section from the URL hash after a page reload", async () => {
diff --git a/webui/src/tests/bun-react-runtime.test.ts b/webui/src/tests/bun-react-runtime.test.ts
new file mode 100644
index 000000000..27f57824c
--- /dev/null
+++ b/webui/src/tests/bun-react-runtime.test.ts
@@ -0,0 +1,18 @@
+import { execFileSync, spawnSync } from "node:child_process";
+import { expect, it } from "vitest";
+
+const root = process.cwd();
+const bunError = spawnSync("bun", ["--version"], { timeout: 10_000 }).error;
+const bunAvailable = !(bunError && "code" in bunError && bunError.code === "ENOENT");
+
+it.skipIf(!bunAvailable)("Bun loads React runtime code for the packaged Vite SSR build", () => {
+ // Type-only aliases previously made Bun execute @types/react/index.d.ts.
+ // npm-only development can skip this; native-package CI installs pinned Bun.
+ const html = execFileSync("bun", ["--eval", `
+ import { createElement } from "react";
+ import { renderToStaticMarkup } from "react-dom/server";
+ import { jsx } from "react/jsx-runtime";
+ console.log(renderToStaticMarkup(createElement("div", null, jsx("span", {children: "ready"}))));
+ `], { cwd: root, encoding: "utf8", timeout: 10_000 });
+ expect(html.trim()).toBe("<div><span>ready</span></div>");
+});
diff --git a/webui/src/tests/gallery-language.test.tsx b/webui/src/tests/gallery-language.test.tsx
index ee5824c02..fa2eb7259 100644
--- a/webui/src/tests/gallery-language.test.tsx
+++ b/webui/src/tests/gallery-language.test.tsx
@@ -76,3 +76,27 @@ it("keeps the visible assistant identity when translating existing interaction f
expect(preview.getByText("Support assistant:已关闭")).toBeVisible();
});
+
+it("quietly keeps Preview selection and translates update feedback without executing an update", async () => {
+ const source = "webui/src/components/settings/overview/VersionCheckRowView.tsx";
+ window.history.replaceState({}, "", `/gallery.html#${new URLSearchParams({ component: source })}`);
+ const fetch = vi.fn().mockResolvedValue({ ok: true, json: async () => inventory });
+ vi.stubGlobal("fetch", fetch);
+ render(<Gallery />);
+ const preview = within(await screen.findByRole("region", { name: "Component preview" }));
+ await userEvent.click(preview.getByRole("combobox", { name: "Version state" }));
+ await userEvent.click(await screen.findByRole("option", { name: "preview" }));
+ const toggle = preview.getByRole("switch", { name: "Receive preview updates" });
+ await userEvent.click(toggle);
+ expect(toggle).toBeChecked();
+ expect(preview.queryByText("Sample preference saved; nothing will be installed or restarted.")).toBeNull();
+ await userEvent.click(preview.getByRole("button", { name: "Update" }));
+ expect(preview.getByText("Update review selected; this preview does not install or restart anything.")).toBeVisible();
+
+ await chooseChinese();
+
+ expect(preview.getByText("已选择查看更新;组件预览不会安装或重启。")).toBeVisible();
+ expect(toggle).toBeChecked();
+ expect(preview.getByText("v0.3.7.dev2026101501")).toBeVisible();
+ expect(fetch).toHaveBeenCalledTimes(1);
+});
diff --git a/webui/src/tests/settings-overview.test.tsx b/webui/src/tests/settings-overview.test.tsx
index c2692d0b4..6fb44a1b1 100644
--- a/webui/src/tests/settings-overview.test.tsx
+++ b/webui/src/tests/settings-overview.test.tsx
@@ -15,16 +15,74 @@ import { jsonResponse, settingsPayload, renderSettingsView, installSettingsViewT
describe("Settings overview and appearance", () => {
installSettingsViewTestHooks();
+ it.each([{ capabilities: [] }, { capabilities: ["webui.core.v1", "webui.self-update.v1"] }])(
+ "checks on About entry without calling the legacy updater (%j)",
+ async ({ capabilities }) => {
+ const fetcher = vi.fn(async () => jsonResponse({
+ updateAvailable: { currentVersion: "0.2.2", latestVersion: "0.3.6" },
+ }));
+ vi.stubGlobal("fetch", fetcher);
+ render(
+ <ClientProvider client={new NanobotClient({ url: "ws://localhost:8765" })} token="tok"
+ webuiCapabilities={capabilities}>
+ <AboutSettings settings={settingsPayload()} />
+ </ClientProvider>,
+ );
+ expect(await screen.findByRole("link", { name: "Installation guide" })).toBeVisible();
+ expect(fetcher).toHaveBeenCalledTimes(1);
+ expect(fetcher).toHaveBeenCalledWith("/api/settings/version-check", expect.any(Object));
+ expect(screen.queryByRole("button", { name: /^Update$/ })).not.toBeInTheDocument();
+ },
+ );
+
it("displays a caller-owned version result and delegates checking without a client provider", () => {
const check = vi.fn();
- render(<VersionCheckRowView currentVersion="0.3.5" checking={false}
+ const { rerender } = render(<VersionCheckRowView currentVersion="0.3.5" checking={false}
result={{ type: "update", latestVersion: "0.3.6", pypiUrl: "https://pypi.org/project/nanobot-ai/" }} onCheck={check} />);
- expect(screen.getByText("Update available v0.3.6")).toBeVisible();
+ expect(screen.getByText("v0.3.6")).toBeVisible();
expect(screen.getByRole("link", { name: "PyPI" })).toHaveAttribute("href", "https://pypi.org/project/nanobot-ai/");
- fireEvent.click(screen.getByRole("button", { name: "Check for updates" }));
+ rerender(<VersionCheckRowView currentVersion="0.3.5" checking={false} result={{ type: "up-to-date" }} onCheck={check} />);
+ expect(screen.getByText("You're up to date")).toBeVisible();
+ fireEvent.click(screen.getByRole("button", { name: "Check again" }));
expect(check).toHaveBeenCalledTimes(1);
});
+ it("delegates update actions and keeps saved-job details available in the shared view", () => {
+ const requestUpdate = vi.fn();
+ const props = { currentVersion: "0.3.5", checking: false, onCheck: vi.fn(),
+ onRequestUpdate: requestUpdate };
+ const { rerender } = render(<VersionCheckRowView {...props}
+ result={{ type: "update", latestVersion: "0.3.7.dev2026101501",
+ releaseUrl: "https://github.com/HKUDS/nanobot/releases/tag/v0.3.7.dev2026101501" }} />);
+ expect(screen.getByText("v0.3.7.dev2026101501")).toBeVisible();
+ expect(screen.getByRole("link", { name: "Release notes" })).toHaveAttribute("href",
+ "https://github.com/HKUDS/nanobot/releases/tag/v0.3.7.dev2026101501");
+ expect(requestUpdate).not.toHaveBeenCalled();
+ expect(screen.queryByRole("link", { name: "Installation guide" })).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: /^Update$/ }));
+ expect(requestUpdate).toHaveBeenCalledTimes(1);
+
+ rerender(<VersionCheckRowView {...props} currentVersion="0.3.6"
+ result={{ type: "up-to-date" }} hasPendingUpdate />);
+ expect(screen.queryByRole("button", { name: /^Update$/ })).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "View details" }));
+ expect(requestUpdate).toHaveBeenCalledTimes(2);
+ });
+
+ it("lets the visible Preview label toggle the setting without consenting to an update", () => {
+ const changeChannel = vi.fn().mockResolvedValue(undefined);
+ const requestUpdate = vi.fn();
+ render(<VersionCheckRowView currentVersion="0.3.6" checking={false} result={null} onCheck={vi.fn()}
+ releaseStatus={{ channel: "stable", revision: 1, currentVersion: "0.3.6", state: "current" }}
+ canChangeChannel onChangeChannel={changeChannel} onRequestUpdate={requestUpdate} />);
+ const toggle = screen.getByRole("switch", { name: "Receive preview updates" });
+ expect(toggle).toHaveAccessibleDescription("Try new features early.");
+ fireEvent.click(document.querySelector(`label[for="${toggle.id}"]`)!);
+ expect(changeChannel).toHaveBeenCalledTimes(1);
+ expect(changeChannel).toHaveBeenCalledWith("preview");
+ expect(requestUpdate).not.toHaveBeenCalled();
+ });
+
it("opens the notifications section and preserves independent browser-local channel preferences", () => {
writeLocalPreferences({ ...DEFAULT_LOCAL_PREFS, notificationSound: true });
renderSettingsView({ initialSection: "appearance", initialSettings: settingsPayload(), showSidebar: true });
@@ -74,7 +132,7 @@ describe("Settings overview and appearance", () => {
initialSettings: { ...settingsPayload(), version: { current: "0.3.5", commit } },
});
expect(screen.getByText("v0.3.5")).toBeInTheDocument();
- expect(screen.getByRole("button", { name: "Check for updates" })).toBeEnabled();
+ expect(screen.getByText("Checking...")).toBeVisible();
expect(document.querySelector('a[href*="/commit/"]')).toBeNull();
const reportUrl = new URL(screen.getByRole("link", { name: "Report an issue" }).getAttribute("href")!);
expect(reportUrl.searchParams.get("version")).toBe("0.3.5");
diff --git a/webui/src/tests/update-channels.test.tsx b/webui/src/tests/update-channels.test.tsx
new file mode 100644
index 000000000..c2d272099
--- /dev/null
+++ b/webui/src/tests/update-channels.test.tsx
@@ -0,0 +1,172 @@
+import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { AboutSettings } from "@/components/settings/overview/OverviewSettings";
+import { NanobotClient } from "@/lib/nanobot-client";
+import { ClientProvider } from "@/providers/ClientProvider";
+import { useVersionCheck } from "@/providers/VersionCheckProvider";
+import { jsonResponse, settingsPayload } from "@/tests/settings-test-utils";
+
+afterEach(() => { cleanup(); vi.unstubAllGlobals(); vi.restoreAllMocks(); });
+const state = (channel = "stable", revision = 0, status = "current") => ({
+ updateAvailable: null, can_change_channel: true,
+ releaseStatus: { channel, revision, currentVersion: "0.3.7.dev42", state: status },
+});
+
+function Controls() {
+ const channel = useVersionCheck();
+ return <>
+ <button onClick={() => void channel.changeChannel("preview")}>Subscribe preview</button>
+ <button onClick={() => void channel.changeChannel("stable")}>Subscribe stable</button>
+ <input aria-label="Draft" />
+ </>;
+}
+function view(client: NanobotClient, token = "channel-a", native = false) {
+ return <ClientProvider client={client} token={token} checkUpdatesOnConnect allowUpdateFlow={!native}
+ webuiCapabilities={["webui.update-channels.v1"]}>
+ <AboutSettings settings={settingsPayload()} /><Controls />
+ </ClientProvider>;
+}
+
+describe("Installation-owned release channels", () => {
+ it("shows saving progress, then quietly selects a channel without installation or restart consent", async () => {
+ const client = new NanobotClient({ url: "ws://localhost:8765" });
+ let resolve!: (value: unknown) => void;
+ const mutation = vi.spyOn(client, "requestMutation").mockImplementation(() => new Promise(done => { resolve = done; }));
+ const fetcher = vi.fn().mockResolvedValueOnce(jsonResponse(state()))
+ .mockResolvedValueOnce(jsonResponse(state("preview", 1, "unavailable")));
+ vi.stubGlobal("fetch", fetcher);
+ render(view(client));
+ const selector = await screen.findByRole("switch", { name: "Receive preview updates" });
+ expect(selector).toBeVisible();
+ expect(selector).toHaveAccessibleDescription("Try new features early.");
+ expect(selector).toHaveAttribute("aria-checked", "false");
+ fireEvent.change(screen.getByLabelText("Draft"), { target: { value: "Keep writing" } });
+ fireEvent.click(selector);
+ expect(selector).toBeDisabled();
+ expect(screen.getByText("Saving…")).toBeVisible();
+ fireEvent.click(screen.getByText("Subscribe stable"));
+ expect(mutation).toHaveBeenCalledOnce();
+ expect(mutation).toHaveBeenCalledWith("settings.nanobot.update.channel", { channel: "preview", revision: 0 }, expect.any(Number));
+ await act(async () => resolve({ channel: "preview", revision: 1 }));
+ await waitFor(() => expect(selector).toBeEnabled());
+ expect(selector).toHaveAttribute("aria-checked", "true");
+ expect(selector).toBeVisible();
+ expect(screen.queryByText("Saving…")).toBeNull();
+ expect(screen.queryByText("Update preference saved")).toBeNull();
+ expect(screen.getByText(/Could not verify/)).toBeVisible();
+ expect(screen.queryByText("You're up to date")).toBeNull();
+ expect(screen.getByLabelText("Draft")).toHaveValue("Keep writing");
+ expect(fetcher).toHaveBeenCalledWith("/api/settings/version-check?channel_status=1", expect.any(Object));
+ expect(mutation).toHaveBeenCalledOnce();
+ });
+
+ it("reloads a quietly saved channel and uses its latest revision for the next save", async () => {
+ const client = new NanobotClient({ url: "ws://localhost:8765" });
+ let selection = { channel: "stable", revision: 0 };
+ const mutation = vi.spyOn(client, "requestMutation").mockImplementation(async (_action, payload) => {
+ selection = { channel: String(payload?.channel), revision: selection.revision + 1 };
+ return selection;
+ });
+ vi.stubGlobal("fetch", vi.fn(async () => jsonResponse(state(selection.channel, selection.revision))));
+ const first = render(view(client));
+ fireEvent.click(await screen.findByRole("switch", { name: "Receive preview updates" }));
+ await waitFor(() => expect(screen.getByRole("switch")).toBeEnabled());
+ expect(screen.getByRole("switch")).toHaveAttribute("aria-checked", "true");
+ first.unmount();
+
+ render(view(client));
+ const selector = await screen.findByRole("switch", { name: "Receive preview updates" });
+ expect(selector).toHaveAttribute("aria-checked", "true");
+ fireEvent.click(selector);
+ await waitFor(() => expect(selector).toBeEnabled());
+ expect(selector).toHaveAttribute("aria-checked", "false");
+ expect(mutation).toHaveBeenNthCalledWith(1, "settings.nanobot.update.channel", { channel: "preview", revision: 0 }, expect.any(Number));
+ expect(mutation).toHaveBeenNthCalledWith(2, "settings.nanobot.update.channel", { channel: "stable", revision: 1 }, expect.any(Number));
+ expect(screen.queryByText("Update preference saved")).toBeNull();
+ });
+
+ it("shares the post-save check when About is reentered during a channel mutation and retries its failure", async () => {
+ const client = new NanobotClient({ url: "ws://localhost:8765" });
+ let resolveSave!: (value: unknown) => void;
+ const mutation = vi.spyOn(client, "requestMutation").mockImplementation(() => new Promise(done => { resolveSave = done; }));
+ const fetcher = vi.fn().mockResolvedValueOnce(jsonResponse(state()))
+ .mockRejectedValueOnce(new Error("Channel check unavailable"))
+ .mockResolvedValueOnce(jsonResponse(state("preview", 1)));
+ vi.stubGlobal("fetch", fetcher);
+ const surface = (about: boolean) => <ClientProvider client={client} token="save-reentry"
+ webuiCapabilities={["webui.update-channels.v1"]}>
+ {about && <AboutSettings settings={settingsPayload()} />}
+ </ClientProvider>;
+ const mounted = render(surface(true));
+ fireEvent.click(await screen.findByRole("switch", { name: "Receive preview updates" }));
+ mounted.rerender(surface(false));
+ mounted.rerender(surface(true));
+ expect(screen.getByText("Saving…")).toBeVisible();
+ expect(fetcher).toHaveBeenCalledOnce();
+ await act(async () => resolveSave({ channel: "preview", revision: 1 }));
+ expect(await screen.findByText("Channel check unavailable")).toBeVisible();
+ expect(fetcher).toHaveBeenCalledTimes(2);
+ fireEvent.click(screen.getByRole("button", { name: "Retry" }));
+ await waitFor(() => expect(screen.getByRole("switch")).toBeEnabled());
+ expect(screen.getByRole("switch")).toHaveAttribute("aria-checked", "true");
+ expect(screen.getByText("You're up to date")).toBeVisible();
+ expect(fetcher).toHaveBeenCalledTimes(3);
+ expect(mutation).toHaveBeenCalledOnce();
+ expect(mutation).toHaveBeenCalledWith("settings.nanobot.update.channel", { channel: "preview", revision: 0 }, expect.any(Number));
+ });
+
+ it("resynchronizes a stale tab or lost response and waits for stable without downgrading", async () => {
+ const client = new NanobotClient({ url: "ws://localhost:8765" });
+ const mutation = vi.spyOn(client, "requestMutation").mockRejectedValue(new Error("Channel changed elsewhere; check again"));
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValueOnce(jsonResponse(state("preview", 1)))
+ .mockResolvedValueOnce(jsonResponse(state("stable", 2, "waiting_stable"))));
+ render(view(client));
+ fireEvent.click(await screen.findByRole("switch", { name: "Receive preview updates" }));
+ await waitFor(() => expect(screen.getByRole("switch")).toHaveAttribute("aria-checked", "false"));
+ expect(screen.getByText(/Channel changed elsewhere/)).toBeVisible();
+ expect(screen.getByText(/newer stable release/)).toBeVisible();
+ expect(screen.queryByText("You're up to date")).toBeNull();
+ expect(mutation).toHaveBeenCalledOnce();
+ });
+
+ it("does not let a late old-host mutation change the new host or discard its draft", async () => {
+ const client = new NanobotClient({ url: "ws://localhost:8765" });
+ let resolve!: (value: unknown) => void;
+ vi.spyOn(client, "requestMutation").mockImplementation(() => new Promise(done => { resolve = done; }));
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValueOnce(jsonResponse(state()))
+ .mockResolvedValueOnce(jsonResponse(state("stable", 4)))
+ .mockResolvedValueOnce(jsonResponse(state("preview", 1))));
+ const { rerender } = render(view(client));
+ fireEvent.click(await screen.findByRole("switch", { name: "Receive preview updates" }));
+ fireEvent.change(screen.getByLabelText("Draft"), { target: { value: "Survives" } });
+ rerender(view(client, "channel-b"));
+ await screen.findByRole("switch", { name: "Receive preview updates" });
+ await waitFor(() => expect(screen.getByRole("switch")).toBeEnabled());
+ await act(async () => resolve({ channel: "preview", revision: 1 }));
+ expect(screen.getByRole("switch")).toHaveAttribute("aria-checked", "false");
+ expect(screen.getByLabelText("Draft")).toHaveValue("Survives");
+ });
+
+ it("does not turn a missing channel result into a green success", async () => {
+ vi.stubGlobal("fetch", vi.fn(async () => jsonResponse({ updateAvailable: null })));
+ render(view(new NanobotClient({ url: "ws://localhost:8765" })));
+ expect(await screen.findByText(/did not return its update channel/)).toBeVisible();
+ expect(screen.queryByText("You're up to date")).toBeNull();
+ });
+
+ it("shows a read-only channel for remote callers and leaves native updates to the distributor", async () => {
+ const client = new NanobotClient({ url: "ws://localhost:8765" });
+ const mutation = vi.spyOn(client, "requestMutation");
+ vi.stubGlobal("fetch", vi.fn(async () => jsonResponse({ ...state(), can_change_channel: false })));
+ const { rerender } = render(view(client));
+ const selector = await screen.findByRole("switch", { name: "Receive preview updates" });
+ expect(selector).toBeDisabled();
+ expect(selector).toHaveAccessibleDescription(/Open this gateway on localhost or allow remote package installation/);
+ fireEvent.click(screen.getByText("Subscribe preview"));
+ expect(mutation).not.toHaveBeenCalled();
+ rerender(view(client, "native", true));
+ await waitFor(() => expect(screen.queryByRole("switch")).toBeNull());
+ expect(mutation).not.toHaveBeenCalled();
+ });
+});
diff --git a/webui/src/tests/update-flow.test.tsx b/webui/src/tests/update-flow.test.tsx
new file mode 100644
index 000000000..4561d1aae
--- /dev/null
+++ b/webui/src/tests/update-flow.test.tsx
@@ -0,0 +1,636 @@
+import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import * as api from "@/lib/api";
+import { copyTextToClipboard } from "@/lib/clipboard";
+import type { NanobotClient } from "@/lib/nanobot-client";
+import type { ConnectionStatus } from "@/lib/types";
+import { UpdateFlowProvider, useUpdateFlow } from "@/providers/UpdateFlowProvider";
+import { ClientProvider } from "@/providers/ClientProvider";
+import { AboutSettings } from "@/components/settings/overview/OverviewSettings";
+import { settingsPayload } from "@/tests/settings-test-utils";
+
+vi.mock("@/lib/api", async (original) => ({
+ ...await original<typeof api>(), createUpdateReview: vi.fn(), readUpdateReview: vi.fn(),
+ readUpdateJob: vi.fn(), prepareUpdate: vi.fn(), executeUpdate: vi.fn(), settleUpdate: vi.fn(), checkVersion: vi.fn(), fetchSettings: vi.fn(),
+}));
+vi.mock("@/lib/clipboard", () => ({ copyTextToClipboard: vi.fn() }));
+const id = "71c91a73-842e-42e9-aeb4-61a5bfe51135";
+let connectionStatus: ConnectionStatus = "open";
+const client = { get status() { return connectionStatus; } } as NanobotClient;
+const review: api.UpdateReviewResponse = {
+ plan: { id, installation_id: "installed-a", host: "test Mac", running_version: "0.3.5", target_version: "0.3.6",
+ action: "upgrade", validity: "current", execution_blocked_reason: null, profiles: [] },
+ installation_allowed: true, execution_available: true,
+};
+const externalReview: api.UpdateReviewResponse = {
+ ...review, execution_available: false,
+ plan: { ...review.plan, execution_blocked_reason: "installation_owner", guide: {
+ method: "pipx", host: "remote-server", environment: "/server/pipx/venvs/nanobot-ai-work", shell: "sh", reason: "registry",
+ inspect_command: "env PIPX_HOME=/server/pipx pipx list",
+ update_command: "env PIPX_HOME=/server/pipx pipx upgrade nanobot-ai-work",
+ verify_command: "/server/pipx/venvs/nanobot-ai-work/bin/python -I -m nanobot --version",
+ } },
+};
+const job = (phase: api.UpdateJobPhase, confirmation: string | null = null): api.UpdateJob => ({
+ id, installation_id: "installed-a", target_version: "0.3.6", running_version: "0.3.5",
+ recorded_phase: phase, mutation_started: false, execution_confirmation_id: confirmation,
+});
+function Entry() {
+ const flow = useUpdateFlow();
+ return <button disabled={!flow.open} onClick={flow.open}>Update entry</button>;
+}
+function view(token = "gateway-a", enabled = true, canSettleHandoff = true) {
+ return <UpdateFlowProvider client={client} token={token} enabled={enabled} canSettleHandoff={canSettleHandoff}><Entry /></UpdateFlowProvider>;
+}
+beforeEach(() => {
+ connectionStatus = "open";
+ vi.resetAllMocks(); sessionStorage.clear();
+ vi.mocked(api.createUpdateReview).mockResolvedValue(review);
+ vi.mocked(api.readUpdateReview).mockResolvedValue(review);
+ vi.mocked(api.prepareUpdate).mockResolvedValue({ job: job("preparing") });
+ vi.mocked(api.readUpdateJob).mockResolvedValue({ job: job("ready") });
+ vi.mocked(api.executeUpdate).mockResolvedValue({ job: job("checking", "confirmed") });
+ vi.mocked(api.checkVersion).mockResolvedValue({ updateAvailable: null });
+});
+afterEach(() => { cleanup(); sessionStorage.clear(); vi.useRealTimers(); });
+
+describe("Real update consent and recovery", () => {
+ it("opens the original confirmation from an automatically checked About update without consenting to installation", async () => {
+ vi.mocked(api.checkVersion).mockResolvedValue({ installation_method: "managed",
+ updateAvailable: { currentVersion: "0.3.5", latestVersion: "0.3.6" } });
+ render(<ClientProvider client={client} token="about-confirmation" webuiCapabilities={["webui.update-flow.v1"]}>
+ <AboutSettings settings={settingsPayload()} />
+ </ClientProvider>);
+ fireEvent.click(await screen.findByRole("button", { name: /^Update$/ }));
+ expect(await screen.findByRole("button", { name: "Update & restart" })).toBeEnabled();
+ expect(api.checkVersion).toHaveBeenCalledOnce();
+ expect(api.createUpdateReview).toHaveBeenCalledOnce();
+ expect(api.prepareUpdate).not.toHaveBeenCalled();
+ expect(api.executeUpdate).not.toHaveBeenCalled();
+ });
+ it("offers installation-bound instructions and copy feedback, without installation consent", async () => {
+ vi.mocked(api.createUpdateReview).mockResolvedValue(externalReview);
+ vi.mocked(copyTextToClipboard).mockResolvedValueOnce(false).mockResolvedValueOnce(true);
+ render(view());
+ fireEvent.click(screen.getByText("Update entry"));
+ await screen.findByRole("heading", { name: "Update via pipx" });
+ expect(screen.getByText("Gateway: remote-server")).toBeVisible();
+ expect(screen.getByText(/connect by SSH or its server console/)).toBeVisible();
+ expect(screen.getByLabelText("Update command")).toHaveValue(externalReview.plan.guide!.update_command);
+ fireEvent.click(screen.getByRole("button", { name: "Copy command" }));
+ await screen.findByText("Could not copy. Select and copy the command above.");
+ fireEvent.click(screen.getByRole("button", { name: "Copy command" }));
+ await screen.findByRole("button", { name: "Copied" });
+ expect(copyTextToClipboard).toHaveBeenLastCalledWith(externalReview.plan.guide!.update_command);
+ fireEvent.click(screen.getByRole("button", { name: "Inspect this installation" }));
+ expect(screen.getByRole("button", { name: "Inspect this installation" })).toHaveAttribute("aria-expanded", "true");
+ fireEvent.click(screen.getByRole("button", { name: "Inspect this installation" }));
+ expect(screen.getByRole("button", { name: "Inspect this installation" })).toHaveAttribute("aria-expanded", "false");
+ expect(api.prepareUpdate).not.toHaveBeenCalled();
+ expect(api.executeUpdate).not.toHaveBeenCalled();
+ });
+ it("verifies the running gateway, reports mismatch and offline errors, never infers success from package installation", async () => {
+ vi.mocked(api.createUpdateReview).mockResolvedValue(externalReview);
+ vi.mocked(api.fetchSettings).mockResolvedValueOnce({ ...settingsPayload(), version: { current: "0.3.5" } })
+ .mockRejectedValueOnce(new Error("offline"))
+ .mockResolvedValueOnce({ ...settingsPayload(), version: { current: "0.3.6" } });
+ render(view());
+ fireEvent.click(screen.getByText("Update entry"));
+ const check = await screen.findByRole("button", { name: "Check running gateway" });
+ fireEvent.click(check);
+ await screen.findByText(/reports v0.3.5, not the notice’s v0.3.6/);
+ fireEvent.click(check);
+ await screen.findByText(/Could not read the running version/);
+ fireEvent.click(check);
+ await screen.findByText("Confirmed: this gateway is running v0.3.6.");
+ expect(api.fetchSettings).toHaveBeenLastCalledWith("gateway-a");
+ expect(api.executeUpdate).not.toHaveBeenCalled();
+ });
+ it("discards an old gateway's late verification on a credential switch", async () => {
+ vi.mocked(api.createUpdateReview).mockResolvedValue(externalReview);
+ let resolve!: (value: Awaited<ReturnType<typeof api.fetchSettings>>) => void;
+ vi.mocked(api.fetchSettings).mockImplementation(() => new Promise(done => { resolve = done; }));
+ const mounted = render(view());
+ fireEvent.click(screen.getByText("Update entry"));
+ fireEvent.click(await screen.findByRole("button", { name: "Check running gateway" }));
+ mounted.rerender(view("gateway-b"));
+ await act(async () => { resolve({ ...settingsPayload(), version: { current: "0.3.6" } }); });
+ expect(screen.queryByText(/Confirmed: this gateway/)).not.toBeInTheDocument();
+ expect(screen.queryByText("Gateway: remote-server")).not.toBeInTheDocument();
+ });
+ it("retains the safe fallback for an older host without optional guidance", async () => {
+ vi.mocked(api.createUpdateReview).mockResolvedValue({ ...review, execution_available: false,
+ plan: { ...review.plan, execution_blocked_reason: "installation_owner" } });
+ render(view());
+ fireEvent.click(screen.getByText("Update entry"));
+ await screen.findByRole("link", { name: "Update instructions for your installation" });
+ expect(screen.queryByRole("button", { name: "Update & restart" })).not.toBeInTheDocument();
+ expect(api.executeUpdate).not.toHaveBeenCalled();
+ });
+ it("guides an already installed target through restart without offering another installation", async () => {
+ vi.mocked(api.createUpdateReview).mockResolvedValue({ ...externalReview,
+ plan: { ...externalReview.plan, action: "restart", execution_blocked_reason: "not_upgrade",
+ guide: { ...externalReview.plan.guide!, reason: "restart", update_command: null, inspect_command: null } } });
+ render(view());
+ fireEvent.click(screen.getByText("Update entry"));
+ await screen.findByRole("heading", { name: "Restart and verify" });
+ expect(screen.getByRole("button", { name: "Check running gateway" })).toBeVisible();
+ expect(screen.queryByLabelText("Update command")).not.toBeInTheDocument();
+ expect(api.prepareUpdate).not.toHaveBeenCalled();
+ });
+ it("does not send a managed-install user to the terminal during a long reconnect", async () => {
+ vi.useFakeTimers();
+ connectionStatus = "closed";
+ sessionStorage.setItem("nanobot.pending-update.v1", id);
+ sessionStorage.setItem("nanobot.pending-update-recovery.v1", JSON.stringify({
+ id, command: "private recovery command", automatic: true,
+ }));
+ render(view());
+ await act(async () => { await vi.advanceTimersByTimeAsync(123_000); });
+ expect(screen.getByText(/nanobot will try to restore service/)).toBeVisible();
+ expect(screen.queryByDisplayValue("private recovery command")).not.toBeInTheDocument();
+ expect(api.executeUpdate).not.toHaveBeenCalled();
+ expect(api.readUpdateJob).not.toHaveBeenCalled();
+ });
+ it("reports a restored service without claiming the update succeeded or asking for terminal repair", async () => {
+ sessionStorage.setItem("nanobot.pending-update.v1", id);
+ vi.mocked(api.readUpdateJob).mockResolvedValue({ job: {
+ ...job("failed", "confirmed"), previous_version: "0.3.5", service_restored: true,
+ mutation_started: true, recovery_command: "private recovery command",
+ } });
+ render(view());
+ await screen.findByText("Previous version restored");
+ expect(screen.getByText(/v0.3.5 is running again/)).toBeInTheDocument();
+ expect(screen.queryByText("Update complete")).not.toBeInTheDocument();
+ expect(screen.queryByDisplayValue("private recovery command")).not.toBeInTheDocument();
+ expect(api.executeUpdate).not.toHaveBeenCalled();
+ });
+ it("keeps polling a failed attempt while its independent recovery owner is active", async () => {
+ sessionStorage.setItem("nanobot.pending-update.v1", id);
+ vi.mocked(api.readUpdateJob).mockResolvedValueOnce({ job: {
+ ...job("failed", "confirmed"), recovery_active: true, mutation_started: true,
+ } }).mockResolvedValue({ job: {
+ ...job("failed", "confirmed"), previous_version: "0.3.5", service_restored: true,
+ } });
+ render(view());
+ await screen.findByText("Previous version restored", {}, { timeout: 4000 });
+ expect(api.readUpdateJob).toHaveBeenCalledTimes(2);
+ expect(api.executeUpdate).not.toHaveBeenCalled();
+ });
+ it.each(["0.3.7.dev42", "0.3.7"])("shows preview risk only for a preview installation target (%s)", async (version) => {
+ vi.mocked(api.createUpdateReview).mockResolvedValue({ ...review, plan: { ...review.plan, target_version: version } });
+ render(view());
+ fireEvent.click(screen.getByText("Update entry"));
+ await screen.findByRole("button", { name: "Update & restart" });
+ expect(screen.queryByText("This is a preview release and may have bugs.") !== null).toBe(version.includes(".dev"));
+ expect(api.prepareUpdate).not.toHaveBeenCalled();
+ expect(api.executeUpdate).not.toHaveBeenCalled();
+ });
+ it.each(["preparation_requested", "preparing"] as const)("settles a refreshed %s job before reviewing a fresh plan, without the handoff extension", async (phase) => {
+ vi.useFakeTimers();
+ vi.mocked(api.prepareUpdate).mockResolvedValue({ job: job(phase) });
+ vi.mocked(api.readUpdateJob).mockResolvedValue({ job: job(phase) });
+ let resolveSettlement!: (value: { job: api.UpdateJob }) => void;
+ vi.mocked(api.settleUpdate).mockImplementation(() => new Promise(resolve => { resolveSettlement = resolve; }));
+ const mounted = render(view("gateway-a", true, false));
+ fireEvent.click(screen.getByText("Update entry"));
+ await act(async () => {});
+ fireEvent.click(screen.getByRole("button", { name: "Update & restart" }));
+ await act(async () => {});
+ expect(screen.getByRole("button", { name: "Please wait" })).toBeDisabled();
+ expect(screen.queryByRole("button", { name: "Review update" })).not.toBeInTheDocument();
+ mounted.unmount();
+
+ // A refresh restores the durable ID, not the old tab's installation consent.
+ render(view("gateway-a", true, false));
+ await act(async () => {});
+ expect(screen.getByRole("button", { name: "Review update" })).toBeEnabled();
+ await act(async () => { await vi.advanceTimersByTimeAsync(123_000); });
+ expect(screen.getByRole("button", { name: "Review update" })).toBeEnabled();
+ expect(api.settleUpdate).not.toHaveBeenCalled();
+ expect(api.createUpdateReview).toHaveBeenCalledOnce();
+ expect(sessionStorage.getItem("nanobot.pending-update.v1")).toBe(id);
+
+ const nextId = "81c91a73-842e-42e9-aeb4-61a5bfe51135";
+ vi.mocked(api.createUpdateReview).mockResolvedValue({ ...review, plan: { ...review.plan, id: nextId, target_version: "0.3.7" } });
+ fireEvent.click(screen.getByRole("button", { name: "Review update" }));
+ await act(async () => {});
+ expect(screen.getByRole("button", { name: "Please wait" })).toBeDisabled();
+ expect(api.createUpdateReview).toHaveBeenCalledOnce();
+ expect(sessionStorage.getItem("nanobot.pending-update.v1")).toBe(id);
+ await act(async () => resolveSettlement({ job: job("preparation_failed") }));
+ expect(screen.getByText(/Updating to v0.3.7/)).toBeVisible();
+ expect(screen.getByRole("button", { name: "Update & restart" })).toBeEnabled();
+ expect(api.settleUpdate).toHaveBeenCalledOnce();
+ expect(api.settleUpdate).toHaveBeenCalledWith(client, id);
+ expect(api.createUpdateReview).toHaveBeenCalledTimes(2);
+ expect(sessionStorage.getItem("nanobot.pending-update.v1")).toBeNull();
+ expect(sessionStorage.getItem("nanobot.pending-update-recovery.v1")).toBeNull();
+ await act(async () => { await vi.advanceTimersByTimeAsync(3000); });
+ expect(api.prepareUpdate).toHaveBeenCalledOnce();
+ expect(api.executeUpdate).not.toHaveBeenCalled();
+ });
+ it("keeps an active preparer's refused settlement and retries status read-only", async () => {
+ vi.useFakeTimers();
+ sessionStorage.setItem("nanobot.pending-update.v1", id);
+ vi.mocked(api.readUpdateJob).mockResolvedValue({ job: job("preparing") });
+ vi.mocked(api.settleUpdate).mockRejectedValue(new api.ApiError(409, "Preparation owner still active"));
+ render(view("gateway-a", true, false));
+ await act(async () => {});
+ fireEvent.click(screen.getByRole("button", { name: "Review update" }));
+ await act(async () => {});
+ expect(screen.getByText(/previous update could not be cleared safely/)).toBeVisible();
+ expect(sessionStorage.getItem("nanobot.pending-update.v1")).toBe(id);
+ fireEvent.click(screen.getByRole("button", { name: "Check again" }));
+ await act(async () => { await vi.advanceTimersByTimeAsync(600); });
+ expect(api.readUpdateJob).toHaveBeenCalledTimes(2);
+ expect(screen.getByRole("button", { name: "Review update" })).toBeEnabled();
+ await act(async () => { await vi.advanceTimersByTimeAsync(3000); });
+ expect(screen.getByRole("button", { name: "Review update" })).toBeEnabled();
+ expect(api.settleUpdate).toHaveBeenCalledOnce();
+ expect(api.createUpdateReview).not.toHaveBeenCalled();
+ expect(api.prepareUpdate).not.toHaveBeenCalled();
+ expect(api.executeUpdate).not.toHaveBeenCalled();
+ expect(sessionStorage.getItem("nanobot.pending-update.v1")).toBe(id);
+ });
+ it("keeps a lost preparation-settlement response recoverable without creating another job", async () => {
+ vi.useFakeTimers();
+ sessionStorage.setItem("nanobot.pending-update.v1", id);
+ sessionStorage.setItem("nanobot.pending-update-recovery.v1", JSON.stringify({ id, command: "saved recovery command" }));
+ let saved = job("preparing");
+ vi.mocked(api.readUpdateJob).mockImplementation(async () => ({ job: saved }));
+ vi.mocked(api.settleUpdate).mockImplementation(async () => {
+ saved = job("preparation_failed");
+ throw new Error("response lost after settlement");
+ });
+ const mounted = render(view("gateway-a", true, false));
+ await act(async () => {});
+ fireEvent.click(screen.getByRole("button", { name: "Review update" }));
+ await act(async () => {});
+ expect(sessionStorage.getItem("nanobot.pending-update.v1")).toBe(id);
+ expect(sessionStorage.getItem("nanobot.pending-update-recovery.v1")).toContain("saved recovery command");
+ fireEvent.click(screen.getByRole("button", { name: "Check again" }));
+ await act(async () => { await vi.advanceTimersByTimeAsync(600); });
+ expect(screen.getByText("Update did not finish")).toBeVisible();
+ expect(api.readUpdateJob).toHaveBeenCalledTimes(2);
+ expect(api.settleUpdate).toHaveBeenCalledOnce();
+ expect(api.createUpdateReview).not.toHaveBeenCalled();
+ expect(sessionStorage.getItem("nanobot.pending-update.v1")).toBe(id);
+ mounted.unmount();
+ render(view("gateway-a", true, false));
+ await act(async () => {});
+ expect(screen.getByText("Update did not finish")).toBeVisible();
+ expect(api.createUpdateReview).not.toHaveBeenCalled();
+ expect(api.prepareUpdate).not.toHaveBeenCalled();
+ expect(api.executeUpdate).not.toHaveBeenCalled();
+ });
+ it("retires a restored failed handoff and reviews a fresh plan before new consent", async () => {
+ sessionStorage.setItem("nanobot.pending-update.v1", id);
+ vi.mocked(api.readUpdateJob).mockResolvedValue({ job: job("handoff_failed", "previous") });
+ vi.mocked(api.settleUpdate).mockResolvedValue({ job: job("cancelled", "previous") });
+ const nextId = "81c91a73-842e-42e9-aeb4-61a5bfe51135";
+ vi.mocked(api.createUpdateReview).mockResolvedValue({ ...review, plan: { ...review.plan, id: nextId } });
+ render(view());
+ fireEvent.click(await screen.findByRole("button", { name: "Review update" }));
+ await screen.findByRole("button", { name: "Update & restart" });
+ expect(api.settleUpdate).toHaveBeenCalledWith(client, id);
+ expect(api.createUpdateReview).toHaveBeenCalledOnce();
+ expect(api.executeUpdate).not.toHaveBeenCalled();
+ expect(api.prepareUpdate).not.toHaveBeenCalled();
+ expect(sessionStorage.getItem("nanobot.pending-update.v1")).toBeNull();
+ vi.mocked(api.prepareUpdate).mockResolvedValue({ job: { ...job("preparing"), id: nextId } });
+ vi.mocked(api.readUpdateJob).mockResolvedValue({ job: { ...job("ready"), id: nextId } });
+ fireEvent.click(screen.getByRole("button", { name: "Update & restart" }));
+ await waitFor(() => expect(api.executeUpdate).toHaveBeenCalledWith(client, nextId));
+ expect(api.executeUpdate).toHaveBeenCalledOnce();
+ });
+ it("keeps a refused settlement recoverable and Check again strictly read-only", async () => {
+ sessionStorage.setItem("nanobot.pending-update.v1", id);
+ vi.mocked(api.readUpdateJob).mockResolvedValue({ job: job("handoff_failed", "previous") });
+ vi.mocked(api.settleUpdate).mockRejectedValue(new api.ApiError(409, "Worker still active"));
+ render(view());
+ fireEvent.click(await screen.findByRole("button", { name: "Review update" }));
+ await screen.findByText(/previous update could not be cleared safely/);
+ expect(sessionStorage.getItem("nanobot.pending-update.v1")).toBe(id);
+ expect(api.createUpdateReview).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole("button", { name: "Check again" }));
+ await screen.findByRole("button", { name: "Review update" });
+ expect(api.readUpdateJob).toHaveBeenCalledTimes(2);
+ expect(api.settleUpdate).toHaveBeenCalledOnce();
+ expect(api.executeUpdate).not.toHaveBeenCalled();
+ });
+ it("can leave an expired READY review without bypassing gateway settlement", async () => {
+ sessionStorage.setItem("nanobot.pending-update.v1", id);
+ vi.mocked(api.readUpdateReview).mockResolvedValue({ ...review, execution_available: false,
+ plan: { ...review.plan, validity: "expired", execution_blocked_reason: "review_changed" } });
+ vi.mocked(api.settleUpdate).mockResolvedValue({ job: job("cancelled") });
+ render(view());
+ fireEvent.click(await screen.findByRole("button", { name: "Review update" }));
+ await screen.findByRole("button", { name: "Update & restart" });
+ expect(api.settleUpdate).toHaveBeenCalledWith(client, id);
+ expect(api.executeUpdate).not.toHaveBeenCalled();
+ });
+ it("recovers a lost settlement response after reload without restoring consent", async () => {
+ sessionStorage.setItem("nanobot.pending-update.v1", id);
+ vi.mocked(api.readUpdateJob).mockResolvedValue({ job: job("cancelled", "previous") });
+ vi.mocked(api.settleUpdate).mockResolvedValue({ job: job("cancelled", "previous") });
+ render(view());
+ fireEvent.click(await screen.findByRole("button", { name: "Review update" }));
+ await screen.findByRole("button", { name: "Update & restart" });
+ expect(api.executeUpdate).not.toHaveBeenCalled();
+ });
+ it("does not retry execution or send unsupported settlement to older hosts", async () => {
+ sessionStorage.setItem("nanobot.pending-update.v1", id);
+ vi.mocked(api.readUpdateJob).mockResolvedValue({ job: job("handoff_failed", "previous") });
+ render(view("gateway-a", true, false));
+ fireEvent.click(await screen.findByRole("button", { name: "Check again" }));
+ await waitFor(() => expect(api.readUpdateJob).toHaveBeenCalledTimes(2));
+ expect(api.executeUpdate).not.toHaveBeenCalled();
+ expect(api.settleUpdate).not.toHaveBeenCalled();
+ });
+ it("reviews on open and stages/executes the same exact plan only after confirmation", async () => {
+ render(view());
+ fireEvent.click(screen.getByText("Update entry"));
+ expect(await screen.findByText(/Updating to v0.3.6/)).toBeVisible();
+ expect(api.prepareUpdate).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole("button", { name: "Update & restart" }));
+ await waitFor(() => expect(api.executeUpdate).toHaveBeenCalledOnce());
+ expect(api.executeUpdate).toHaveBeenCalledWith(client, id);
+ expect(api.prepareUpdate).toHaveBeenCalledOnce();
+ expect(api.prepareUpdate).toHaveBeenCalledWith(client, id);
+ });
+ it("reads a restored READY job but never restores installation consent", async () => {
+ sessionStorage.setItem("nanobot.pending-update.v1", id);
+ render(view());
+ await screen.findByText(/Updating to v0.3.6/);
+ expect(api.createUpdateReview).not.toHaveBeenCalled();
+ expect(api.prepareUpdate).not.toHaveBeenCalled();
+ expect(api.executeUpdate).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole("button", { name: "Update & restart" }));
+ await waitFor(() => expect(api.executeUpdate).toHaveBeenCalledOnce());
+ });
+ it("waits for the restored review before enabling confirmation", async () => {
+ sessionStorage.setItem("nanobot.pending-update.v1", id);
+ let resolveReview!: (value: api.UpdateReviewResponse) => void;
+ vi.mocked(api.readUpdateReview).mockImplementation(() => new Promise(resolve => { resolveReview = resolve; }));
+ render(view());
+ await waitFor(() => expect(api.readUpdateReview).toHaveBeenCalledWith("gateway-a", id));
+ expect(screen.queryByRole("button", { name: "Update & restart" })).toBeNull();
+ expect(screen.getByRole("button", { name: "Please wait" })).toBeDisabled();
+ expect(screen.getByText("Checking the update…")).toBeVisible();
+ await act(async () => resolveReview(review));
+ expect(screen.getByRole("button", { name: "Update & restart" })).toBeEnabled();
+ expect(api.executeUpdate).not.toHaveBeenCalled();
+ });
+ it("allows a fresh review after a rejected stale preparation has no saved job", async () => {
+ // Another tab changed the channel after this plan was reviewed. The gateway
+ // rejects preparation before creating a job; a 404 alone is not that proof.
+ vi.mocked(api.prepareUpdate).mockRejectedValue(new api.ApiError(409, "Preparation refused"));
+ vi.mocked(api.readUpdateJob).mockRejectedValue(new api.ApiError(404, "No saved update"));
+ render(view());
+ fireEvent.click(screen.getByText("Update entry"));
+ fireEvent.click(await screen.findByRole("button", { name: "Update & restart" }));
+ await screen.findByText(/No package files were changed. Review the update again/);
+ expect(sessionStorage.getItem("nanobot.pending-update.v1")).toBeNull();
+ const nextId = "81c91a73-842e-42e9-aeb4-61a5bfe51135";
+ vi.mocked(api.createUpdateReview).mockResolvedValue({ ...review, plan: { ...review.plan, id: nextId } });
+ fireEvent.click(screen.getByRole("button", { name: "Check again" }));
+ await screen.findByRole("button", { name: "Update & restart" });
+ expect(api.createUpdateReview).toHaveBeenCalledTimes(2);
+ expect(api.prepareUpdate).toHaveBeenCalledOnce();
+ expect(api.executeUpdate).not.toHaveBeenCalled();
+ });
+ it("retains an unknown preparation outcome even if the job is not visible yet", async () => {
+ vi.mocked(api.prepareUpdate).mockRejectedValue(new api.ApiError(504, "Request timed out"));
+ vi.mocked(api.readUpdateJob).mockRejectedValue(new api.ApiError(404, "No saved update"));
+ render(view());
+ fireEvent.click(screen.getByText("Update entry"));
+ fireEvent.click(await screen.findByRole("button", { name: "Update & restart" }));
+ await screen.findByText(/Could not read the saved update/);
+ expect(sessionStorage.getItem("nanobot.pending-update.v1")).toBe(id);
+ fireEvent.click(screen.getByRole("button", { name: "Check again" }));
+ await waitFor(() => expect(api.readUpdateJob).toHaveBeenCalledTimes(2));
+ expect(api.createUpdateReview).toHaveBeenCalledOnce();
+ expect(api.prepareUpdate).toHaveBeenCalledOnce();
+ expect(api.executeUpdate).not.toHaveBeenCalled();
+ });
+ it("preserves a durable job after a preparation error instead of granting new consent", async () => {
+ vi.mocked(api.prepareUpdate).mockRejectedValue(new api.ApiError(409, "Read the saved state"));
+ render(view());
+ fireEvent.click(screen.getByText("Update entry"));
+ fireEvent.click(await screen.findByRole("button", { name: "Update & restart" }));
+ await waitFor(() => expect(api.readUpdateJob).toHaveBeenCalled());
+ await screen.findByRole("button", { name: "Update & restart" });
+ expect(sessionStorage.getItem("nanobot.pending-update.v1")).toBe(id);
+ expect(api.createUpdateReview).toHaveBeenCalledOnce();
+ expect(api.prepareUpdate).toHaveBeenCalledOnce();
+ expect(api.executeUpdate).not.toHaveBeenCalled();
+ });
+ it("never creates or executes a second job after a lost execution response", async () => {
+ vi.mocked(api.executeUpdate).mockRejectedValue(new Error("connection closed"));
+ vi.mocked(api.readUpdateJob).mockResolvedValueOnce({ job: job("ready") }).mockResolvedValue({ job: job("ready", "confirmed") });
+ render(view());
+ fireEvent.click(screen.getByText("Update entry"));
+ fireEvent.click(await screen.findByRole("button", { name: "Update & restart" }));
+ await screen.findByText(/request may have been accepted/);
+ fireEvent.click(screen.getByRole("button", { name: "Check again" }));
+ await waitFor(() => expect(api.readUpdateJob).toHaveBeenCalledTimes(2));
+ expect(api.executeUpdate).toHaveBeenCalledOnce();
+ expect(api.createUpdateReview).toHaveBeenCalledOnce();
+ expect(screen.getByRole("button", { name: "Checking..." })).toBeDisabled();
+ expect(await screen.findByRole("button", { name: "Please wait" })).toBeDisabled();
+ });
+ it("does not report completion until the actual running version matches", async () => {
+ sessionStorage.setItem("nanobot.pending-update.v1", id);
+ vi.mocked(api.readUpdateJob).mockResolvedValue({ job: job("succeeded", "confirmed") });
+ const mounted = render(view());
+ await screen.findByText("Reconnecting…");
+ expect(screen.queryByText("Update complete")).toBeNull();
+ mounted.unmount();
+ vi.mocked(api.readUpdateJob).mockResolvedValue({ job: { ...job("succeeded", "confirmed"), running_version: "0.3.6" } });
+ render(view());
+ expect(await screen.findByText("Update complete")).toBeVisible();
+ expect(screen.getByText("Now running v0.3.6.")).toBeVisible();
+ expect(screen.getAllByRole("button").filter(button => button.textContent === "Done")).toHaveLength(1);
+ });
+ it("waits for authenticated reconnect when a restart invalidates an in-flight journal read", async () => {
+ vi.useFakeTimers();
+ sessionStorage.setItem("nanobot.pending-update.v1", id);
+ let rejectRead!: (reason: unknown) => void;
+ vi.mocked(api.readUpdateJob).mockImplementationOnce(() => new Promise((_, reject) => { rejectRead = reject; }));
+ const mounted = render(view());
+ await act(async () => {
+ connectionStatus = "reconnecting";
+ rejectRead(new api.ApiError(401, "Unauthorized"));
+ });
+ expect(screen.getByText("Reconnecting…")).toBeVisible();
+ expect(screen.queryByText(/Could not read the saved update/)).toBeNull();
+ await act(async () => { await vi.advanceTimersByTimeAsync(3000); });
+ expect(api.readUpdateJob).toHaveBeenCalledTimes(1);
+
+ // Bootstrap renews the API token before the socket finishes reconnecting.
+ mounted.rerender(view("renewed-gateway-a"));
+ expect(api.readUpdateJob).toHaveBeenCalledTimes(1);
+ vi.mocked(api.readUpdateJob).mockResolvedValue({ job: {
+ ...job("succeeded", "confirmed"), mutation_started: true, running_version: "0.3.6",
+ } });
+ connectionStatus = "open";
+ await act(async () => { await vi.advanceTimersByTimeAsync(1500); });
+ expect(api.readUpdateJob).toHaveBeenLastCalledWith("renewed-gateway-a", id);
+ expect(screen.getByText("Update complete")).toBeVisible();
+ expect(api.createUpdateReview).not.toHaveBeenCalled();
+ expect(api.prepareUpdate).not.toHaveBeenCalled();
+ expect(api.executeUpdate).not.toHaveBeenCalled();
+ });
+ it("still reports rejected journal access on an authenticated connection", async () => {
+ sessionStorage.setItem("nanobot.pending-update.v1", id);
+ vi.mocked(api.readUpdateJob).mockRejectedValue(new api.ApiError(401, "Unauthorized"));
+ render(view());
+ expect(await screen.findByText(/Could not read the saved update/)).toBeVisible();
+ expect(screen.getByRole("button", { name: "Check again" })).toBeEnabled();
+ expect(api.executeUpdate).not.toHaveBeenCalled();
+ });
+ it("replaces a prolonged reconnect with the actual journal error and allows a read-only retry", async () => {
+ vi.useFakeTimers();
+ sessionStorage.setItem("nanobot.pending-update.v1", id);
+ connectionStatus = "reconnecting";
+ render(view());
+ await act(async () => { await vi.advanceTimersByTimeAsync(123_000); });
+ expect(screen.getByText("Reconnecting…")).toBeVisible();
+ connectionStatus = "open";
+ vi.mocked(api.readUpdateJob).mockRejectedValue(new api.ApiError(403, "Forbidden"));
+ await act(async () => { await vi.advanceTimersByTimeAsync(1500); });
+ expect(screen.getByText(/Could not read the saved update/)).toBeVisible();
+ expect(screen.queryByText("Reconnecting…")).toBeNull();
+ vi.mocked(api.readUpdateJob).mockResolvedValue({ job: {
+ ...job("succeeded", "confirmed"), running_version: "0.3.6",
+ } });
+ await act(async () => { fireEvent.click(screen.getByRole("button", { name: "Check again" })); });
+ await act(async () => { await vi.advanceTimersByTimeAsync(600); });
+ expect(screen.getByText("Update complete")).toBeVisible();
+ expect(api.prepareUpdate).not.toHaveBeenCalled();
+ expect(api.executeUpdate).not.toHaveBeenCalled();
+ });
+ it("keeps one preparation when double-clicked, hidden and reopened", async () => {
+ let resolve!: (value: { job: api.UpdateJob }) => void;
+ vi.useFakeTimers();
+ vi.mocked(api.prepareUpdate).mockImplementation(() => new Promise(done => { resolve = done; }));
+ vi.mocked(api.readUpdateJob).mockResolvedValue({ job: job("preparing") });
+ render(view("gateway-a", true, false));
+ fireEvent.click(screen.getByText("Update entry"));
+ await act(async () => {});
+ const button = screen.getByRole("button", { name: "Update & restart" });
+ fireEvent.click(button);
+ fireEvent.click(button);
+ fireEvent.click(screen.getByRole("button", { name: "Hide" }));
+ fireEvent.click(screen.getByText("Update entry"));
+ await act(async () => resolve({ job: job("preparing") }));
+ await act(async () => { await vi.advanceTimersByTimeAsync(123_000); });
+ expect(screen.getByRole("button", { name: "Please wait" })).toBeDisabled();
+ expect(screen.queryByRole("button", { name: "Review update" })).not.toBeInTheDocument();
+ expect(api.settleUpdate).not.toHaveBeenCalled();
+ expect(api.executeUpdate).not.toHaveBeenCalled();
+ vi.mocked(api.readUpdateJob).mockResolvedValue({ job: job("ready") });
+ await act(async () => { await vi.advanceTimersByTimeAsync(1500); });
+ expect(api.executeUpdate).toHaveBeenCalledOnce();
+ expect(api.createUpdateReview).toHaveBeenCalledOnce();
+ expect(api.prepareUpdate).toHaveBeenCalledOnce();
+ expect(api.executeUpdate).toHaveBeenCalledWith(client, id);
+ });
+ it("acknowledges a read-only retry even when the same failure returns immediately", async () => {
+ vi.useFakeTimers();
+ sessionStorage.setItem("nanobot.pending-update.v1", id);
+ vi.mocked(api.readUpdateJob).mockResolvedValue({ job: {
+ ...job("restart_failed", "confirmed"), mutation_started: true,
+ } });
+ render(view());
+ await act(async () => {});
+ const retry = screen.getByRole("button", { name: "Check again" });
+ fireEvent.click(retry);
+ fireEvent.click(retry);
+ await act(async () => { await vi.advanceTimersByTimeAsync(599); });
+ expect(screen.getByRole("button", { name: "Checking..." })).toBeDisabled();
+ expect(api.readUpdateJob).toHaveBeenCalledTimes(2);
+ await act(async () => { await vi.advanceTimersByTimeAsync(1); });
+ expect(screen.getByRole("button", { name: "Check again" })).toBeEnabled();
+ expect(screen.getByText("Update did not finish")).toBeVisible();
+ expect(api.createUpdateReview).not.toHaveBeenCalled();
+ expect(api.prepareUpdate).not.toHaveBeenCalled();
+ expect(api.executeUpdate).not.toHaveBeenCalled();
+ });
+ it("can reopen a hidden saved update from About even after the new version is installed", async () => {
+ sessionStorage.setItem("nanobot.pending-update.v1", id);
+ vi.mocked(api.readUpdateJob).mockResolvedValue({ job: {
+ ...job("restart_failed", "confirmed"), mutation_started: true, running_version: "0.3.6",
+ } });
+ render(<ClientProvider client={client} token="gateway-a" checkUpdatesOnConnect webuiCapabilities={["webui.update-flow.v1"]}>
+ <AboutSettings settings={settingsPayload()} />
+ </ClientProvider>);
+ fireEvent.click(await screen.findByRole("button", { name: "Close" }));
+ expect(screen.queryByRole("alertdialog")).toBeNull();
+ expect(screen.getByText("You're up to date")).toBeVisible();
+ fireEvent.click(screen.getByRole("button", { name: "View details" }));
+ expect(screen.getByRole("alertdialog", { name: "Update did not finish" })).toBeVisible();
+ expect(api.createUpdateReview).not.toHaveBeenCalled();
+ expect(api.prepareUpdate).not.toHaveBeenCalled();
+ expect(api.executeUpdate).not.toHaveBeenCalled();
+ });
+ it("ignores an old gateway's late review without starting an installation", async () => {
+ let resolve!: (value: api.UpdateReviewResponse) => void;
+ vi.mocked(api.createUpdateReview).mockImplementation(() => new Promise(done => { resolve = done; }));
+ const mounted = render(view());
+ fireEvent.click(screen.getByText("Update entry"));
+ mounted.rerender(view("gateway-b"));
+ await act(async () => resolve(review));
+ expect(screen.queryByRole("alertdialog")).toBeNull();
+ expect(api.prepareUpdate).not.toHaveBeenCalled();
+ });
+ it("keeps unsupported or unauthorized installations read-only", async () => {
+ vi.mocked(api.createUpdateReview).mockResolvedValue({ ...review, installation_allowed: false });
+ render(view());
+ fireEvent.click(screen.getByText("Update entry"));
+ expect(await screen.findByText(/Open this gateway on localhost/)).toBeVisible();
+ expect(screen.queryByRole("button", { name: "Update & restart" })).toBeNull();
+ expect(screen.getByRole("button", { name: "Close" })).toBeEnabled();
+ expect(api.prepareUpdate).not.toHaveBeenCalled();
+ });
+ it("does not offer the flow to older hosts without its optional capability", () => {
+ render(view("gateway-a", false));
+ expect(screen.getByText("Update entry")).toBeDisabled();
+ expect(api.createUpdateReview).not.toHaveBeenCalled();
+ });
+ it("shows the saved host recovery command after mutation failure without executing it", async () => {
+ sessionStorage.setItem("nanobot.pending-update.v1", id);
+ const command = `python3 -I -S ~/.nanobot/updates/recover.py ${id} --repair`;
+ vi.mocked(api.readUpdateJob).mockResolvedValue({ job: {
+ ...job("failed", "confirmed"), mutation_started: true, recovery_command: command,
+ } });
+ render(view());
+ expect(await screen.findByDisplayValue(command)).toBeVisible();
+ expect(screen.getByRole("button", { name: "Check again" })).toBeEnabled();
+ vi.mocked(api.readUpdateJob).mockResolvedValue({ job: {
+ ...job("succeeded", "confirmed"), running_version: "0.3.6", mutation_started: true,
+ } });
+ fireEvent.click(screen.getByRole("button", { name: "Check again" }));
+ expect(await screen.findByText("Update complete")).toBeVisible();
+ expect(api.executeUpdate).not.toHaveBeenCalled();
+ expect(JSON.parse(sessionStorage.getItem("nanobot.pending-update-recovery.v1") || "{}").command).toBe(command);
+ });
+ it("shows recovery after an admitted job fails during backup before package mutation", async () => {
+ sessionStorage.setItem("nanobot.pending-update.v1", id);
+ const command = `python3 -I -S /private/update/recover.py ${id} --repair`;
+ vi.mocked(api.readUpdateJob).mockResolvedValue({ job: {
+ ...job("failed", "confirmed"), recovery_command: command,
+ } });
+ render(view());
+ expect(await screen.findByDisplayValue(command)).toBeVisible();
+ expect(screen.getByText(/The update stopped before installation. No package files were changed/)).toBeVisible();
+ expect(screen.getAllByText(/Run this command in a terminal/)).toHaveLength(1);
+ fireEvent.click(screen.getByRole("button", { name: "Check again" }));
+ await waitFor(() => expect(api.readUpdateJob).toHaveBeenCalledTimes(2));
+ expect(api.createUpdateReview).not.toHaveBeenCalled();
+ expect(api.prepareUpdate).not.toHaveBeenCalled();
+ expect(api.executeUpdate).not.toHaveBeenCalled();
+ });
+});
diff --git a/webui/src/tests/update-notice.test.tsx b/webui/src/tests/update-notice.test.tsx
new file mode 100644
index 000000000..ffed18c86
--- /dev/null
+++ b/webui/src/tests/update-notice.test.tsx
@@ -0,0 +1,195 @@
+import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { useState } from "react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { Sidebar } from "@/components/Sidebar";
+import { AboutSettings } from "@/components/settings/overview/OverviewSettings";
+import { UpdateNotice } from "@/components/UpdateNotice";
+import { ClientProvider } from "@/providers/ClientProvider";
+import { useVersionCheck } from "@/providers/VersionCheckProvider";
+import { NanobotClient } from "@/lib/nanobot-client";
+import { jsonResponse, settingsPayload } from "@/tests/settings-test-utils";
+
+afterEach(() => { cleanup(); vi.unstubAllGlobals(); vi.useRealTimers(); });
+const client = new NanobotClient({ url: "ws://localhost:8765" });
+const available = (version = "0.3.6") => ({ updateAvailable: { currentVersion: "0.3.5", latestVersion: version } });
+
+it.each([
+ ["uv", "Update via uv"], ["pipx", "Update via pipx"], ["pip", "Update via pip"],
+ ["source", "Update via source checkout"], ["container", "Update via container deployment"],
+ ["managed", "Update"], ["future-owner", "Update"],
+])("labels the update entry with the detected owner (%s)", async (method, label) => {
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(jsonResponse({ ...available(), installation_method: method })));
+ const request = vi.fn();
+ render(<ClientProvider token="test" client={client}><AboutSettings settings={settingsPayload()} onRequestUpdate={request} /></ClientProvider>);
+ const entry = await screen.findByRole("button", { name: label });
+ fireEvent.click(entry);
+ expect(request).toHaveBeenCalledOnce();
+});
+
+function Surface() {
+ const update = useVersionCheck();
+ const [about, setAbout] = useState(false);
+ return <>
+ <input aria-label="Draft" />
+ {update.result?.type === "update" && update.dismissedVersion !== update.result.latestVersion && (
+ <UpdateNotice version={update.result.latestVersion} onOpen={() => setAbout(true)} onDismiss={update.dismiss} />
+ )}
+ <button onClick={() => void update.check()}>Refresh version</button>
+ {about && <AboutSettings settings={{ ...settingsPayload(), version: { current: "0.3.5" } }} />}
+ </>;
+}
+
+const view = (token = "host-a") => <ClientProvider client={client} token={token} checkUpdatesOnConnect><Surface /></ClientProvider>;
+
+describe("Sidebar update entry", () => {
+ it("keeps About update actions available after dismissing the sidebar notice", async () => {
+ const fetcher = vi.fn(async () => jsonResponse(available()));
+ vi.stubGlobal("fetch", fetcher);
+ const { rerender } = render(view("dismiss-sidebar"));
+ fireEvent.click(await screen.findByRole("button", { name: "Update available v0.3.6" }));
+ fireEvent.click(screen.getByRole("button", { name: "Dismiss update notice" }));
+ rerender(<ClientProvider client={client} token="dismiss-sidebar" checkUpdatesOnConnect>
+ <Surface />
+ <AboutSettings settings={settingsPayload()} onRequestUpdate={vi.fn()} />
+ </ClientProvider>);
+ expect(await screen.findByRole("button", { name: /^Update$/ })).toBeVisible();
+ expect(screen.queryByRole("button", { name: "Update available v0.3.6" })).toBeNull();
+ expect(screen.queryByRole("button", { name: "Dismiss update notice" })).toBeNull();
+ expect(fetcher).toHaveBeenCalledTimes(2);
+ });
+
+ it("automatically checks each About entry, shares an in-flight check and retries failures without a loading delay", async () => {
+ let resolve!: (response: Response) => void;
+ const fetcher = vi.fn().mockImplementation(() => new Promise<Response>(done => { resolve = done; }));
+ vi.stubGlobal("fetch", fetcher);
+ const surface = (about: boolean) => <ClientProvider client={client} token="about-entry" checkUpdatesOnConnect>
+ {about && <AboutSettings settings={settingsPayload()} />}
+ </ClientProvider>;
+ const mounted = render(surface(false));
+ expect(fetcher).toHaveBeenCalledOnce();
+ mounted.rerender(surface(true));
+ expect(screen.getByRole("status")).toHaveTextContent("Checking...");
+ expect(fetcher).toHaveBeenCalledOnce();
+ await act(async () => resolve(jsonResponse({ updateAvailable: null })));
+ expect(screen.getByText("You're up to date")).toBeVisible();
+
+ mounted.rerender(surface(false));
+ mounted.rerender(surface(true));
+ expect(fetcher).toHaveBeenCalledTimes(2);
+ expect(screen.getByRole("status")).toHaveTextContent("Checking...");
+ await act(async () => resolve(jsonResponse({ updateAvailable: null })));
+ fetcher.mockRejectedValueOnce(new Error("Connection unavailable"));
+ fireEvent.click(screen.getByRole("button", { name: "Check again" }));
+ expect(await screen.findByText("Connection unavailable")).toBeVisible();
+ fireEvent.click(screen.getByRole("button", { name: "Retry" }));
+ expect(screen.getByRole("status")).toHaveTextContent("Checking...");
+ expect(fetcher).toHaveBeenCalledTimes(4);
+ await act(async () => resolve(jsonResponse(available())));
+ expect(screen.getByRole("link", { name: "Installation guide" })).toBeVisible();
+ });
+ it("opens the provided update confirmation directly without navigating through details", () => {
+ const openDetails = vi.fn();
+ const requestUpdate = vi.fn();
+ render(<UpdateNotice version="0.3.6" onOpen={openDetails} onDismiss={vi.fn()} onRequestUpdate={requestUpdate} />);
+ expect(requestUpdate).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole("button", { name: "Update available v0.3.6" }));
+ expect(requestUpdate).toHaveBeenCalledOnce();
+ expect(openDetails).not.toHaveBeenCalled();
+ expect(screen.queryByRole("button", { name: "View details" })).toBeNull();
+ });
+
+ it("uses the same direct confirmation in About when an update action is available", async () => {
+ vi.stubGlobal("fetch", vi.fn(async () => jsonResponse(available())));
+ const requestUpdate = vi.fn();
+ render(<ClientProvider client={client} token="about-update" checkUpdatesOnConnect>
+ <AboutSettings settings={{ ...settingsPayload(), version: { current: "0.3.5" } }} onRequestUpdate={requestUpdate} />
+ </ClientProvider>);
+ const button = await screen.findByRole("button", { name: /^Update$/ });
+ expect(screen.queryByRole("link", { name: "Installation guide" })).toBeNull();
+ expect(requestUpdate).not.toHaveBeenCalled();
+ fireEvent.click(button);
+ expect(requestUpdate).toHaveBeenCalledOnce();
+ });
+
+ it("opens in place, preserves the draft, and navigates only from View details", async () => {
+ const fetcher = vi.fn(async () => jsonResponse(available()));
+ vi.stubGlobal("fetch", fetcher);
+ render(view());
+ fireEvent.change(screen.getByLabelText("Draft"), { target: { value: "Keep writing" } });
+ fireEvent.click(await screen.findByRole("button", { name: "Update available v0.3.6" }));
+ expect(screen.getByRole("dialog", { name: "Update available v0.3.6" })).toBeVisible();
+ expect(screen.queryByRole("link", { name: "Installation guide" })).toBeNull();
+ expect(screen.getByLabelText("Draft")).toHaveValue("Keep writing");
+ fireEvent.keyDown(screen.getByRole("dialog"), { key: "Escape" });
+ await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());
+ expect(screen.getByRole("button", { name: "Update available v0.3.6" })).toHaveFocus();
+ fireEvent.click(screen.getByRole("button", { name: "Update available v0.3.6" }));
+ fireEvent.click(screen.getByRole("button", { name: "View details" }));
+ expect(await screen.findByRole("link", { name: "Installation guide" })).toHaveAttribute("href", "https://github.com/HKUDS/nanobot#-install");
+ expect(fetcher).toHaveBeenCalledTimes(2);
+ expect(fetcher).toHaveBeenCalledWith("/api/settings/version-check", expect.any(Object));
+ });
+
+ it("deduplicates checks, dismisses one version, and shows a later version", async () => {
+ let resolve!: (response: Response) => void;
+ const fetcher = vi.fn().mockImplementationOnce(() => new Promise<Response>((done) => { resolve = done; }))
+ .mockResolvedValueOnce(jsonResponse(available())).mockResolvedValueOnce(jsonResponse(available("0.3.7")));
+ vi.stubGlobal("fetch", fetcher);
+ render(view());
+ fireEvent.click(screen.getByText("Refresh version"));
+ expect(fetcher).toHaveBeenCalledTimes(1);
+ await act(async () => resolve(jsonResponse(available())));
+ fireEvent.click(screen.getByRole("button", { name: "Update available v0.3.6" }));
+ fireEvent.click(screen.getByRole("button", { name: "Dismiss update notice" }));
+ expect(screen.queryByRole("button", { name: "Update available v0.3.6" })).toBeNull();
+ fireEvent.click(screen.getByText("Refresh version"));
+ await waitFor(() => expect(fetcher).toHaveBeenCalledTimes(2));
+ expect(screen.queryByRole("button", { name: "Update available v0.3.6" })).toBeNull();
+ fireEvent.click(screen.getByText("Refresh version"));
+ expect(await screen.findByRole("button", { name: "Update available v0.3.7" })).toBeVisible();
+ });
+
+ it("ignores late host results without remounting the client or losing its draft", async () => {
+ let resolveOld!: (response: Response) => void;
+ const fetcher = vi.fn().mockImplementationOnce(() => new Promise<Response>((done) => { resolveOld = done; }))
+ .mockResolvedValueOnce(jsonResponse({ updateAvailable: null }));
+ vi.stubGlobal("fetch", fetcher);
+ const { rerender } = render(view());
+ fireEvent.change(screen.getByLabelText("Draft"), { target: { value: "Keep this draft" } });
+ rerender(view("host-b"));
+ await waitFor(() => expect(fetcher).toHaveBeenCalledTimes(2));
+ await act(async () => resolveOld(jsonResponse(available())));
+ expect(screen.queryByRole("button", { name: /Update available/ })).toBeNull();
+ expect(screen.getByLabelText("Draft")).toHaveValue("Keep this draft");
+ });
+
+ it.each([null, new Error("offline")])("keeps an unavailable check quiet (%s)", async (failure) => {
+ const fetcher = vi.fn().mockImplementation(() => failure ? Promise.reject(failure) : Promise.resolve(jsonResponse({ updateAvailable: null })));
+ vi.stubGlobal("fetch", fetcher);
+ render(view());
+ await waitFor(() => expect(fetcher).toHaveBeenCalledTimes(1));
+ expect(screen.queryByRole("button", { name: /Update available/ })).toBeNull();
+ expect(screen.queryByRole("alert")).toBeNull();
+ });
+
+ it("renders the same entry in expanded and collapsed navigation", () => {
+ const noop = vi.fn();
+ const props = { sessions: [], activeKey: null, loading: false, newChatActive: false,
+ onNewChat: noop, onSelect: noop, onRequestDelete: noop, onTogglePin: noop, onRequestRename: noop,
+ onToggleArchive: noop, onToggleGroup: noop, onRequestRenameProject: noop, onNewChatInProject: noop,
+ onOpenSettings: noop, onOpenApps: noop, onOpenSkills: noop, onOpenAutomations: noop, onOpenChannels: noop,
+ onOpenSearch: noop, onToggleArchived: noop, onOpenUpdates: noop,
+ availableUpdate: { version: "0.3.6", onDismiss: noop } };
+ const { rerender } = render(<ClientProvider client={client} token="test"><Sidebar {...props} /></ClientProvider>);
+ fireEvent.click(screen.getByRole("button", { name: "Update available v0.3.6" }));
+ expect(noop).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole("button", { name: "View details" }));
+ expect(noop).toHaveBeenCalledOnce();
+ rerender(<ClientProvider client={client} token="test"><Sidebar {...props} collapsed /></ClientProvider>);
+ expect(screen.getByRole("button", { name: "Update available v0.3.6" })).toBeVisible();
+ expect(screen.queryByText("Update available")).toBeNull();
+ fireEvent.click(screen.getByRole("button", { name: "Update available v0.3.6" }));
+ expect(screen.getByRole("dialog", { name: "Update available v0.3.6" })).toBeVisible();
+ });
+});
diff --git a/webui/tsconfig.json b/webui/tsconfig.json
index 91a06654c..82d35ccca 100644
--- a/webui/tsconfig.json
+++ b/webui/tsconfig.json
@@ -22,14 +22,13 @@
"allowSyntheticDefaultImports": true,
"types": ["node", "vite/client", "vitest/globals", "@testing-library/jest-dom"],
+ "typeRoots": ["./node_modules/@types", "./node_modules"],
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"],
"vitest": ["./node_modules/vitest"],
"lucide-react": ["./node_modules/lucide-react"],
- "react": ["./node_modules/@types/react/index.d.ts"],
- "react/*": ["./node_modules/@types/react/*"],
"react-i18next": ["./node_modules/react-i18next"]
}
},