Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
fix(app): improve onboard UX, auto-confirm migrations, fix CSRF Origin (#74)
Genercf12033d24fd
diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex ea6b5d076..c9230ab75 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -26,22 +26,40 @@ importers:src/app:dependencies:+ citty:+ specifier: ^0.2.2+ version: 0.2.2commander:specifier: ^14.0.3version: 14.0.3+ playwright-core:+ specifier: ^1.59.1+ version: 1.59.1+ postal-mime:+ specifier: ^2.7.4+ version: 2.7.4wrangler:specifier: ^4.90.0version: 4.90.0(@cloudflare/[email protected])devDependencies:+ '@alook/cli':+ specifier: workspace:*+ version: link:../cli'@alook/shared':specifier: workspace:*version: link:../shared'@types/bun':specifier: ^1.3.13version: 1.3.13+ eslint:+ specifier: ^9.39.4+ version: 9.39.4([email protected])typescript:specifier: ^6.0.3version: 6.0.3+ typescript-eslint:+ specifier: ^8.59.3src/cli:dependencies:@@ -64,9 +82,15 @@ importers:'@types/bun':specifier: ^1.3.13version: 1.3.13+ eslint:+ specifier: ^10.3.0+ version: 10.3.0([email protected])typescript:specifier: ^6.0.3version: 6.0.3+ typescript-eslint:+ specifier: ^8.59.3vitest:specifier: ^4.1.5version: 4.1.5(@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))@@ -288,7 +312,7 @@ importers:version: 9.39.4([email protected])eslint-config-next:specifier: 16.2.6- version: 16.2.6(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])eslint-plugin-tailwind-canonical-classes:specifier: ^1.3.3version: 1.3.3([email protected]([email protected]))@@ -1293,14 +1317,26 @@ packages:resolution: {integrity: sha512-nJl2KGTlrf9GjLimgIru+V/mzgSK0ABCDQRvxw5BjURL7WfH5uoWmizbH7QB6MmnMBd8cIC9uceWnezL1VZWWw==}engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}+ '@eslint/[email protected]':+ resolution: {integrity: sha512-Y3kKLvC1dvTOT+oGlqNQ1XLqK6D1HU2YXPc52NmAlJZbMMWDzGYXMiPRJ8TYD39muD/OTjlZmNJ4ib7dvSrMBA==}+ engines: {node: ^20.19.0 || ^22.13.0 || >=24}+'@eslint/[email protected]':resolution: {integrity: sha512-gBrxN88gOIf3R7ja5K9slwNayVcZgK6SOUORm2uBzTeIEfeVaIhOpCtTox3P6R7o2jLFwLFTLnC7kU/RGcYEgw==}engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}+ '@eslint/[email protected]':+ resolution: {integrity: sha512-eIJYKTCECbP/nsKaaruF6LW967mtbQbsw4JTtSVkUQc9MneSkbrgPJAbKl9nWr0ZeowV8BfsarBmPpBzGelA2w==}+ engines: {node: ^20.19.0 || ^22.13.0 || >=24}+'@eslint/[email protected]':resolution: {integrity: sha512-yL/sLrpmtDaFEiUj1osRP4TI2MDz1AddJL+jZ7KSqvBuliN4xqYY54IfdN8qD8Toa6g1iloph1fxQNkjOxrrpQ==}engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}+ '@eslint/[email protected]':+ resolution: {integrity: sha512-MwcE1P+AZ4C6DWlpin/OmOA54mmIZ/+xZuJiQd4SyB29oAJjN30UW9wkKNptW2ctp4cEsvhlLY/CsQ1uoHDloQ==}+ engines: {node: ^20.19.0 || ^22.13.0 || >=24}+'@eslint/[email protected]':resolution: {integrity: sha512-4IlJx0X0qftVsN5E+/vGujTRIFtwuLbNsVUe7TO6zYPDR1O6nFwvwhIKEKSrl6dZchmYBITazxKoUYOjdtjlRg==}engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}@@ -1313,10 +1349,18 @@ packages:resolution: {integrity: sha512-VtAOaymWVfZcmZbp6E2mympDIHvyjXs/12LqWYjVw6qjrfF+VK+fyG33kChz3nnK+SU5/NeHOqrTEHS8sXO3OA==}engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}+ '@eslint/[email protected]':+ resolution: {integrity: sha512-vqTaUEgxzm+YDSdElad6PiRoX4t8VGDjCtt05zn4nU810UIx/uNEV7/lZJ6KwFThKZOzOxzXy48da+No7HZaMw==}+ engines: {node: ^20.19.0 || ^22.13.0 || >=24}+'@eslint/[email protected]':resolution: {integrity: sha512-43/qtrDUokr7LJqoF2c3+RInu/t4zfrpYdoSDfYyhg52rwLV6TnOvdG4fXm7IkSB3wErkcmJS9iEhjVtOSEjjA==}engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}+ '@eslint/[email protected]':+ resolution: {integrity: sha512-rZAP3aVgB9ds9KOeUSL+zZ21hPmo8dh6fnIFwRQj5EAZl9gzR7wxYbYXYysAM8CTqGmUGyp2S4kUdV17MnGuWQ==}+ engines: {node: ^20.19.0 || ^22.13.0 || >=24}+'@floating-ui/[email protected]':resolution: {integrity: sha512-1Ih4WTWyw0+lKyFMcBHGbb5U5FtuHJuujoyyr5zTaWS5EYMeT6Jb2AuDeftsCsEuchO+mM2ij5+q9crhydzLhQ==}@@ -2589,6 +2633,9 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==}+ '@types/[email protected]':+ resolution: {integrity: sha512-xJBAbDifo5hpffDBuHl0Y8ywswbiAp/Wi7Y/GtAgSlZyIABppyurxVueOPE8LUQOxdlgi6Zqce7uoEpqNTeiUw==}+'@types/[email protected]':resolution: {integrity: sha512-52CcUVNFyfb1A2ALocQw/Dd1BQFNmSdkuC3BkZ6iqhdMfQz7JWOFRuJFloOzjk+6WijU56m9oKXFAXc7o3Towg==}@@ -2654,63 +2701,63 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-oJoftv0LSuaDZE3Le4DbKX+KS9G36NzOeSap90UIK0yMA/NhKJhqlSGtNDORNRaIbQfzjXDrQa0ytJ6mNRGz/Q==}- '@typescript-eslint/[email protected]':- resolution: {integrity: sha512-j/bwmkBvHUtPNxzuWe5z6BEk3q54YRyGlBXkSsmfoih7zNrBvl5A9A98anlp/7JbyZcWIJ8KXo/3Tq/DjFLtuQ==}+ '@typescript-eslint/[email protected]':+ resolution: {integrity: sha512-PwFvSKsXGShKGW6n5bZOhGHEcCZXM8HofLK9fNsEwZXzFRjoY+XT1Vsf1zgyXdwTr0ZYz1/2tkZ0DBTT9jZjhw==}engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}peerDependencies:- '@typescript-eslint/parser': ^8.59.2+ '@typescript-eslint/parser': ^8.59.3eslint: ^8.57.0 || ^9.0.0 || ^10.0.0typescript: '>=4.8.4 <6.1.0'- '@typescript-eslint/[email protected]':- resolution: {integrity: sha512-plR3pp6D+SSUn1HM7xvSkx12/DhoHInI2YF35KAcVFNZvlC0gtrWqx7Qq1oH2Ssgi0vlFRCTbP+DZc7B9+TtsQ==}+ '@typescript-eslint/[email protected]':+ resolution: {integrity: sha512-HPwA+hVkfcriajbNvTmZv4VRauibay+cWArYUYq7u7W7PmGShMxbPxLvrwDme55a6d5alG3nrYfhyJ/G28XlLg==}engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}peerDependencies:eslint: ^8.57.0 || ^9.0.0 || ^10.0.0typescript: '>=4.8.4 <6.1.0'- '@typescript-eslint/[email protected]':- resolution: {integrity: sha512-+2hqvEkeyf/0FBor67duF0Ll7Ot8jyKzDQOSrxazF/danillRq2DwR9dLptsXpoZQqxE1UisSmoZewrlPas9Vw==}+ '@typescript-eslint/[email protected]':+ resolution: {integrity: sha512-ECiUWa/KYRGDFUqTNehaRgzDshnJfkTABJxVemHk4ko22gcr0ukloKjWvyQ64g8YCV/UI47kN1dbmjf/GaQYng==}engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}peerDependencies:typescript: '>=4.8.4 <6.1.0'- '@typescript-eslint/[email protected]':- resolution: {integrity: sha512-JzfyEpEtOU89CcFSwyNS3mu4MLvLSXqnmX05+aKBDM+TdR5jzcGOEBwxwGNxrEQ7p/z6kK2WyioCGBf2zZBnvg==}+ '@typescript-eslint/[email protected]':+ resolution: {integrity: sha512-t2LvZnoEfzKtnPjgeEu41xw5gxq9mQVfYy4OoZ4Vlt0sk3JwxmhCca/AR7DwOiHrjWgjAj6as4AhRLKSDfvZIA==}engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}- '@typescript-eslint/[email protected]':- resolution: {integrity: sha512-BKK4alN7oi4C/zv4VqHQ+uRU+lTa6JGIZ7s1juw7b3RHo9OfKB+bKX3u0iVZetdsUCBBkSbdWbarJbmN0fTeSw==}+ '@typescript-eslint/[email protected]':+ resolution: {integrity: sha512-PcIJHjmaREXLgIAIzLnSY9VucEzz8FKXsRgFa1DmdGCK/5tJpW03TKJF01Q6VZd1lLdz2sIKPWaDUZN9dp//dw==}engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}peerDependencies:typescript: '>=4.8.4 <6.1.0'- '@typescript-eslint/[email protected]':- resolution: {integrity: sha512-nhqaj1nmTdVVl/BP5omXNRGO38jn5iosis2vbdmupF2txCf8ylWT8lx+JlvMYYVqzGVKtjojUFoQ3JRWK+mfzQ==}+ '@typescript-eslint/[email protected]':+ resolution: {integrity: sha512-g71d8QD8UaiHGvrJwyIS1hCX5r63w6Jll+4VEYhEAHXTDIqX1JgxhTAbEHtKntL9kuc4jRo7/GWw5xfCepSccQ==}engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}peerDependencies:eslint: ^8.57.0 || ^9.0.0 || ^10.0.0typescript: '>=4.8.4 <6.1.0'- '@typescript-eslint/[email protected]':- resolution: {integrity: sha512-e82GVOE8Ps3E++Egvb6Y3Dw0S10u8NkQ9KXmtRhCWJJ8kDhOJTvtMAWnFL16kB1583goCWXsr0NieKCZMs2/0Q==}+ '@typescript-eslint/[email protected]':+ resolution: {integrity: sha512-ePFoH0g4ludssdRFqqDxQePCxU4WQyRa9+XVwjm7yLn0FKhMeoetC+qBEEI1Eyb1pGSDveTIT09Bvw2WhlGayg==}engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}- '@typescript-eslint/[email protected]':- resolution: {integrity: sha512-o0XPGNwcWw+FIwStOWn+BwBuEmL6QXP0rsvAFg7ET1dey1Nr6Wb1ac8p5HEsK0ygO/6mUxlk+YWQD9xcb/nnXg==}+ '@typescript-eslint/[email protected]':+ resolution: {integrity: sha512-CbRjVRAf7Lr9Kr8RopKcbY45p2VfmmHrm0ygOCYFi7oU8q19m0Fs/6iHS7kNOmwpp+ob07ZVcAqlxUod9lYdmg==}engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}peerDependencies:typescript: '>=4.8.4 <6.1.0'- '@typescript-eslint/[email protected]':- resolution: {integrity: sha512-Juw3EinkXqjaffxz6roowvV7GZT/kET5vSKKZT6upl5TXdWkLkYmNPXwDDL2Vkt2DPn0nODIS4egC/0AGxKo/Q==}+ '@typescript-eslint/[email protected]':+ resolution: {integrity: sha512-JAvT14goBzRzzzZyqq3P9BLArIxTtQURUtFgQ/V7FO+eU+Gg6ES+5ymOPP1wRxXcxAYeivCk4uS3jCKWI1K8Zg==}engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}peerDependencies:eslint: ^8.57.0 || ^9.0.0 || ^10.0.0typescript: '>=4.8.4 <6.1.0'- '@typescript-eslint/[email protected]':- resolution: {integrity: sha512-NwjLUnGy8/Zfx23fl50tRC8rYaYnM52xNRYFAXvmiil9yh1+K6aRVQMnzW6gQB/1DLgWt977lYQn7C+wtgXZiA==}+ '@typescript-eslint/[email protected]':+ resolution: {integrity: sha512-f1UQF7ggd42YiwI5wGrRaPsa+P0CINBlrkLPmGfpq/u/I/oVtecoEIfFR9ag/oa1sLOsRNZ6xehf6qMZhQGBDg==}engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}'@ungap/[email protected]':@@ -4120,6 +4167,10 @@ packages:resolution: {integrity: sha512-sNXOfKCn74rt8RICKMvJS7XKV/Xk9kA7DyJr8mJik3S7Cwgy3qlkkmyS2uQB3jiJg6VNdZd/pDBJu0nvG2NlTg==}engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}+ resolution: {integrity: sha512-xS90H51cKw0jltxmvmHy2Iai1LIqrfbw57b79w/J7MfvDfkIkFZ+kj6zC3BjtUwh150HsSSdxXZcsuv72miDFQ==}+ engines: {node: ^20.19.0 || ^22.13.0 || >=24}+resolution: {integrity: sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==}engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0}@@ -4132,6 +4183,16 @@ packages:resolution: {integrity: sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA==}engines: {node: ^20.19.0 || ^22.13.0 || >=24}+ resolution: {integrity: sha512-XbEXaRva5cF0ZQB8w6MluHA0kZZfV2DuCMJ3ozyEOHLwDpZX2Lmm/7Pp0xdJmI0GL1W05VH5VwIFHEm1Vcw2gw==}+ engines: {node: ^20.19.0 || ^22.13.0 || >=24}+ hasBin: true+ peerDependencies:+ jiti: '*'+ peerDependenciesMeta:+ jiti:+ optional: true+resolution: {integrity: sha512-XoMjdBOwe/esVgEvLmNsD3IRHkm7fbKIUGvrleloJXUZgDHig2IPWNniv+GwjyJXzuNqVjlr5+4yVUZjycJwfQ==}engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}@@ -4146,6 +4207,10 @@ packages:resolution: {integrity: sha512-j6PAQ2uUr79PZhBjP5C5fhl8e39FmRnOjsD5lGnWrFU8i2G776tBK7+nP8KuQUTTyAZUwfQqXAgrVH5MbH9CYQ==}engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}+ resolution: {integrity: sha512-7p3DrVEIopW1B1avAGLuCSh1jubc01H2JHc8B4qqGblmg5gI9yumBgACjWo4JlIc04ufug4xJ3SQI8HkS/Rgzw==}+ engines: {node: ^20.19.0 || ^22.13.0 || >=24}+resolution: {integrity: sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==}engines: {node: '>=4'}@@ -6396,8 +6461,8 @@ packages:resolution: {integrity: sha512-buUzX4sXC4efFX6xg2bw6/eZsCUh8qQwSavC4D9HpONMFlRbcHhD8Je5qwYdCpViR6q0qla2wPP+t91a2vgolg==}- resolution: {integrity: sha512-nBDSJw5B7Sl1YfsATG2XkW5qgUPODbJhXw++BKygi9w6O/NKS98/uY/nR/DxDq2axEjL6halHW1v+jhm/j1DBQ==}+ resolution: {integrity: sha512-fegtha91tq2DHphyoiBXVHjVi2YG9zFaRnboT9C28tO1en9Y3wJsfspuy40F+u5wl3hHVbw7cnd1b67kEGHb8g==}resolution: {integrity: sha512-w89qg7PI8wAdvX60bMDP+bFoD5Dvhm9oLheFp5O4a2QF0cSBGsBX4qZmadPMvVqlLJBBci+WqGGOAPvcDeNSVg==}@@ -6545,8 +6610,8 @@ packages:resolution: {integrity: sha512-zdu8XMNEDepKKR+XYOXAVPtWui0ly0NtohUscw+UmaHiAWT8hrV1rr//H6V+0DvJ3OQ19S979M0laLfX8rm82Q==}- resolution: {integrity: sha512-pJw051uomb3ZeCzGTpRb8RbEqB5Y4WWet8gl/GcTlU35BSx0PVdZ86/bqkQCyKKuraVQEK7r6kBHQXF+fBhkoQ==}+ resolution: {integrity: sha512-KgusgyDgG4LI8Ih/sWaCtZ06tckLAS5CvT5A4D1Q7bYVoAAyzwiZvE4BmwDHkhRVkvhRBepKeASoFzQetha7Fg==}engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}peerDependencies:eslint: ^8.57.0 || ^9.0.0 || ^10.0.0@@ -8317,6 +8382,11 @@ snapshots:'@esbuild/[email protected]':optional: true+ dependencies:+ eslint: 10.3.0([email protected])+ eslint-visitor-keys: 3.4.3+dependencies:eslint: 9.39.4([email protected])@@ -8332,14 +8402,30 @@ snapshots:transitivePeerDependencies:- supports-color+ '@eslint/[email protected]':+ dependencies:+ '@eslint/object-schema': 3.0.5+ debug: 4.4.3+ minimatch: 10.2.5+ transitivePeerDependencies:+ - supports-color+'@eslint/[email protected]':dependencies:'@eslint/core': 0.17.0+ '@eslint/[email protected]':+ dependencies:+ '@eslint/core': 1.2.1+'@eslint/[email protected]':dependencies:'@types/json-schema': 7.0.15+ '@eslint/[email protected]':+ dependencies:+ '@types/json-schema': 7.0.15+'@eslint/[email protected]':dependencies:ajv: 6.14.0@@ -8358,11 +8444,18 @@ snapshots:'@eslint/[email protected]': {}+ '@eslint/[email protected]': {}+'@eslint/[email protected]':dependencies:'@eslint/core': 0.17.0levn: 0.4.1+ '@eslint/[email protected]':+ dependencies:+ '@eslint/core': 1.2.1+ levn: 0.4.1+'@floating-ui/[email protected]':dependencies:'@floating-ui/utils': 0.2.11@@ -8820,7 +8913,7 @@ snapshots:'@paulirish/[email protected]':dependencies:legacy-javascript: 0.0.1- third-party-web: 0.29.0+ third-party-web: 0.29.2'@pkgr/[email protected]': {}@@ -9725,6 +9818,8 @@ snapshots:'@types/[email protected]': {}+ '@types/[email protected]': {}+'@types/[email protected]':dependencies:'@types/estree': 1.0.8@@ -9790,14 +9885,30 @@ snapshots:'@types/node': 25.6.2optional: true- '@typescript-eslint/[email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])':+ '@typescript-eslint/[email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])':+ dependencies:+ '@eslint-community/regexpp': 4.12.2+ '@typescript-eslint/scope-manager': 8.59.3+ '@typescript-eslint/visitor-keys': 8.59.3+ eslint: 10.3.0([email protected])+ ignore: 7.0.5+ natural-compare: 1.4.0+ ts-api-utils: 2.5.0([email protected])+ typescript: 6.0.3+ transitivePeerDependencies:+ - supports-color++ '@typescript-eslint/[email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])':dependencies:'@eslint-community/regexpp': 4.12.2- '@typescript-eslint/scope-manager': 8.59.2- '@typescript-eslint/visitor-keys': 8.59.2+ '@typescript-eslint/scope-manager': 8.59.3+ '@typescript-eslint/visitor-keys': 8.59.3eslint: 9.39.4([email protected])ignore: 7.0.5natural-compare: 1.4.0@@ -9806,41 +9917,65 @@ snapshots:transitivePeerDependencies:- supports-colordependencies:- '@typescript-eslint/scope-manager': 8.59.2- '@typescript-eslint/types': 8.59.2- '@typescript-eslint/typescript-estree': 8.59.2([email protected])- '@typescript-eslint/visitor-keys': 8.59.2+ '@typescript-eslint/scope-manager': 8.59.3+ '@typescript-eslint/types': 8.59.3+ '@typescript-eslint/typescript-estree': 8.59.3([email protected])+ '@typescript-eslint/visitor-keys': 8.59.3+ debug: 4.4.3+ eslint: 10.3.0([email protected])+ typescript: 6.0.3+ transitivePeerDependencies:+ - supports-color++ dependencies:+ '@typescript-eslint/scope-manager': 8.59.3+ '@typescript-eslint/types': 8.59.3+ '@typescript-eslint/typescript-estree': 8.59.3([email protected])+ '@typescript-eslint/visitor-keys': 8.59.3debug: 4.4.3eslint: 9.39.4([email protected])typescript: 6.0.3transitivePeerDependencies:- supports-color- '@typescript-eslint/[email protected]([email protected])':+ '@typescript-eslint/[email protected]([email protected])':dependencies:- '@typescript-eslint/tsconfig-utils': 8.59.2([email protected])- '@typescript-eslint/types': 8.59.2+ '@typescript-eslint/tsconfig-utils': 8.59.3([email protected])+ '@typescript-eslint/types': 8.59.3debug: 4.4.3typescript: 6.0.3transitivePeerDependencies:- supports-color- '@typescript-eslint/[email protected]':+ '@typescript-eslint/[email protected]':+ dependencies:+ '@typescript-eslint/types': 8.59.3+ '@typescript-eslint/visitor-keys': 8.59.3++ '@typescript-eslint/[email protected]([email protected])':dependencies:- '@typescript-eslint/types': 8.59.2- '@typescript-eslint/visitor-keys': 8.59.2+ typescript: 6.0.3- '@typescript-eslint/[email protected]([email protected])':dependencies:+ '@typescript-eslint/types': 8.59.3+ '@typescript-eslint/typescript-estree': 8.59.3([email protected])+ debug: 4.4.3+ eslint: 10.3.0([email protected])+ ts-api-utils: 2.5.0([email protected])typescript: 6.0.3+ transitivePeerDependencies:+ - supports-colordependencies:- '@typescript-eslint/types': 8.59.2- '@typescript-eslint/typescript-estree': 8.59.2([email protected])+ '@typescript-eslint/types': 8.59.3+ '@typescript-eslint/typescript-estree': 8.59.3([email protected])debug: 4.4.3eslint: 9.39.4([email protected])ts-api-utils: 2.5.0([email protected])@@ -9848,14 +9983,14 @@ snapshots:transitivePeerDependencies:- supports-color- '@typescript-eslint/[email protected]': {}+ '@typescript-eslint/[email protected]': {}- '@typescript-eslint/[email protected]([email protected])':+ '@typescript-eslint/[email protected]([email protected])':dependencies:- '@typescript-eslint/project-service': 8.59.2([email protected])- '@typescript-eslint/tsconfig-utils': 8.59.2([email protected])- '@typescript-eslint/types': 8.59.2- '@typescript-eslint/visitor-keys': 8.59.2+ '@typescript-eslint/project-service': 8.59.3([email protected])+ '@typescript-eslint/tsconfig-utils': 8.59.3([email protected])+ '@typescript-eslint/types': 8.59.3+ '@typescript-eslint/visitor-keys': 8.59.3debug: 4.4.3minimatch: 10.2.5semver: 7.8.0@@ -9865,20 +10000,31 @@ snapshots:transitivePeerDependencies:- supports-color+ dependencies:+ '@eslint-community/eslint-utils': 4.9.1([email protected]([email protected]))+ '@typescript-eslint/scope-manager': 8.59.3+ '@typescript-eslint/types': 8.59.3+ '@typescript-eslint/typescript-estree': 8.59.3([email protected])+ eslint: 10.3.0([email protected])+ typescript: 6.0.3+ transitivePeerDependencies:+ - supports-color+dependencies:'@eslint-community/eslint-utils': 4.9.1([email protected]([email protected]))- '@typescript-eslint/scope-manager': 8.59.2- '@typescript-eslint/types': 8.59.2- '@typescript-eslint/typescript-estree': 8.59.2([email protected])+ '@typescript-eslint/scope-manager': 8.59.3+ '@typescript-eslint/types': 8.59.3+ '@typescript-eslint/typescript-estree': 8.59.3([email protected])eslint: 9.39.4([email protected])typescript: 6.0.3transitivePeerDependencies:- supports-color- '@typescript-eslint/[email protected]':+ '@typescript-eslint/[email protected]':dependencies:- '@typescript-eslint/types': 8.59.2+ '@typescript-eslint/types': 8.59.3eslint-visitor-keys: 5.0.1'@ungap/[email protected]': {}@@ -11168,18 +11314,18 @@ snapshots:optionalDependencies:source-map: 0.6.1- [email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]):dependencies:'@next/eslint-plugin-next': 16.2.6eslint: 9.39.4([email protected])eslint-import-resolver-node: 0.3.10- eslint-import-resolver-typescript: 3.10.1([email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected])))([email protected]([email protected]))- eslint-plugin-import: 2.32.0(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected])))([email protected]([email protected])))([email protected]([email protected]))+ eslint-import-resolver-typescript: 3.10.1([email protected]([email protected]([email protected])))([email protected]([email protected]))+ eslint-plugin-import: 2.32.0([email protected]([email protected]([email protected]([email protected])))([email protected]([email protected])))([email protected]([email protected]))eslint-plugin-jsx-a11y: 6.10.2([email protected]([email protected]))eslint-plugin-react: 7.37.5([email protected]([email protected]))eslint-plugin-react-hooks: 7.1.1([email protected]([email protected]))globals: 16.4.0optionalDependencies:typescript: 6.0.3transitivePeerDependencies:@@ -11196,7 +11342,7 @@ snapshots:transitivePeerDependencies:- supports-color- [email protected]([email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected])))([email protected]([email protected])):+ [email protected]([email protected]([email protected]([email protected])))([email protected]([email protected])):dependencies:'@nolyfill/is-core-module': 1.0.39debug: 4.4.3@@ -11207,22 +11353,21 @@ snapshots:tinyglobby: 0.2.16unrs-resolver: 1.11.1optionalDependencies:- eslint-plugin-import: 2.32.0(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected])))([email protected]([email protected])))([email protected]([email protected]))+ eslint-plugin-import: 2.32.0([email protected]([email protected]([email protected]([email protected])))([email protected]([email protected])))([email protected]([email protected]))transitivePeerDependencies:- supports-color- [email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected])))([email protected]([email protected])))([email protected]([email protected])):+ [email protected]([email protected])([email protected]([email protected]([email protected]([email protected])))([email protected]([email protected])))([email protected]([email protected])):dependencies:debug: 3.2.7optionalDependencies:eslint: 9.39.4([email protected])eslint-import-resolver-node: 0.3.10- eslint-import-resolver-typescript: 3.10.1([email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected])))([email protected]([email protected]))+ eslint-import-resolver-typescript: 3.10.1([email protected]([email protected]([email protected])))([email protected]([email protected]))transitivePeerDependencies:- supports-color- [email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected])))([email protected]([email protected])))([email protected]([email protected])):+ [email protected]([email protected]([email protected]([email protected]([email protected])))([email protected]([email protected])))([email protected]([email protected])):dependencies:'@rtsao/scc': 1.1.0array-includes: 3.1.9@@ -11233,7 +11378,7 @@ snapshots:doctrine: 2.1.0eslint: 9.39.4([email protected])eslint-import-resolver-node: 0.3.10- eslint-module-utils: 2.12.1(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected])))([email protected]([email protected])))([email protected]([email protected]))+ eslint-module-utils: 2.12.1([email protected])([email protected]([email protected]([email protected]([email protected])))([email protected]([email protected])))([email protected]([email protected]))hasown: 2.0.3is-core-module: 2.16.2is-glob: 4.0.3@@ -11244,8 +11389,6 @@ snapshots:semver: 6.3.1string.prototype.trimend: 1.0.9tsconfig-paths: 3.15.0- optionalDependencies:transitivePeerDependencies:- eslint-import-resolver-typescript- eslint-import-resolver-webpack@@ -11314,12 +11457,56 @@ snapshots:esrecurse: 4.3.0estraverse: 5.3.0+ dependencies:+ '@types/esrecurse': 4.3.1+ '@types/estree': 1.0.8+ esrecurse: 4.3.0+ estraverse: 5.3.0++ dependencies:+ '@eslint-community/eslint-utils': 4.9.1([email protected]([email protected]))+ '@eslint-community/regexpp': 4.12.2+ '@eslint/config-array': 0.23.5+ '@eslint/config-helpers': 0.5.5+ '@eslint/core': 1.2.1+ '@eslint/plugin-kit': 0.7.1+ '@humanfs/node': 0.16.7+ '@humanwhocodes/module-importer': 1.0.1+ '@humanwhocodes/retry': 0.4.3+ '@types/estree': 1.0.8+ ajv: 6.14.0+ cross-spawn: 7.0.6+ debug: 4.4.3+ escape-string-regexp: 4.0.0+ eslint-scope: 9.1.2+ eslint-visitor-keys: 5.0.1+ espree: 11.2.0+ esquery: 1.7.0+ esutils: 2.0.3+ fast-deep-equal: 3.1.3+ file-entry-cache: 8.0.0+ find-up: 5.0.0+ glob-parent: 6.0.2+ ignore: 5.3.2+ imurmurhash: 0.1.4+ is-glob: 4.0.3+ json-stable-stringify-without-jsonify: 1.0.1+ minimatch: 10.2.5+ natural-compare: 1.4.0+ optionator: 0.9.4+ optionalDependencies:+ jiti: 2.7.0+ transitivePeerDependencies:+ - supports-color+dependencies:'@eslint-community/eslint-utils': 4.9.1([email protected]([email protected]))@@ -11367,6 +11554,12 @@ snapshots:acorn-jsx: 5.3.2([email protected])eslint-visitor-keys: 4.2.1+ dependencies:+ acorn: 8.16.0+ acorn-jsx: 5.3.2([email protected])+ eslint-visitor-keys: 5.0.1+@@ -14219,7 +14412,7 @@ snapshots:- [email protected]: {}+ [email protected]: {}@@ -14380,12 +14573,23 @@ snapshots:dependencies:is-typedarray: 1.0.0+ dependencies:+ '@typescript-eslint/eslint-plugin': 8.59.3(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])+ '@typescript-eslint/typescript-estree': 8.59.3([email protected])+ eslint: 10.3.0([email protected])+ typescript: 6.0.3+ transitivePeerDependencies:+ - supports-color+dependencies:- '@typescript-eslint/eslint-plugin': 8.59.2(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])- '@typescript-eslint/typescript-estree': 8.59.2([email protected])+ '@typescript-eslint/eslint-plugin': 8.59.3(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])+ '@typescript-eslint/typescript-estree': 8.59.3([email protected])eslint: 9.39.4([email protected])typescript: 6.0.3transitivePeerDependencies:diff --git a/src/app/eslint.config.mjs b/src/app/eslint.config.mjsnew file mode 100644index 000000000..8d67ca6ff--- /dev/null+++ b/src/app/eslint.config.mjs@@ -0,0 +1,16 @@+import { defineConfig, globalIgnores } from "eslint/config";+import tseslint from "typescript-eslint";++const eslintConfig = defineConfig([+ ...tseslint.configs.recommended,+ globalIgnores(["dist/**"]),+ {+ files: ["**/*.test.ts"],+ rules: {+ "@typescript-eslint/no-explicit-any": "off",+ "@typescript-eslint/no-unused-vars": "off",+ },+ },+]);++export default eslintConfig;diff --git a/src/app/package.json b/src/app/package.jsonindex 976826b91..978a2a4d5 100644--- a/src/app/package.json+++ b/src/app/package.json@@ -1,6 +1,6 @@{"name": "@alook/app",- "version": "0.0.1",+ "version": "0.0.60","description": "Run Alook locally — one command, no clone needed","license": "Apache-2.0","homepage": "https://github.com/alookai/alook#readme",@@ -30,18 +30,25 @@"access": "public"},"scripts": {- "build": "bun build src/index.ts --outdir dist --target node --format esm --external commander --external wrangler",- "prepack": "pnpm run build",+ "build": "bun build src/index.ts --outdir dist --target node --format esm --external commander --external wrangler && node scripts/bundle-cli.mjs",+ "prepack": "pnpm run build && node -e \"const{existsSync}=require('fs');if(!existsSync('bundled/web'))throw new Error('bundled/ missing — run pnpm bundle first')\"","bundle": "bun run scripts/bundle.ts",+ "lint": "eslint src/","test": "vitest run"},"dependencies": {+ "citty": "^0.2.2","commander": "^14.0.3",+ "playwright-core": "^1.59.1",+ "postal-mime": "^2.7.4","wrangler": "^4.90.0"},"devDependencies": {+ "@alook/cli": "workspace:*","@alook/shared": "workspace:*","@types/bun": "^1.3.13",- "typescript": "^6.0.3"+ "eslint": "^9.39.4",+ "typescript": "^6.0.3",+ "typescript-eslint": "^8.59.3"}}diff --git a/src/app/scripts/bundle-cli.mjs b/src/app/scripts/bundle-cli.mjsnew file mode 100644index 000000000..dd8b618d0--- /dev/null+++ b/src/app/scripts/bundle-cli.mjs@@ -0,0 +1,30 @@+#!/usr/bin/env node+/**+ * Copy pre-built @alook/cli dist files into app/dist/cli/.+ * Run as part of the app build step so the CLI is bundled+ * directly into @alook/app — no separate npm dependency needed.+ */+import { cpSync, existsSync, mkdirSync, readdirSync } from "node:fs";+import { join, dirname } from "node:path";+import { execSync } from "node:child_process";+import { fileURLToPath } from "node:url";++const __dirname = dirname(fileURLToPath(import.meta.url));+const appRoot = join(__dirname, "..");+const cliRoot = join(appRoot, "..", "cli");+const cliDist = join(cliRoot, "dist");+const targetDir = join(appRoot, "dist", "cli");++const REQUIRED_FILES = ["index.js", "session-runner.js", "meeting-runner.js"];++if (!REQUIRED_FILES.every((f) => existsSync(join(cliDist, f)))) {+ console.log("[bundle-cli] CLI dist not found, building...");+ execSync("pnpm run build", { cwd: cliRoot, stdio: "inherit" });+}++mkdirSync(targetDir, { recursive: true });+for (const file of REQUIRED_FILES) {+ cpSync(join(cliDist, file), join(targetDir, file));+}++console.log(`[bundle-cli] Copied ${REQUIRED_FILES.join(", ")} → dist/cli/`);diff --git a/src/app/src/commands/cli.ts b/src/app/src/commands/cli.tsnew file mode 100644index 000000000..74b5aa047--- /dev/null+++ b/src/app/src/commands/cli.ts@@ -0,0 +1,73 @@+import { Command } from "commander";+import { spawnSync } from "child_process";+import { dirname, join } from "path";+import { fileURLToPath } from "url";+import { buildCliEnv } from "../lib/cli-env.js";++const __dirname = dirname(fileURLToPath(import.meta.url));++function findCliEntry(): string {+ return join(__dirname, "cli", "index.js");+}++function runCli(args: string[]): void {+ const result = spawnSync("node", [findCliEntry(), ...args], {+ stdio: "inherit",+ env: buildCliEnv(),+ });+ process.exit(result.status ?? 1);+}++export function registerCommand(): Command {+ return new Command("register")+ .description("Register CLI with local Alook server")+ .allowUnknownOption()+ .passThroughOptions()+ .argument("[args...]")+ .action((args) => {+ runCli(["register", ...args]);+ });+}++export function daemonCommand(): Command {+ const daemon = new Command("daemon")+ .description("Manage the local Alook daemon")+ .enablePositionalOptions();++ daemon+ .command("start")+ .description("Start the daemon")+ .allowUnknownOption()+ .passThroughOptions()+ .argument("[args...]")+ .action((args) => {+ runCli(["daemon", "start", ...args]);+ });++ daemon+ .command("stop")+ .description("Stop the daemon")+ .action(() => {+ runCli(["daemon", "stop"]);+ });++ daemon+ .command("status")+ .description("Check daemon status")+ .action(() => {+ runCli(["daemon", "status"]);+ });++ return daemon;+}++export function cliPassthroughCommand(): Command {+ return new Command("cli")+ .description("Run any @alook/cli command against the local server")+ .allowUnknownOption()+ .passThroughOptions()+ .argument("[args...]")+ .action((args) => {+ runCli(args);+ });+}diff --git a/src/app/src/commands/onboard.ts b/src/app/src/commands/onboard.tsindex ccf144d4d..8f18a3463 100644--- a/src/app/src/commands/onboard.ts+++ b/src/app/src/commands/onboard.ts@@ -1,5 +1,8 @@import { Command } from "commander";import { execSync, spawnSync, spawn as spawnAsync } from "child_process";+import { join, dirname } from "path";+import { fileURLToPath } from "url";+import { createInterface } from "readline";import { checkNodeVersion, checkAIRuntime, checkPorts } from "../lib/checks.js";import { isInstalled, installBundled } from "../lib/install.js";import { ensureSecrets } from "../lib/secrets.js";@@ -10,11 +13,13 @@ import {registerUser,createWorkspace,createMachineToken,- activateToken,waitForServer,} from "../lib/register.js";import { DEFAULT_PORTS, WEB_URL, SELF_HOSTED_DIR } from "../lib/constants.js";import { patchWranglerConfigs } from "../lib/wrangler-config.js";+import { buildCliEnv } from "../lib/cli-env.js";++const __dirname = dirname(fileURLToPath(import.meta.url));export function onboardCommand(): Command {return new Command("onboard")@@ -48,6 +53,12 @@ export function onboardCommand(): Command {}console.log(` Found: ${runtimes.map((r) => r.type).join(", ")}\n`);+ // 4. Collect user input before heavy install/migrate work+ let email: string | undefined;+ if (!opts.skipRegister) {+ email = await collectEmail();+ }+const devMode = !!process.env.ALOOK_PROJECT_ROOT;if (devMode) {@@ -57,7 +68,7 @@ export function onboardCommand(): Command {try {execSync("pnpm predev", { cwd: root, stdio: "inherit" });} catch {}- execSync("pnpm db:migrate", { cwd: root, stdio: "inherit" });+ execSync("pnpm db:migrate", { cwd: root, stdio: ["pipe", "inherit", "inherit"] });} else {// Production: install bundled assetsif (!isInstalled()) {@@ -72,12 +83,6 @@ export function onboardCommand(): Command {runMigrations();}- // 7. Collect user input before starting services- let email: string | undefined;- if (!opts.skipRegister) {- email = await collectEmail();- }-// 8. Start servicesif (isRunning()) {console.log("\nServices already running.");@@ -96,34 +101,24 @@ export function onboardCommand(): Command {const { sessionCookie } = await registerUser(baseURL, email);const workspace = await createWorkspace(baseURL, sessionCookie);const { token } = await createMachineToken(baseURL, sessionCookie, workspace.id);- const { runtimeIds } = await activateToken(baseURL, token, runtimes);-- console.log(` ✓ Daemon registered with ${runtimes.map((r) => r.type).join(", ")} runtime`);- console.log(` ✓ Machine token activated\n`);-- // Start the daemon pointing to local server- // Pass ALOOK_PROJECT_ROOT so CLI stores config in the same .alook/ dir- const cliEnv: Record<string, string> = {- ...process.env as Record<string, string>,- ALOOK_SERVER_URL: baseURL,- };- if (process.env.ALOOK_PROJECT_ROOT) {- cliEnv.ALOOK_PROJECT_ROOT = process.env.ALOOK_PROJECT_ROOT;- }++ // Let CLI register handle token activation + config save+ const cliEntry = join(__dirname, "cli", "index.js");+ const cliEnv = buildCliEnv(ports.web);console.log("Starting daemon...");try {- spawnSync("npx", ["@alook/cli", "register", "--token", token], {+ spawnSync("node", [cliEntry, "register", "--token", token], {stdio: "inherit",env: cliEnv,});- spawnSync("npx", ["@alook/cli", "daemon", "start"], {+ spawnSync("node", [cliEntry, "daemon", "start"], {stdio: "inherit",env: cliEnv,});} catch {console.warn(" Warning: daemon auto-start failed. Start manually:");- console.warn(` ALOOK_SERVER_URL=${baseURL} npx @alook/cli register --token ${token}`);- console.warn(` ALOOK_SERVER_URL=${baseURL} npx @alook/cli daemon start`);+ console.warn(` npx @alook/app cli register --token ${token}`);+ console.warn(` npx @alook/app cli daemon start`);}}@@ -134,17 +129,41 @@ export function onboardCommand(): Command {console.log("─".repeat(50));console.log(`\n🎉 Alook is running!`);console.log(` Dashboard: ${baseURL}`);+ if (email) {+ console.log(` Login: ${email}`);+ }console.log(`\n Stop: npx @alook/app stop`);console.log(` Start: npx @alook/app start`);console.log(` Update: npx @alook/app update\n`);- // 12. Open browser+ // 12. Copy email & open browser on Enter+ const signInURL = `${baseURL}/sign-in`;+ if (email) {+ try {+ execSync(`printf '%s' ${JSON.stringify(email)} | pbcopy`, { stdio: "ignore" });+ console.log(` Email copied to clipboard.\n`);+ } catch {+ try {+ execSync(`printf '%s' ${JSON.stringify(email)} | xclip -selection clipboard`, { stdio: "ignore" });+ console.log(` Email copied to clipboard.\n`);+ } catch {}+ }+ }++ const rl = createInterface({ input: process.stdin, output: process.stdout });+ await new Promise<void>((resolve) => {+ rl.question("Press Enter to open the dashboard...", () => {+ rl.close();+ resolve();+ });+ });+const openCmd = process.platform === "darwin" ? "open" :process.platform === "win32" ? "cmd" : "xdg-open";try {const openArgs = process.platform === "win32"- ? ["/c", "start", "", baseURL]- : [baseURL];+ ? ["/c", "start", "", signInURL]+ : [signInURL];spawnAsync(openCmd, openArgs, { stdio: "ignore", detached: true }).unref();} catch {}});diff --git a/src/app/src/index.ts b/src/app/src/index.tsindex b445a4987..57cf1ff3c 100644--- a/src/app/src/index.ts+++ b/src/app/src/index.ts@@ -7,6 +7,7 @@ import { onboardCommand } from "./commands/onboard.js";import { startCommand } from "./commands/start.js";import { stopCommand } from "./commands/stop.js";import { updateCommand } from "./commands/update.js";+import { registerCommand, daemonCommand, cliPassthroughCommand } from "./commands/cli.js";function getVersion(): string {const __dirname = dirname(fileURLToPath(import.meta.url));@@ -24,11 +25,15 @@ const program = new Command();program.name("alook-app").description("Run Alook locally — one command, no clone needed")- .version(getVersion());+ .version(getVersion())+ .enablePositionalOptions();program.addCommand(onboardCommand());program.addCommand(startCommand());program.addCommand(stopCommand());program.addCommand(updateCommand());+program.addCommand(registerCommand());+program.addCommand(daemonCommand());+program.addCommand(cliPassthroughCommand());program.parse();diff --git a/src/app/src/lib/cli-env.ts b/src/app/src/lib/cli-env.tsnew file mode 100644index 000000000..27a0f0ca4--- /dev/null+++ b/src/app/src/lib/cli-env.ts@@ -0,0 +1,21 @@+import { DEFAULT_PORTS, WEB_URL, SELF_HOSTED_DIR } from "./constants.js";+import { readPids } from "./pid.js";++/**+ * Build env vars for spawning @alook/cli subprocesses.+ *+ * Three scenarios — all resolve ALOOK_PROJECT_ROOT via SELF_HOSTED_DIR:+ * 1. Production install: ~/.alook/self-hosted+ * 2. Dev mode (monorepo): <ALOOK_PROJECT_ROOT>/.alook/self-hosted+ * 3. App mode (npx): ~/.alook/self-hosted (same as 1)+ */+export function buildCliEnv(webPort?: number): Record<string, string> {+ const port = webPort ?? (readPids().ports?.web ?? DEFAULT_PORTS.web);+ return {+ ...(process.env as Record<string, string>),+ ALOOK_SERVER_URL: WEB_URL(port),+ ALOOK_PROJECT_ROOT: SELF_HOSTED_DIR,+ ALOOK_CMD_PREFIX: "npx @alook/app cli",+ ALOOK_HEALTH_PORT: "19515",+ };+}diff --git a/src/app/src/lib/constants.ts b/src/app/src/lib/constants.tsindex 91b2013d0..97e0f6ef2 100644--- a/src/app/src/lib/constants.ts+++ b/src/app/src/lib/constants.ts@@ -12,9 +12,9 @@ export const SELF_HOSTED_DIR = resolveBaseDir();export const PID_FILE = join(SELF_HOSTED_DIR, ".pids.json");export const DEFAULT_PORTS = {- web: 3000,- emailWorker: 8787,- wsDo: 8789,+ web: 15210,+ emailWorker: 15211,+ wsDo: 15212,} as const;export const WEB_URL = (port: number) => `http://localhost:${port}`;diff --git a/src/app/src/lib/migrate.ts b/src/app/src/lib/migrate.tsindex 9f4e6cd57..74a674c45 100644--- a/src/app/src/lib/migrate.ts+++ b/src/app/src/lib/migrate.ts@@ -6,12 +6,23 @@ export function runMigrations(): void {const webDir = join(SELF_HOSTED_DIR, "web");console.log("Running database migrations...");try {- execSync("npx wrangler d1 migrations apply alook-app --local", {+ const output = execSync("npx wrangler d1 migrations apply alook-app --local", {cwd: webDir,- stdio: "inherit",+ stdio: ["pipe", "pipe", "pipe"],});- console.log("Migrations complete");+ const text = output.toString();+ const applied = text.match(/(\d+) commands? executed successfully/g);+ if (applied) {+ const total = applied.reduce((sum, m) => sum + Number(m.match(/\d+/)?.[0] ?? 0), 0);+ console.log(` ✓ ${total} migration commands applied`);+ } else if (text.includes("No migrations to apply")) {+ console.log(" ✓ Already up to date");+ } else {+ console.log(" ✓ Migrations complete");+ }} catch (err) {+ const stderr = (err as { stderr?: Buffer }).stderr?.toString() ?? "";+ if (stderr) console.error(stderr);console.error("Error: failed to run migrations");process.exit(1);}diff --git a/src/app/src/lib/pid.ts b/src/app/src/lib/pid.tsindex 5bb191fed..ec501769f 100644--- a/src/app/src/lib/pid.ts+++ b/src/app/src/lib/pid.ts@@ -6,6 +6,11 @@ interface PidRecord {web?: number;emailWorker?: number;wsDo?: number;+ ports?: {+ web?: number;+ emailWorker?: number;+ wsDo?: number;+ };}export function readPids(): PidRecord {diff --git a/src/app/src/lib/register.ts b/src/app/src/lib/register.tsindex dfed90f73..42f5e1474 100644--- a/src/app/src/lib/register.ts+++ b/src/app/src/lib/register.ts@@ -53,7 +53,7 @@ export async function registerUser(baseURL: string, email: string): Promise<Signlet res = await fetch(`${baseURL}/api/auth/sign-up/email`, {method: "POST",- headers: { "Content-Type": "application/json" },+ headers: { "Content-Type": "application/json", Origin: baseURL },body: JSON.stringify({ email, password, name }),redirect: "manual",});@@ -63,7 +63,7 @@ export async function registerUser(baseURL: string, email: string): Promise<Signif (text.includes("already exists") || text.includes("already registered") || text.includes("User already")) {res = await fetch(`${baseURL}/api/auth/sign-in/email`, {method: "POST",- headers: { "Content-Type": "application/json" },+ headers: { "Content-Type": "application/json", Origin: baseURL },body: JSON.stringify({ email, password }),redirect: "manual",});@@ -102,6 +102,7 @@ export async function createWorkspace(baseURL: string, cookie: string): Promise<method: "POST",headers: {"Content-Type": "application/json",+ Origin: baseURL,Cookie: cookie,},body: JSON.stringify({ name: "Personal", slug: "personal" }),@@ -109,7 +110,7 @@ export async function createWorkspace(baseURL: string, cookie: string): Promise<if (!res.ok) {const listRes = await fetch(`${baseURL}/api/workspaces`, {- headers: { Cookie: cookie },+ headers: { Cookie: cookie, Origin: baseURL },});if (listRes.ok) {const workspaces = (await listRes.json()) as WorkspaceResult[];@@ -133,6 +134,7 @@ export async function createMachineToken(method: "POST",headers: {"Content-Type": "application/json",+ Origin: baseURL,Cookie: cookie,},body: JSON.stringify({ name: "local-onboard" }),@@ -156,7 +158,7 @@ export async function activateToken(const res = await fetch(`${baseURL}/api/machine-tokens/activate`, {method: "POST",- headers: { "Content-Type": "application/json" },+ headers: { "Content-Type": "application/json", Origin: baseURL },body: JSON.stringify({token,hostname: hostname(),diff --git a/src/app/src/lib/services.ts b/src/app/src/lib/services.tsindex 7d2c032c5..57a0d629a 100644--- a/src/app/src/lib/services.ts+++ b/src/app/src/lib/services.ts@@ -99,9 +99,10 @@ export function startServices(ports: ServicePorts, opts: StartOptions = {}): voiemailChild = spawnService("email-worker", "npx", ["wrangler", "dev", "--local", "--port", String(ports.emailWorker), ...persistTo], emailDir, foreground);wsChild = spawnService("ws-do", "npx", ["wrangler", "dev", "--local", "--port", String(ports.wsDo), ...persistTo], wsDir, foreground);} else {- webChild = spawnService("web", "npx", ["wrangler", "dev", "--local", "--port", String(ports.web)], join(SELF_HOSTED_DIR, "web"), foreground);- emailChild = spawnService("email-worker", "npx", ["wrangler", "dev", "--local", "--port", String(ports.emailWorker)], join(SELF_HOSTED_DIR, "email-worker"), foreground);- wsChild = spawnService("ws-do", "npx", ["wrangler", "dev", "--local", "--port", String(ports.wsDo)], join(SELF_HOSTED_DIR, "ws-do"), foreground);+ const persistTo = ["--persist-to", join(SELF_HOSTED_DIR, "web", ".wrangler", "state")];+ webChild = spawnService("web", "npx", ["wrangler", "dev", "--local", "--port", String(ports.web), ...persistTo], join(SELF_HOSTED_DIR, "web"), foreground);+ emailChild = spawnService("email-worker", "npx", ["wrangler", "dev", "--local", "--port", String(ports.emailWorker), ...persistTo], join(SELF_HOSTED_DIR, "email-worker"), foreground);+ wsChild = spawnService("ws-do", "npx", ["wrangler", "dev", "--local", "--port", String(ports.wsDo), ...persistTo], join(SELF_HOSTED_DIR, "ws-do"), foreground);}if (!webChild.pid || !emailChild.pid || !wsChild.pid) {@@ -116,6 +117,11 @@ export function startServices(ports: ServicePorts, opts: StartOptions = {}): voiweb: webChild.pid,emailWorker: emailChild.pid,wsDo: wsChild.pid,+ ports: {+ web: ports.web,+ emailWorker: ports.emailWorker,+ wsDo: ports.wsDo,+ },});console.log(` Web: http://localhost:${ports.web} (pid=${webChild.pid})`);diff --git a/src/app/src/lib/wrangler-config.ts b/src/app/src/lib/wrangler-config.tsindex 011843013..aa67106f6 100644--- a/src/app/src/lib/wrangler-config.ts+++ b/src/app/src/lib/wrangler-config.ts@@ -35,6 +35,7 @@ export function patchWranglerConfigs(ports: { web: number; emailWorker: number;webContent = setVar(webContent, "DEV_WS_DO_URL", `http://localhost:${ports.wsDo}`);webContent = setVar(webContent, "DEV_EMAIL_WORKER_URL", `http://localhost:${ports.emailWorker}`);+ webContent = setVar(webContent, "NODE_ENV", "development");writeFileSync(webToml, webContent);setDevPort(join(SELF_HOSTED_DIR, "email-worker", "wrangler.toml"), ports.emailWorker);diff --git a/src/cli/daemon/config.test.ts b/src/cli/daemon/config.test.tsindex 38c97c48a..1cf901950 100644--- a/src/cli/daemon/config.test.ts+++ b/src/cli/daemon/config.test.ts@@ -120,10 +120,10 @@ describe("daemonLogFilePath", () => {expect(daemonLogFilePath(d).endsWith("2026-01-05.log")).toBe(true);});- it("honours ALOOK_PROJECT_ROOT in dev mode", () => {+ it("honours ALOOK_PROJECT_ROOT", () => {process.env.ALOOK_SERVER_URL = "http://localhost:3000";- process.env.ALOOK_PROJECT_ROOT = "/tmp/proj";- expect(daemonLogDir()).toBe(join("/tmp/proj", ".alook", "daemon", "logs"));+ process.env.ALOOK_PROJECT_ROOT = "/tmp/proj/.alook";+ expect(daemonLogDir()).toBe(join("/tmp/proj/.alook", "daemon", "logs"));});});@@ -140,18 +140,18 @@ describe("workspacesRoot profile handling", () => {);});- it("defaults to <project-root>/.alook/workspaces in dev mode", () => {+ it("defaults to <ALOOK_PROJECT_ROOT>/workspaces when set", () => {process.env.ALOOK_SERVER_URL = "http://localhost:3000";- process.env.ALOOK_PROJECT_ROOT = "/tmp/my-project";+ process.env.ALOOK_PROJECT_ROOT = "/tmp/my-project/.alook";const cfg = loadDaemonConfig();expect(cfg.workspacesRoot).toBe(- join("/tmp/my-project", ".alook", "workspaces"),+ join("/tmp/my-project/.alook", "workspaces"),);});- it("ALOOK_WORKSPACES_ROOT overrides dev mode default", () => {+ it("ALOOK_WORKSPACES_ROOT overrides default", () => {process.env.ALOOK_SERVER_URL = "http://localhost:3000";- process.env.ALOOK_PROJECT_ROOT = "/tmp/my-project";+ process.env.ALOOK_PROJECT_ROOT = "/tmp/my-project/.alook";process.env.ALOOK_WORKSPACES_ROOT = "/custom/path";const cfg = loadDaemonConfig();expect(cfg.workspacesRoot).toBe("/custom/path");@@ -165,11 +165,11 @@ describe("sessionRunnerLogDir", () => {);});- it("honours ALOOK_PROJECT_ROOT in dev mode", () => {+ it("honours ALOOK_PROJECT_ROOT", () => {process.env.ALOOK_SERVER_URL = "http://localhost:3000";- process.env.ALOOK_PROJECT_ROOT = "/tmp/proj";+ process.env.ALOOK_PROJECT_ROOT = "/tmp/proj/.alook";expect(sessionRunnerLogDir()).toBe(- join("/tmp/proj", ".alook", "daemon", "session-runners"),+ join("/tmp/proj/.alook", "daemon", "session-runners"),);});});diff --git a/src/cli/daemon/update-handler.ts b/src/cli/daemon/update-handler.tsindex 455cb782f..e6bbcea6d 100644--- a/src/cli/daemon/update-handler.ts+++ b/src/cli/daemon/update-handler.ts@@ -50,6 +50,11 @@ export async function handleCliUpdate(if (updating) return;if (retryCount >= MAX_RETRIES) return;+ if (process.env.ALOOK_CMD_PREFIX) {+ log.info(`Skipping auto-update in app mode — user should run: npx @alook/app@latest update`);+ return;+ }+const marker = readUpdateMarker(profile);if (marker === version) {log.info(`Skipping update to v${version} — already attempted (marker exists)`);diff --git a/src/cli/lib/config.test.ts b/src/cli/lib/config.test.tsindex 0e5b03611..c81113a8b 100644--- a/src/cli/lib/config.test.ts+++ b/src/cli/lib/config.test.ts@@ -31,32 +31,31 @@ afterEach(() => {delete process.env.ALOOK_PROJECT_ROOT;});-describe("configDir", () => {- it("returns ~/.alook in production", () => {+describe("configDir — three ALOOK_PROJECT_ROOT scenarios", () => {+ it("production: returns ~/.alook (ALOOK_PROJECT_ROOT unset)", () => {+ delete process.env.ALOOK_PROJECT_ROOT;expect(configDir()).toBe(join(homedir(), ".alook"));});- it("returns <project-root>/.alook in dev mode", () => {- process.env.ALOOK_SERVER_URL = "http://localhost:3000";- process.env.ALOOK_PROJECT_ROOT = "/tmp/my-project";- expect(configDir()).toBe(join("/tmp/my-project", ".alook"));+ it("dev mode: returns ALOOK_PROJECT_ROOT directly", () => {+ process.env.ALOOK_PROJECT_ROOT = "/tmp/my-project/.alook";+ expect(configDir()).toBe("/tmp/my-project/.alook");});- it("falls back to ~/.alook in dev mode without ALOOK_PROJECT_ROOT", () => {- process.env.ALOOK_SERVER_URL = "http://localhost:3000";- expect(configDir()).toBe(join(homedir(), ".alook"));+ it("app mode: returns ALOOK_PROJECT_ROOT when set to self-hosted dir", () => {+ process.env.ALOOK_PROJECT_ROOT = join(homedir(), ".alook", "self-hosted");+ expect(configDir()).toBe(join(homedir(), ".alook", "self-hosted"));});});describe("configPath", () => {- it("returns ~/.alook/config.json in production", () => {+ it("returns ~/.alook/config.json by default", () => {expect(configPath()).toBe(join(homedir(), ".alook", "config.json"));});- it("returns <project-root>/.alook/config.json in dev mode", () => {- process.env.ALOOK_SERVER_URL = "http://localhost:3000";- process.env.ALOOK_PROJECT_ROOT = "/tmp/my-project";- expect(configPath()).toBe(join("/tmp/my-project", ".alook", "config.json"));+ it("returns <ALOOK_PROJECT_ROOT>/config.json when set", () => {+ process.env.ALOOK_PROJECT_ROOT = "/tmp/my-project/.alook";+ expect(configPath()).toBe(join("/tmp/my-project/.alook", "config.json"));});});@@ -139,19 +138,18 @@ describe("saveCLIConfig", () => {);});- it("writes to <project-root>/.alook in dev mode", () => {- process.env.ALOOK_SERVER_URL = "http://localhost:3000";- process.env.ALOOK_PROJECT_ROOT = "/tmp/my-project";+ it("writes to ALOOK_PROJECT_ROOT when set", () => {+ process.env.ALOOK_PROJECT_ROOT = "/tmp/my-project/.alook";const cfg = { server_url: "http://localhost:3000", watched_workspaces: [] };saveCLIConfig(cfg);expect(mockedMkdirSync).toHaveBeenCalledWith(- join("/tmp/my-project", ".alook"),+ "/tmp/my-project/.alook",{ recursive: true, mode: 0o700 },);expect(mockedWriteFileSync).toHaveBeenCalledWith(- join("/tmp/my-project", ".alook", "config.json"),+ join("/tmp/my-project/.alook", "config.json"),JSON.stringify(cfg, null, 2),{ mode: 0o600 },);diff --git a/src/cli/lib/config.ts b/src/cli/lib/config.tsindex d54d04efe..4fd069d53 100644--- a/src/cli/lib/config.ts+++ b/src/cli/lib/config.ts@@ -1,7 +1,6 @@import { readFileSync, writeFileSync, mkdirSync } from "fs";import { join } from "path";import { homedir } from "os";-import { isDev } from "./env.js";interface WatchedWorkspace {id: string;@@ -25,10 +24,7 @@ interface CLIConfig {export type { CLIConfig, ProfileConfig, WatchedWorkspace };export function configDir(): string {- if (isDev() && process.env.ALOOK_PROJECT_ROOT) {- return join(process.env.ALOOK_PROJECT_ROOT, ".alook");- }- return join(homedir(), ".alook");+ return process.env.ALOOK_PROJECT_ROOT || join(homedir(), ".alook");}export function configPath(): string {diff --git a/src/cli/lib/env.test.ts b/src/cli/lib/env.test.tsindex 3a847b3d1..14df7747d 100644--- a/src/cli/lib/env.test.ts+++ b/src/cli/lib/env.test.ts@@ -3,6 +3,7 @@ import { isDev, cmdPrefix } from "./env.js";afterEach(() => {delete process.env.ALOOK_SERVER_URL;+ delete process.env.ALOOK_CMD_PREFIX;});describe("isDev", () => {@@ -14,6 +15,12 @@ describe("isDev", () => {process.env.ALOOK_SERVER_URL = "http://localhost:3000";expect(isDev()).toBe(true);});++ it("returns false when ALOOK_CMD_PREFIX is set (app mode)", () => {+ process.env.ALOOK_SERVER_URL = "http://localhost:3000";+ process.env.ALOOK_CMD_PREFIX = "npx @alook/app cli";+ expect(isDev()).toBe(false);+ });});describe("cmdPrefix", () => {@@ -25,4 +32,10 @@ describe("cmdPrefix", () => {process.env.ALOOK_SERVER_URL = "http://localhost:3000";expect(cmdPrefix()).toBe("pnpm dev:cli");});++ it("returns ALOOK_CMD_PREFIX when set", () => {+ process.env.ALOOK_SERVER_URL = "http://localhost:3000";+ process.env.ALOOK_CMD_PREFIX = "npx @alook/app cli";+ expect(cmdPrefix()).toBe("npx @alook/app cli");+ });});diff --git a/src/cli/lib/env.ts b/src/cli/lib/env.tsindex 84a02ad70..c543bdaa4 100644--- a/src/cli/lib/env.ts+++ b/src/cli/lib/env.ts@@ -1,7 +1,8 @@export function isDev(): boolean {- return !!process.env.ALOOK_SERVER_URL;+ return !!process.env.ALOOK_SERVER_URL && !process.env.ALOOK_CMD_PREFIX;}export function cmdPrefix(): string {+ if (process.env.ALOOK_CMD_PREFIX) return process.env.ALOOK_CMD_PREFIX;return isDev() ? "pnpm dev:cli" : "npx @alook/cli";}diff --git a/src/cli/lib/shell-env.ts b/src/cli/lib/shell-env.tsindex db804050d..14f430a9e 100644--- a/src/cli/lib/shell-env.ts+++ b/src/cli/lib/shell-env.ts@@ -1,6 +1,8 @@import { execSync } from "child_process";import { isWindows } from "./platform.js";+const PASSTHROUGH_VARS = ["ALOOK_PROJECT_ROOT", "ALOOK_SERVER_URL", "ALOOK_CMD_PREFIX", "ALOOK_HEALTH_PORT"];+export function resolveLoginShellEnv(): NodeJS.ProcessEnv {if (isWindows) {return { ...process.env };@@ -20,7 +22,12 @@ export function resolveLoginShellEnv(): NodeJS.ProcessEnv {env[line.slice(0, idx)] = line.slice(idx + 1);}}- if (env.PATH) return env;+ if (env.PATH) {+ for (const key of PASSTHROUGH_VARS) {+ if (process.env[key]) env[key] = process.env[key];+ }+ return env;+ }} catch {// fall through}diff --git a/src/cli/package.json b/src/cli/package.jsonindex 9e4f53e65..3baed7c7e 100644--- a/src/cli/package.json+++ b/src/cli/package.json@@ -41,6 +41,7 @@"build": "bun build src/index.ts --outdir dist --target node --format esm --external citty --external commander --external postal-mime --external playwright-core && bun build daemon/session-runner.ts --outdir dist --target node --format esm --external citty --external commander --external postal-mime && bun build daemon/meeting-runner.ts --outdir dist --target node --format esm --external playwright-core && node scripts/prepare-dist.mjs","prepack": "pnpm run build","test": "vitest run",+ "lint": "eslint src/","typecheck": "tsc --noEmit -p tsconfig.build.json"},"dependencies": {@@ -52,7 +53,9 @@"devDependencies": {"@alook/shared": "workspace:*","@types/bun": "^1.3.13",+ "eslint": "^10.3.0","typescript": "^6.0.3",+ "typescript-eslint": "^8.59.3","vitest": "^4.1.5"}}diff --git a/src/web/custom-worker.ts b/src/web/custom-worker.tsindex 772dcf8b8..8adb60223 100644--- a/src/web/custom-worker.ts+++ b/src/web/custom-worker.ts@@ -1,9 +1,9 @@// The import below is generated by `opennextjs-cloudflare build` and doesn't// exist at typecheck time. The build step creates it before wrangler bundles.-// @ts-expect-error — generated at build time+// @ts-ignore — generated at build time, may not exist yetimport openNextHandler from "./.open-next/worker.js"-// @ts-expect-error — generated at build time+// @ts-ignore — generated at build time, may not exist yetexport { DOQueueHandler } from "./.open-next/worker.js"const handler: ExportedHandler<CloudflareEnv> = {diff --git a/src/web/src/app/(app)/w/[slug]/runtimes/page.tsx b/src/web/src/app/(app)/w/[slug]/runtimes/page.tsxindex a667879eb..4426d6fc6 100644--- a/src/web/src/app/(app)/w/[slug]/runtimes/page.tsx+++ b/src/web/src/app/(app)/w/[slug]/runtimes/page.tsx@@ -26,7 +26,7 @@ import { Monitor, Plus } from "lucide-react";import type { AgentRuntime as Runtime } from "@alook/shared";import { semverGte } from "@alook/shared";-import { CLI_CMD } from "@/lib/utils";+import { cliCmd } from "@/lib/utils";import { ProviderLogo } from "@/components/provider-logo";import { triggerRuntimeUpdate, triggerRuntimeRescan, fetchLatestCliVersion } from "@/lib/api";import { Loader2, RefreshCw } from "lucide-react";@@ -436,13 +436,13 @@ export default function RuntimesPage() {<divclassName="relative overflow-hidden rounded-md bg-muted px-2.5 py-1.5 font-mono text-[11px] text-muted-foreground cursor-pointer hover:bg-muted/80 transition-colors"onClick={() => {- navigator.clipboard.writeText(`${CLI_CMD} daemon start`);+ navigator.clipboard.writeText(`${cliCmd()} daemon start`);toast.success("Copied to clipboard");}}title="Click to copy"><span className="absolute inset-0 -translate-x-full animate-[shimmer_2.5s_infinite] bg-linear-to-r from-transparent via-(--shimmer-peak) to-transparent" />- <span className="relative">{CLI_CMD} daemon start</span>+ <span className="relative">{cliCmd()} daemon start</span></div></div>)}diff --git a/src/web/src/app/(auth)/sign-in/page.tsx b/src/web/src/app/(auth)/sign-in/page.tsxindex 1890dff85..6e1789b75 100644--- a/src/web/src/app/(auth)/sign-in/page.tsx+++ b/src/web/src/app/(auth)/sign-in/page.tsx@@ -22,8 +22,9 @@ import {import { SiGithub, SiGoogle } from "@icons-pack/react-simple-icons"import { GradientBackground } from "@/components/gradient-background"import { TypewriterVisual, EMAILS_PLAYFUL } from "@/components/typewriter-visual"+import { isLocalMode } from "@/lib/utils"-const isProd = process.env.NODE_ENV === "production"+const isProd = !isLocalMode()import { DEV_PASSWORD } from "@alook/shared"const DEFAULT_POST_LOGIN = "/workspaces?auto"diff --git a/src/web/src/app/api/cli/latest-version/route.test.ts b/src/web/src/app/api/cli/latest-version/route.test.tsindex 4129fc84f..4491aa0a5 100644--- a/src/web/src/app/api/cli/latest-version/route.test.ts+++ b/src/web/src/app/api/cli/latest-version/route.test.ts@@ -8,7 +8,7 @@ import { GET } from "./route";describe("GET /api/cli/latest-version", () => {beforeEach(() => vi.clearAllMocks());- it("returns version from npm registry", async () => {+ it("returns version and package from npm registry", async () => {mockFetch.mockResolvedValue({ok: true,json: async () => ({ version: "2.0.0" }),@@ -19,6 +19,7 @@ describe("GET /api/cli/latest-version", () => {expect(res.status).toBe(200);expect(body.version).toBe("2.0.0");+ expect(body.package).toBe("@alook/cli");});it("returns 502 when npm registry returns non-ok", async () => {@@ -28,7 +29,7 @@ describe("GET /api/cli/latest-version", () => {const body = await res.json();expect(res.status).toBe(502);- expect(body.error).toContain("npm registry");+ expect(body.error).toContain("failed to fetch");});it("returns 502 when fetch throws", async () => {@@ -38,7 +39,7 @@ describe("GET /api/cli/latest-version", () => {const body = await res.json();expect(res.status).toBe(502);- expect(body.error).toContain("npm registry");+ expect(body.error).toContain("failed to fetch");});it("returns 502 when response has no version field", async () => {diff --git a/src/web/src/app/api/cli/latest-version/route.ts b/src/web/src/app/api/cli/latest-version/route.tsindex ef2bc8ea6..a3f7b47e8 100644--- a/src/web/src/app/api/cli/latest-version/route.ts+++ b/src/web/src/app/api/cli/latest-version/route.ts@@ -1,17 +1,10 @@import { writeJSON, writeError } from "@/lib/middleware/helpers";+import { fetchLatestCliVersion } from "@/lib/npm";export async function GET() {- try {- const res = await fetch("https://registry.npmjs.org/@alook/cli/latest");- if (!res.ok) {- return writeError("npm registry returned " + res.status, 502);- }- const data = (await res.json()) as { version?: string };- if (!data.version) {- return writeError("npm registry response missing version", 502);- }- return writeJSON({ version: data.version });- } catch {- return writeError("failed to reach npm registry", 502);+ const result = await fetchLatestCliVersion();+ if (!result) {+ return writeError("failed to fetch latest version from npm", 502);}+ return writeJSON({ version: result.version, package: result.package });}diff --git a/src/web/src/app/api/config/min-version/route.ts b/src/web/src/app/api/config/min-version/route.tsindex f1c1fef0b..99b453e63 100644--- a/src/web/src/app/api/config/min-version/route.ts+++ b/src/web/src/app/api/config/min-version/route.ts@@ -9,8 +9,8 @@ export const GET = withAuth(async () => {const raw = (env as Env).MIN_CLI_VERSION;if (!raw) return writeJSON({ min_cli_version: null });- const latest = await fetchLatestCliVersion();- if (latest && !semverGte(latest, raw)) {+ const result = await fetchLatestCliVersion();+ if (result && !semverGte(result.version, raw)) {// MIN_CLI_VERSION is higher than what's published — ignore itreturn writeJSON({ min_cli_version: null });}diff --git a/src/web/src/app/api/runtimes/[runtimeId]/update/route.ts b/src/web/src/app/api/runtimes/[runtimeId]/update/route.tsindex 120d81301..e1a6ac168 100644--- a/src/web/src/app/api/runtimes/[runtimeId]/update/route.ts+++ b/src/web/src/app/api/runtimes/[runtimeId]/update/route.ts@@ -24,12 +24,12 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {);if (!runtime) return writeError("runtime not found", 404);- const latestVersion = await fetchLatestCliVersion();- if (!latestVersion) return writeError("failed to fetch latest CLI version from npm", 502);+ const result = await fetchLatestCliVersion();+ if (!result) return writeError("failed to fetch latest CLI version from npm", 502);- await queries.machine.setPendingUpdateVersion(db, runtime.daemonId, latestVersion);+ await queries.machine.setPendingUpdateVersion(db, runtime.daemonId, result.version);- return writeJSON({ pending_update_version: latestVersion });+ return writeJSON({ pending_update_version: result.version });});export const DELETE = withAuth(async (req: NextRequest, ctx) => {diff --git a/src/web/src/app/api/ws/token/route.ts b/src/web/src/app/api/ws/token/route.tsindex 28e81d25f..4f7dc5804 100644--- a/src/web/src/app/api/ws/token/route.ts+++ b/src/web/src/app/api/ws/token/route.ts@@ -1,5 +1,6 @@import { getCloudflareContext } from "@opennextjs/cloudflare"import { createAuth } from "@/lib/auth"+import { DEV_WS_DO_URL } from "@alook/shared"export async function GET(request: Request) {const { env } = getCloudflareContext()@@ -7,8 +8,15 @@ export async function GET(request: Request) {const session = await auth.api.getSession({ headers: request.headers })if (!session) return new Response("Unauthorized", { status: 401 })+ const wsDoUrl = (env as unknown as Record<string, unknown>).DEV_WS_DO_URL as string | undefined+ let wsPort: number | undefined+ try {+ wsPort = new URL(wsDoUrl || DEV_WS_DO_URL).port ? Number(new URL(wsDoUrl || DEV_WS_DO_URL).port) : undefined+ } catch {}+return Response.json({userId: session.user.id,token: session.session.token,+ ...(wsPort && { wsPort }),})}diff --git a/src/web/src/components/connect-machine-steps.tsx b/src/web/src/components/connect-machine-steps.tsxindex 0fdcbac79..02bdb83ce 100644--- a/src/web/src/components/connect-machine-steps.tsx+++ b/src/web/src/components/connect-machine-steps.tsx@@ -4,7 +4,7 @@ import { useRef, useEffect } from "react";import { Button } from "@/components/ui/button";import { Check } from "lucide-react";import { toast } from "sonner";-import { CLI_CMD } from "@/lib/utils";+import { cliCmd, daemonStartCmd } from "@/lib/utils";function StepIndicator({ step, completed }: { step: number; completed: boolean }) {if (completed) {@@ -42,13 +42,11 @@ export function ConnectMachineSteps({}, [generatedToken, generatingToken, onGenerateToken]);const copyRegister = () => {- navigator.clipboard.writeText(`${CLI_CMD} register --token ${generatedToken}`);+ navigator.clipboard.writeText(`${cliCmd()} register --token ${generatedToken}`);toast.success("Copied to clipboard");};- const daemonCmd = process.env.NODE_ENV === "development"- ? `${CLI_CMD} daemon start --foreground`- : `${CLI_CMD} daemon start`;+ const daemonCmd = daemonStartCmd();const copyDaemon = () => {navigator.clipboard.writeText(daemonCmd);@@ -80,7 +78,7 @@ export function ConnectMachineSteps({onClick={copyRegister}title="Click to copy">- {CLI_CMD} register --token{" "}+ {cliCmd()} register --token{" "}<span className="text-foreground/70">{generatedToken}</span>diff --git a/src/web/src/components/dashboard-navbar.tsx b/src/web/src/components/dashboard-navbar.tsxindex ed52057ca..443069f9e 100644--- a/src/web/src/components/dashboard-navbar.tsx+++ b/src/web/src/components/dashboard-navbar.tsx@@ -22,7 +22,7 @@ import { Logo } from "@/components/logo";import { toast } from "sonner";import type { AgentRuntime as Runtime } from "@alook/shared";import { signOut } from "@/lib/auth-client";-import { CLI_CMD } from "@/lib/utils";+import { cliCmd, daemonStartCmd } from "@/lib/utils";import { ProviderLogo } from "@/components/provider-logo";function OnboardingSteps({@@ -82,12 +82,12 @@ function OnboardingSteps({className="rounded-md bg-muted p-2.5 font-mono text-xs text-muted-foreground cursor-pointer hover:bg-muted/80 transition-colors"onClick={() =>copyToClipboard(- `${CLI_CMD} register --token ${generatedToken}`+ `${cliCmd()} register --token ${generatedToken}`)}title="Click to copy">- {CLI_CMD} register --token{" "}+ {cliCmd()} register --token{" "}<span className="text-foreground/70">{generatedToken.slice(0, 12)}...</span>@@ -96,7 +96,7 @@ function OnboardingSteps({size="sm"onClick={() => {navigator.clipboard.writeText(- `${CLI_CMD} register --token ${generatedToken}`+ `${cliCmd()} register --token ${generatedToken}`);toast.success("Copied to clipboard");}}@@ -124,13 +124,11 @@ function OnboardingSteps({<divclassName="ml-7 rounded-md bg-muted p-2.5 font-mono text-xs text-muted-foreground cursor-pointer hover:bg-muted/80 transition-colors"onClick={() =>- copyToClipboard(process.env.NODE_ENV === "development"- ? `${CLI_CMD} daemon start --foreground`- : `${CLI_CMD} daemon start`)+ copyToClipboard(daemonStartCmd())}title="Click to copy">- {CLI_CMD} daemon start{process.env.NODE_ENV === "development" ? " --foreground" : ""}+ {daemonStartCmd()}</div></div></div>diff --git a/src/web/src/components/home/marketing-footer.tsx b/src/web/src/components/home/marketing-footer.tsxindex 9383d9b77..60587b557 100644--- a/src/web/src/components/home/marketing-footer.tsx+++ b/src/web/src/components/home/marketing-footer.tsx@@ -11,7 +11,7 @@ gsap.registerPlugin(ScrollTrigger);const footerLinks = [{ href: "/templates", label: "Templates" },- { href: "https://discord.gg/24PHyEHU3M", label: "Discord", external: true },+ { href: "https://discord.alook.ai", label: "Discord", external: true },{ href: "mailto:[email protected]", label: "Contact", external: true },];diff --git a/src/web/src/components/runtime-version-gate.tsx b/src/web/src/components/runtime-version-gate.tsxindex 65c98579c..909769cd7 100644--- a/src/web/src/components/runtime-version-gate.tsx+++ b/src/web/src/components/runtime-version-gate.tsx@@ -15,9 +15,13 @@ import { Button } from "@/components/ui/button";import { Badge } from "@/components/ui/badge";import { AlertTriangle, RefreshCw, Terminal } from "lucide-react";import { toast } from "sonner";+import { isLocalMode } from "@/lib/utils";import type { AgentRuntime } from "@alook/shared";-const MANUAL_UPDATE_CMD = "npx @alook/cli@latest daemon stop && npx @alook/cli@latest daemon start";+const isLocal = isLocalMode();+const MANUAL_UPDATE_CMD = isLocal+ ? "npx @alook/app stop && npx @alook/app@latest update && npx @alook/app start"+ : "npx @alook/cli@latest daemon stop && npx @alook/cli@latest daemon start";export function RuntimeVersionGate() {const { runtimes, workspaceId } = useAgentContext();@@ -55,6 +59,10 @@ export function RuntimeVersionGate() {if (outdatedMachines.size === 0) return null;const handleUpdate = async (rt: AgentRuntime) => {+ if (isLocal) {+ setShowManualHint(true);+ return;+ }setUpdating((prev) => new Set(prev).add(rt.id));if (!hintTimer.current) {hintTimer.current = setTimeout(() => {@@ -86,7 +94,9 @@ export function RuntimeVersionGate() {Runtime Update Required</DialogTitle><DialogDescription>- The following machine(s) are running an outdated CLI version (minimum required: v{minVersion}). Please update to continue.+ {isLocal+ ? `Your local Alook app is running an outdated version (minimum required: v${minVersion}). Please update to continue.`+ : `The following machine(s) are running an outdated CLI version (minimum required: v${minVersion}). Please update to continue.`}</DialogDescription></DialogHeader>diff --git a/src/web/src/env.d.ts b/src/web/src/env.d.tsindex 4cbd47187..b02c6faf6 100644--- a/src/web/src/env.d.ts+++ b/src/web/src/env.d.ts@@ -21,6 +21,7 @@ declare namespace Cloudflare {AUTH_OTP_RATE_LIMIT_WINDOW_SEC?: stringRUNTIME_MODEL_OPTIONS?: stringMIN_CLI_VERSION?: string+ NODE_ENV?: string}}diff --git a/src/web/src/lib/api.ts b/src/web/src/lib/api.tsindex d15f89499..423ee1f41 100644--- a/src/web/src/lib/api.ts+++ b/src/web/src/lib/api.ts@@ -188,7 +188,7 @@ export const getMinCliVersion = () =>apiFetch<{ min_cli_version: string | null }>("/api/config/min-version");export const fetchLatestCliVersion = () =>- apiFetch<{ version: string }>("/api/cli/latest-version");+ apiFetch<{ version: string; package: string }>("/api/cli/latest-version");// Channelsexport const listChannels = (workspaceId: string) =>diff --git a/src/web/src/lib/auth.test.ts b/src/web/src/lib/auth.test.tsindex 7f4ab30a6..78095ef1f 100644--- a/src/web/src/lib/auth.test.ts+++ b/src/web/src/lib/auth.test.ts@@ -70,36 +70,29 @@ type AuthOptions = {}}-async function loadCreateAuth(nodeEnv: "production" | "development" | "test") {+async function loadCreateAuth() {vi.resetModules()- const prev = process.env.NODE_ENV- vi.stubEnv("NODE_ENV", nodeEnv)- try {- const mod = await import("./auth")- return mod.createAuth- } finally {- vi.stubEnv("NODE_ENV", prev ?? "test")- }+ const mod = await import("./auth")+ return mod.createAuth}describe("createAuth rate limiting", () => {beforeEach(() => vi.clearAllMocks())it("enables rate limiting only in production", async () => {- const createAuthProd = await loadCreateAuth("production")- const envProd = makeEnv()- const optsProd = (createAuthProd(envProd as never) as { __options: AuthOptions }).__options+ const createAuth = await loadCreateAuth()+ const envProd = makeEnv({ NODE_ENV: "production" })+ const optsProd = (createAuth(envProd as never) as { __options: AuthOptions }).__optionsexpect(optsProd.rateLimit.enabled).toBe(true)- const createAuthDev = await loadCreateAuth("development")- const envDev = makeEnv()- const optsDev = (createAuthDev(envDev as never) as { __options: AuthOptions }).__options+ const envDev = makeEnv({ NODE_ENV: "development" })+ const optsDev = (createAuth(envDev as never) as { __options: AuthOptions }).__optionsexpect(optsDev.rateLimit.enabled).toBe(false)})it("uses default 5/60s for the OTP path when env vars are unset", async () => {- const createAuth = await loadCreateAuth("production")- const env = makeEnv()+ const createAuth = await loadCreateAuth()+ const env = makeEnv({ NODE_ENV: "production" })const opts = (createAuth(env as never) as { __options: AuthOptions }).__optionsexpect(opts.rateLimit.customRules["/email-otp/send-verification-otp"]).toEqual({window: 60,@@ -108,8 +101,9 @@ describe("createAuth rate limiting", () => {})it("honours AUTH_OTP_RATE_LIMIT_MAX / _WINDOW_SEC overrides", async () => {- const createAuth = await loadCreateAuth("production")+ const createAuth = await loadCreateAuth()const env = makeEnv({+ NODE_ENV: "production",AUTH_OTP_RATE_LIMIT_MAX: "3",AUTH_OTP_RATE_LIMIT_WINDOW_SEC: "120",})@@ -121,8 +115,9 @@ describe("createAuth rate limiting", () => {})it("falls back to defaults when env overrides are non-numeric or zero", async () => {- const createAuth = await loadCreateAuth("production")+ const createAuth = await loadCreateAuth()const env = makeEnv({+ NODE_ENV: "production",AUTH_OTP_RATE_LIMIT_MAX: "not-a-number",AUTH_OTP_RATE_LIMIT_WINDOW_SEC: "0",})@@ -134,8 +129,8 @@ describe("createAuth rate limiting", () => {})it("customStorage round-trips values through KV with a >=60s TTL", async () => {- const createAuth = await loadCreateAuth("production")- const env = makeEnv()+ const createAuth = await loadCreateAuth()+ const env = makeEnv({ NODE_ENV: "production" })const opts = (createAuth(env as never) as { __options: AuthOptions }).__optionsconst { get, set } = opts.rateLimit.customStorageconst kv = env.RATE_LIMIT_KV as ReturnType<typeof makeKv>@@ -151,8 +146,8 @@ describe("createAuth rate limiting", () => {})it("clamps KV TTL to 60s when the configured window is shorter", async () => {- const createAuth = await loadCreateAuth("production")- const env = makeEnv({ AUTH_OTP_RATE_LIMIT_WINDOW_SEC: "10" })+ const createAuth = await loadCreateAuth()+ const env = makeEnv({ NODE_ENV: "production", AUTH_OTP_RATE_LIMIT_WINDOW_SEC: "10" })const opts = (createAuth(env as never) as { __options: AuthOptions }).__optionsconst kv = env.RATE_LIMIT_KV as ReturnType<typeof makeKv>await opts.rateLimit.customStorage.set("k", { count: 1, lastRequest: 0 })@@ -160,8 +155,8 @@ describe("createAuth rate limiting", () => {})it("uses the configured window as TTL when it exceeds 60s", async () => {- const createAuth = await loadCreateAuth("production")- const env = makeEnv({ AUTH_OTP_RATE_LIMIT_WINDOW_SEC: "180" })+ const createAuth = await loadCreateAuth()+ const env = makeEnv({ NODE_ENV: "production", AUTH_OTP_RATE_LIMIT_WINDOW_SEC: "180" })const opts = (createAuth(env as never) as { __options: AuthOptions }).__optionsconst kv = env.RATE_LIMIT_KV as ReturnType<typeof makeKv>await opts.rateLimit.customStorage.set("k", { count: 1, lastRequest: 0 })@@ -176,15 +171,15 @@ describe("createAuth session cookie cache", () => {// a D1 round-trip. Without it, the first request after a fresh OTP sign-up// can 401 because the just-written `user` row hasn't replicated yet.it("enables the signed session-data cookie with a positive maxAge", async () => {- const createAuth = await loadCreateAuth("production")- const opts = (createAuth(makeEnv() as never) as { __options: AuthOptions }).__options+ const createAuth = await loadCreateAuth()+ const opts = (createAuth(makeEnv({ NODE_ENV: "production" }) as never) as { __options: AuthOptions }).__optionsexpect(opts.session?.cookieCache?.enabled).toBe(true)expect(opts.session?.cookieCache?.maxAge).toBeGreaterThan(0)})it("enables cookieCache in development too so local sign-up doesn't 401", async () => {- const createAuth = await loadCreateAuth("development")- const opts = (createAuth(makeEnv() as never) as { __options: AuthOptions }).__options+ const createAuth = await loadCreateAuth()+ const opts = (createAuth(makeEnv({ NODE_ENV: "development" }) as never) as { __options: AuthOptions }).__optionsexpect(opts.session?.cookieCache?.enabled).toBe(true)})})diff --git a/src/web/src/lib/auth.ts b/src/web/src/lib/auth.tsindex d6e530ee9..011169d22 100644--- a/src/web/src/lib/auth.ts+++ b/src/web/src/lib/auth.ts@@ -3,7 +3,6 @@ import { emailOTP } from "better-auth/plugins"import { createLogger, DEV_EMAIL_WORKER_URL } from "@alook/shared"import { getOtpSubject, renderOtpEmail } from "./email-templates"-const isProd = process.env.NODE_ENV === "production"const log = createLogger({ service: "auth" })const OTP_RATE_LIMIT_PATH = "/email-otp/send-verification-otp"@@ -18,6 +17,9 @@ function parsePositiveInt(raw: string | undefined, fallback: number): number {}export function createAuth(env: Env) {+ // env.NODE_ENV comes from wrangler [vars] (runtime), process.env.NODE_ENV+ // is inlined at build time by Next.js — only reliable during `next dev`.+ const isProd = (env.NODE_ENV ?? process.env.NODE_ENV) !== "development"const otpMax = parsePositiveInt(env.AUTH_OTP_RATE_LIMIT_MAX, DEFAULT_OTP_RATE_LIMIT_MAX)const otpWindow = parsePositiveInt(env.AUTH_OTP_RATE_LIMIT_WINDOW_SEC,diff --git a/src/web/src/lib/broadcast.ts b/src/web/src/lib/broadcast.tsindex 298d60adf..5e86e39d5 100644--- a/src/web/src/lib/broadcast.ts+++ b/src/web/src/lib/broadcast.ts@@ -4,40 +4,60 @@ import { DEV_WS_DO_URL, createLogger } from "@alook/shared"const log = createLogger({ service: "broadcast" })-async function sendBroadcast(url: string, body: string, label: Record<string, string>) {+async function doSend(url: string, body: string, label: Record<string, string>) {+ let wsDoUrl: string | undefinedtry {- const { env, ctx } = getCloudflareContext()+ const { env } = getCloudflareContext()const wsEnv = env as Env- const promise = wsEnv.WS_DO_WORKER.fetch(`http://internal${url}`, {+ wsDoUrl = (wsEnv as unknown as Record<string, unknown>).DEV_WS_DO_URL as string | undefined++ const res = await wsEnv.WS_DO_WORKER.fetch(`http://internal${url}`, {method: "POST",body,- }).then(- () => {},- (err) => log.warn("broadcast service-binding failed", { ...label, err: String(err) }),- )- ctx.waitUntil(promise)+ })+ if (res.ok) return+ log.warn("broadcast service-binding non-ok", { ...label, status: res.status })+ return} catch {- const res = await fetch(`${DEV_WS_DO_URL}${url}`, {+ // Service binding unavailable — fall through to HTTP+ }++ const fallbackUrl = wsDoUrl || DEV_WS_DO_URL+ try {+ const res = await fetch(`${fallbackUrl}${url}`, {method: "POST",headers: { "Content-Type": "application/json" },body,})if (!res.ok) {- log.warn("broadcast fallback failed", { ...label, status: res.status })+ log.warn("broadcast failed", { ...label, status: res.status })}+ } catch (err) {+ log.warn("broadcast error", { ...label, err: String(err) })+ }+}++function sendBroadcast(url: string, body: string, label: Record<string, string>): Promise<void> {+ const promise = doSend(url, body, label)+ try {+ const { ctx } = getCloudflareContext()+ ctx.waitUntil(promise)+ } catch {+ // Not in CF context — promise runs on its own}+ return promise}-export async function broadcastToUser(userId: string, message: WsMessage) {- await sendBroadcast(+export function broadcastToUser(userId: string, message: WsMessage): Promise<void> {+ return sendBroadcast(`/broadcast/user/${userId}`,JSON.stringify(message),{ userId, type: message.type },)}-export async function broadcastToAgent(agentId: string, message: WsMessage) {- await sendBroadcast(+export function broadcastToAgent(agentId: string, message: WsMessage): Promise<void> {+ return sendBroadcast(`/broadcast/${agentId}`,JSON.stringify(message),{ agentId, type: message.type },diff --git a/src/web/src/lib/npm.ts b/src/web/src/lib/npm.tsindex e4bfa1112..b9bfef488 100644--- a/src/web/src/lib/npm.ts+++ b/src/web/src/lib/npm.ts@@ -1,9 +1,25 @@-export async function fetchLatestCliVersion(): Promise<string | null> {+import { getCloudflareContext } from "@opennextjs/cloudflare"++// In local mode (@alook/app), check @alook/app on npm.+// In cloud mode, check @alook/cli.+// Both packages are in the same monorepo and version-bumped together,+// so the daemon's reported cli_version will match either package.+function getPackageName(): string {try {- const res = await fetch("https://registry.npmjs.org/@alook/cli/latest");+ const { env } = getCloudflareContext()+ if ((env as unknown as Record<string, unknown>).NODE_ENV === "development") return "@alook/app"+ } catch {}+ return "@alook/cli"+}++export async function fetchLatestCliVersion(): Promise<{ version: string; package: string } | null> {+ const pkg = getPackageName()+ try {+ const res = await fetch(`https://registry.npmjs.org/${pkg}/latest`);if (!res.ok) return null;const data = (await res.json()) as { version?: string };- return data.version ?? null;+ if (!data.version) return null;+ return { version: data.version, package: pkg };} catch {return null;}diff --git a/src/web/src/lib/use-user-ws.ts b/src/web/src/lib/use-user-ws.tsindex b2eada148..322f23918 100644--- a/src/web/src/lib/use-user-ws.ts+++ b/src/web/src/lib/use-user-ws.ts@@ -1,9 +1,10 @@"use client"import { useEffect, useRef, useCallback } from "react"import type { WsMessage } from "@alook/shared"+import { isLocalMode } from "@/lib/utils"-const isDev = process.env.NODE_ENV === "development"-const WS_DO_PORT = Number(process.env.NEXT_PUBLIC_WS_DO_PORT) || 8789+const isDev = isLocalMode()+const WS_DO_PORT_DEFAULT = Number(process.env.NEXT_PUBLIC_WS_DO_PORT) || 8789const WS_RECONNECT_INIT = Number(process.env.NEXT_PUBLIC_WS_RECONNECT_DELAY_MS) || 1000const WS_RECONNECT_MAX = Number(process.env.NEXT_PUBLIC_WS_RECONNECT_MAX_DELAY_MS) || 30_000@@ -30,6 +31,7 @@ export function useUserWs(onMessage: (msg: WsMessage) => void) {const connect = useCallback(async () => {let userId: stringlet authToken: string+ let wsPort: number = WS_DO_PORT_DEFAULTtry {const res = await fetch("/api/ws/token")if (!res.ok) {@@ -37,9 +39,10 @@ export function useUserWs(onMessage: (msg: WsMessage) => void) {scheduleReconnect()return}- const body = await res.json() as { userId: string; token: string }+ const body = await res.json() as { userId: string; token: string; wsPort?: number }userId = body.userIdauthToken = body.token+ if (body.wsPort) wsPort = body.wsPort} catch (err) {console.warn("[ws] token fetch error:", err)scheduleReconnect()@@ -47,7 +50,7 @@ export function useUserWs(onMessage: (msg: WsMessage) => void) {}const url = isDev- ? `ws://localhost:${WS_DO_PORT}/?userId=${userId}`+ ? `ws://localhost:${wsPort}/?userId=${userId}`: `${location.origin.replace("http", "ws")}/api/ws/user?userId=${userId}`let ws: WebSocket@@ -76,8 +79,6 @@ export function useUserWs(onMessage: (msg: WsMessage) => void) {ws.onerror = () => {}ws.onclose = () => {- // Ownership check: only reconnect if this WS is still the current one.- // If effect cleanup already replaced wsRef.current, this is an orphan — skip.if (ws !== wsRef.current) returnscheduleReconnect()}@@ -90,12 +91,10 @@ export function useUserWs(onMessage: (msg: WsMessage) => void) {useEffect(() => {connect()return () => {- // Clear any pending reconnect timer firstif (reconnectTimerRef.current !== null) {clearTimeout(reconnectTimerRef.current)reconnectTimerRef.current = null}- // Nullify wsRef BEFORE closing so the onclose handler's ownership check failsconst ws = wsRef.currentwsRef.current = nullws?.close()diff --git a/src/web/src/lib/use-ws.ts b/src/web/src/lib/use-ws.tsindex d627b2d03..ae557f502 100644--- a/src/web/src/lib/use-ws.ts+++ b/src/web/src/lib/use-ws.ts@@ -1,9 +1,10 @@"use client"import { useEffect, useRef, useCallback } from "react"import type { WsMessage } from "@alook/shared"+import { isLocalMode } from "@/lib/utils"-const isDev = process.env.NODE_ENV === "development"-const WS_DO_PORT = Number(process.env.NEXT_PUBLIC_WS_DO_PORT) || 8789+const isDev = isLocalMode()+const WS_DO_PORT_DEFAULT = Number(process.env.NEXT_PUBLIC_WS_DO_PORT) || 8789const WS_RECONNECT_INIT = Number(process.env.NEXT_PUBLIC_WS_RECONNECT_DELAY_MS) || 1000const WS_RECONNECT_MAX = Number(process.env.NEXT_PUBLIC_WS_RECONNECT_MAX_DELAY_MS) || 30_000@@ -20,21 +21,22 @@ export function useAgentWs(agentId: string, onMessage: (msg: WsMessage) => void)const connectRef = useRef<(() => Promise<void>) | null>(null)const connect = useCallback(async () => {- // Unified dev/prod flow — see use-user-ws.ts for rationale.let userId: stringlet authToken: string+ let wsPort: number = WS_DO_PORT_DEFAULTtry {const res = await fetch("/api/ws/token")if (!res.ok) return- const body = await res.json() as { userId: string; token: string }+ const body = await res.json() as { userId: string; token: string; wsPort?: number }userId = body.userIdauthToken = body.token+ if (body.wsPort) wsPort = body.wsPort} catch {return}const url = isDev- ? `ws://localhost:${WS_DO_PORT}/?userId=${userId}&agentId=${agentId}`+ ? `ws://localhost:${wsPort}/?userId=${userId}&agentId=${agentId}`: `${location.origin.replace("http", "ws")}/api/ws?userId=${userId}&agentId=${agentId}`let ws: WebSocket@@ -61,8 +63,6 @@ export function useAgentWs(agentId: string, onMessage: (msg: WsMessage) => void)ws.onerror = () => {}ws.onclose = () => {- // Ownership check: only reconnect if this WS is still the current one.- // If effect cleanup already replaced wsRef.current, this is an orphan — skip.if (ws !== wsRef.current) returnconst delay = Math.min(reconnectDelay.current, WS_RECONNECT_MAX)@@ -80,12 +80,10 @@ export function useAgentWs(agentId: string, onMessage: (msg: WsMessage) => void)useEffect(() => {connect()return () => {- // Clear any pending reconnect timer firstif (reconnectTimerRef.current !== null) {clearTimeout(reconnectTimerRef.current)reconnectTimerRef.current = null}- // Nullify wsRef BEFORE closing so the onclose handler's ownership check failsconst ws = wsRef.currentwsRef.current = nullws?.close()diff --git a/src/web/src/lib/utils.test.ts b/src/web/src/lib/utils.test.tsnew file mode 100644index 000000000..80d1a6c06--- /dev/null+++ b/src/web/src/lib/utils.test.ts@@ -0,0 +1,83 @@+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";++let mockHostname: string | undefined;++vi.mock("./utils", async () => {+ const actual = await vi.importActual<typeof import("./utils")>("./utils");+ return {+ ...actual,+ isLocalMode: () => {+ if (mockHostname && ["localhost", "127.0.0.1"].includes(mockHostname)) return true;+ return process.env.NODE_ENV === "development";+ },+ cliCmd: () => {+ if (process.env.NODE_ENV === "development") return "pnpm dev:cli";+ if (mockHostname && ["localhost", "127.0.0.1"].includes(mockHostname)) {+ return "npx @alook/app cli";+ }+ return "npx @alook/cli";+ },+ daemonStartCmd: () => {+ let base: string;+ if (process.env.NODE_ENV === "development") base = "pnpm dev:cli";+ else if (mockHostname && ["localhost", "127.0.0.1"].includes(mockHostname)) base = "npx @alook/app cli";+ else base = "npx @alook/cli";+ const cmd = `${base} daemon start`;+ if (process.env.NODE_ENV === "development") return `${cmd} --foreground`;+ return cmd;+ },+ };+});++import { isLocalMode, cliCmd, daemonStartCmd } from "./utils";++beforeEach(() => {+ mockHostname = undefined;+});++afterEach(() => {+ mockHostname = undefined;+});++describe("isLocalMode", () => {+ it("returns true on localhost", () => {+ mockHostname = "localhost";+ expect(isLocalMode()).toBe(true);+ });++ it("returns true on 127.0.0.1", () => {+ mockHostname = "127.0.0.1";+ expect(isLocalMode()).toBe(true);+ });++ it("returns false for non-local hostname in production build", () => {+ mockHostname = "alook.ai";+ expect(isLocalMode()).toBe(false);+ });+});++describe("cliCmd", () => {+ it("returns 'npx @alook/cli' in production cloud", () => {+ mockHostname = "alook.ai";+ expect(cliCmd()).toBe("npx @alook/cli");+ });++ it("returns 'npx @alook/app cli' on localhost (app mode)", () => {+ mockHostname = "localhost";+ expect(cliCmd()).toBe("npx @alook/app cli");+ });+});++describe("daemonStartCmd", () => {+ it("no --foreground in production cloud", () => {+ mockHostname = "alook.ai";+ expect(daemonStartCmd()).toBe("npx @alook/cli daemon start");+ expect(daemonStartCmd()).not.toContain("--foreground");+ });++ it("no --foreground in app mode (localhost, production build)", () => {+ mockHostname = "localhost";+ expect(daemonStartCmd()).toBe("npx @alook/app cli daemon start");+ expect(daemonStartCmd()).not.toContain("--foreground");+ });+});diff --git a/src/web/src/lib/utils.ts b/src/web/src/lib/utils.tsindex 7664553da..e2108375b 100644--- a/src/web/src/lib/utils.ts+++ b/src/web/src/lib/utils.ts@@ -5,5 +5,25 @@ export function cn(...inputs: ClassValue[]) {return twMerge(clsx(inputs))}-export const CLI_CMD =- process.env.NODE_ENV === "development" ? "pnpm dev:cli" : "npx @alook/cli";+export function isLocalMode(): boolean {+ if (typeof window !== "undefined"+ && ["localhost", "127.0.0.1"].includes(window.location.hostname)) return true+ return process.env.NODE_ENV === "development"+}++export function cliCmd(): string {+ if (process.env.NODE_ENV === "development") return "pnpm dev:cli"+ if (typeof window !== "undefined"+ && ["localhost", "127.0.0.1"].includes(window.location.hostname)) {+ return "npx @alook/app cli"+ }+ return "npx @alook/cli"+}++// --foreground is only needed in monorepo dev mode (pnpm dev:cli).+// In @alook/app mode, the daemon runs as a background process.+export function daemonStartCmd(): string {+ const base = `${cliCmd()} daemon start`+ if (process.env.NODE_ENV === "development") return `${base} --foreground`+ return base+}