Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

feat(webv2): initial multi-user implementation

joshistoastc31e51aedb25
diff --git a/invokeai/frontend/webv2/index.html b/invokeai/frontend/webv2/index.html
index 252882e766..724ec38c92 100644
--- a/invokeai/frontend/webv2/index.html
+++ b/invokeai/frontend/webv2/index.html
@@ -7,6 +7,8 @@
<script>
// Apply the saved theme before first paint so non-default themes don't
// flash the default dark surfaces. ThemeController re-applies it on mount.
+ // The theme hint key is user-agnostic (the workbench snapshot is per-user
+ // on multi-user backends); the snapshot read is a legacy fallback.
(function () {
try {
var themeColorSchemes = {
@@ -16,8 +18,11 @@
mono: 'dark',
ultradark: 'dark',
};
- var raw = localStorage.getItem('invokeai:v7:webv2:workbench');
- var id = raw && JSON.parse(raw).state.account.preferences.themeId;
+ var id = localStorage.getItem('invokeai:v7:webv2:theme');
+ if (!id) {
+ var raw = localStorage.getItem('invokeai:v7:webv2:workbench');
+ id = raw && JSON.parse(raw).state.account.preferences.themeId;
+ }
var colorScheme = themeColorSchemes[id];
if (colorScheme) {
var isLight = colorScheme === 'light';
diff --git a/invokeai/frontend/webv2/package.json b/invokeai/frontend/webv2/package.json
index dccfd1f04a..3cbccc714e 100644
--- a/invokeai/frontend/webv2/package.json
+++ b/invokeai/frontend/webv2/package.json
@@ -21,6 +21,7 @@
"@chakra-ui/react": "^3.36.0",
"@emotion/react": "^11.14.0",
"@fontsource/inter": "^5.2.8",
+ "@tanstack/react-router": "^1.170.15",
"@tanstack/react-virtual": "^3.14.2",
"lucide-react": "^1.17.0",
"react": "^19.2.7",
diff --git a/invokeai/frontend/webv2/pnpm-lock.yaml b/invokeai/frontend/webv2/pnpm-lock.yaml
index 02adfcfd0f..f3c6147527 100644
--- a/invokeai/frontend/webv2/pnpm-lock.yaml
+++ b/invokeai/frontend/webv2/pnpm-lock.yaml
@@ -17,6 +17,9 @@ importers:
'@fontsource/inter':
specifier: ^5.2.8
version: 5.2.8
+ '@tanstack/react-router':
+ specifier: ^1.170.15
'@tanstack/react-virtual':
specifier: ^3.14.2
@@ -97,6 +100,10 @@ packages:
resolution: {integrity: sha512-DkXD5OJQaAQIdZ1bt3UZdEnHAn9Imd3IVBdX03UFe+ony9Ojw5pzr9YVKGDY1jt+Gcn/FnGkNf8r+Vj5NOJWtQ==}
engines: {node: '>=6.9.0'}
+ '@babel/[email protected]':
+ resolution: {integrity: sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g==}
+ engines: {node: '>=6.9.0'}
+
resolution: {integrity: sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==}
engines: {node: '>=6.9.0'}
@@ -385,6 +392,9 @@ packages:
'@jridgewell/[email protected]':
resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==}
+ '@jridgewell/[email protected]':
+ resolution: {integrity: sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==}
+
'@jridgewell/[email protected]':
resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==}
engines: {node: '>=6.0.0'}
@@ -754,12 +764,36 @@ packages:
resolution: {integrity: sha512-5lSsMOTXURePglDfvuAQUqkGek9Hg2kksOYay2m0+XR++b2NWYL/4sWyuvVBIs8oKnJaxkdi9whaL/sqN13afw==}
+ '@tanstack/[email protected]':
+ resolution: {integrity: sha512-79pf/RkhteYZTRgcR4F9kbk84P2N8rugQJswxfIqovlbRiT3yI7eBE+5QorIrZaOKktsgzRlXh1l/du/xpl4iA==}
+ engines: {node: '>=20.19'}
+
+ '@tanstack/[email protected]':
+ resolution: {integrity: sha512-GawYz7HEjj8rTUUDoT/SemDEVm63pZUO+2mOcXHY9Jl3EwMS5gFBnPu/2UvcrwRm1jN1k79fokc0d4aFmrLatg==}
+ engines: {node: '>=20.19'}
+ peerDependencies:
+ react: '>=18.0.0 || >=19.0.0'
+ react-dom: '>=18.0.0 || >=19.0.0'
+
+ '@tanstack/[email protected]':
+ resolution: {integrity: sha512-y2iHd/N9OkoQbFJLUX1T9vbc2O9tjH0pQRgTcx1/Nz4IlwLvkgpuglXUx+mXt0g5ZDFrEeDnONPqkbfxXJKwRg==}
+ peerDependencies:
+ react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
+ react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
+
'@tanstack/[email protected]':
resolution: {integrity: sha512-IpWnmCLvuymRfeeLNVXIzNEYBFLpd3drVIS91sqV78VTZFyldlChkOocZRCPp1B+Wnk09bcLNme8WaMU/9/9bQ==}
peerDependencies:
react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
+ '@tanstack/[email protected]':
+ resolution: {integrity: sha512-+NOwEj1kO/6IGmpHRIZHasYxYWpyBQGNIZAST9aNrk9Q3YlU9SgqVnl1pbLa9qAKfeNdXQIRve0RQb/0kyDeDA==}
+ engines: {node: '>=20.19'}
+
+ '@tanstack/[email protected]':
+ resolution: {integrity: sha512-8reSzl/qGWGGVKhBoxXPMWzATSbZLZFWhwBAFO9NAyp0TxzfBP0mIrGb8CP8KrQTmvzXlR/vFPPUrHTLBGyFyw==}
+
'@tanstack/[email protected]':
resolution: {integrity: sha512-gOxY/hFkPh/XQYhnThBHzkbkX3Ed+z/iushyz+R+JAr213aXxUDgQoTgTdrDpBSRsjFM73P/KfUyWmaF9WHMkQ==}
@@ -1076,10 +1110,23 @@ packages:
resolution: {integrity: sha512-Ixm8tFfoKKIPYdCCKYTsqv+Fd4IJ0DQqMyEimo+pxUOMUR9cVPlwTrFt9Avu+3cb6Zp3mAzl+t1MrG2fxxKsxw==}
+ resolution: {integrity: sha512-honAfLBde0HAFLdNyBEfuuENkF6zR+ozxqxa/2zJKHBe1qzLqyTSeRKpdPEHAP03rlDGyQOPnCSxnVpVqQo9Mg==}
+ engines: {node: '>=6.0.0'}
+ hasBin: true
+
+ resolution: {integrity: sha512-48xSriZYYg+8qXna9kwqjIVzuQxi+KYWp2+5nCYnYKPTr0LvD89Jqk2Or5ogxz0NUMfIjhh2lIUX/LyX9B4oIg==}
+ engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7}
+ hasBin: true
+
resolution: {integrity: sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==}
engines: {node: '>=6'}
+ resolution: {integrity: sha512-l8xKG+gwAIExZGl9FrF7KUwuOmk6wbEPC9Xoy/RtnWv1XG0Q4LFlagaLpUv3Kiza3W/wm27zy0yWJEieYKAP6w==}
+
resolution: {integrity: sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==}
engines: {node: '>=18'}
@@ -1090,6 +1137,9 @@ packages:
resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==}
+ resolution: {integrity: sha512-UaXxwISYJPTr9hwQxMFYZ7kNhSXboMXP+Z3TRX6f1/NyaGPfuNUZOWP1pUEb75B2HjfklIYLVRfWiFZJyC6Npg==}
+
resolution: {integrity: sha512-AdmX6xUzdNASswsFtmwSt7Vj8po9IuqXm0UXz7QKPuEUmPB4XyjGfaAr2PSuELMwkRMVH1EpIkX5bTZGRB3eCA==}
engines: {node: '>=10'}
@@ -1110,6 +1160,9 @@ packages:
resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==}
engines: {node: '>=8'}
+ resolution: {integrity: sha512-e9htk9mAYL6AzmkEhSvVVw7IWGSBJ/Bqdn2eRyRLrj1g6sncN4WbFt5qnILYoCktktr45pyjIrOiRvBThQ808w==}
+
resolution: {integrity: sha512-QCwxUDULPlXv8F6tqMMKx5dNkTe6OaBYRMPYeXKBlyOoKvAmE0ac6pW7fFhSscJ/5SI7666/U/B+MElbsrJlIg==}
@@ -1132,6 +1185,10 @@ packages:
engines: {node: '>=18'}
hasBin: true
+ resolution: {integrity: sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==}
+ engines: {node: '>=6'}
+
resolution: {integrity: sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==}
engines: {node: '>=10'}
@@ -1163,6 +1220,10 @@ packages:
resolution: {integrity: sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==}
+ resolution: {integrity: sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==}
+ engines: {node: '>=6.9.0'}
+
resolution: {integrity: sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==}
engines: {node: '>= 0.4'}
@@ -1181,6 +1242,10 @@ packages:
resolution: {integrity: sha512-evOr8xfXKxE6qSR0hSXL2r3sd7ALj8+7jQEUvPYcm5sgZFdJ+AYzT6yNmJenvIYQBgIGwfwz08sL8zoL7yq2BA==}
engines: {node: '>= 0.4'}
+ resolution: {integrity: sha512-/SXsVh7KpPRISrD4ffrGSxnTLlUBzEQUfWIusaJPrpJ93FW1P0YEZri5vAUkFsA0m2HRUhQRQadk2wJ+EeKowQ==}
+ engines: {node: '>=18'}
+
resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==}
@@ -1192,6 +1257,11 @@ packages:
resolution: {integrity: sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==}
+ resolution: {integrity: sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==}
+ engines: {node: '>=6'}
+ hasBin: true
+
resolution: {integrity: sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg==}
engines: {node: '>= 12.0.0'}
@@ -1265,6 +1335,9 @@ packages:
resolution: {integrity: sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==}
+ resolution: {integrity: sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==}
+
resolution: {integrity: sha512-9FA9evdox/JQL5PT57fdA1x/yg8T7knJ98+zjTL3UfKza6pflQUUh3XtaQIHKvnsJw1lmsEyHVlt5jchYxOQ5w==}
peerDependencies:
@@ -1281,6 +1354,10 @@ packages:
engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
hasBin: true
+ resolution: {integrity: sha512-Uzmd6LXpouKo8EUK68IjH4+E01w/hXyV3R3g/geCJo+rXLNfh1xucB+LOzYEOQPSiUK3h/xZf0cQGcSsmyL2Og==}
+ engines: {node: '>=18'}
+
resolution: {integrity: sha512-AWGB9WFcRXOQs48Z/udjI5ZcZMHXwX8XPByNpOydgcGsDLIzjGizhoMWJyKAWze7AVW/2W1i+/gPX4YtKe5cyg==}
engines: {node: '>=12.20.0'}
@@ -1383,6 +1460,20 @@ packages:
resolution: {integrity: sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==}
+ resolution: {integrity: sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==}
+ hasBin: true
+
+ resolution: {integrity: sha512-S0xQPhUTefAhNvNWFg0c1J8qJArHt5KdtJ/cFAofo06KD1MVSeFWyl4iiu+ApDIuw0WhjpOfCdgConOfAnLgkw==}
+ engines: {node: '>=10'}
+ peerDependencies:
+ seroval: ^1.0
+
+ resolution: {integrity: sha512-46uFvgrXTVxZcUorgSSRZ4y+ieqLLQRMlG4bnCZKW3qI6BZm7Rg4ntMW4p1mILEEBZWrFlcpp0AyIIlM6jD9iw==}
+ engines: {node: '>=10'}
+
resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==}
@@ -1445,9 +1536,20 @@ packages:
resolution: {integrity: sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==}
+ resolution: {integrity: sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==}
+ hasBin: true
+ peerDependencies:
+ browserslist: '>= 4.21.0'
+
resolution: {integrity: sha512-0rjE8iEJe4YmT9TOhwsZtqCMRLc5DXZUI2UEYUUg63ikBkqqE5EYWaI0etFe/5KUcmcYwLih2RND1kq+hrUJXA==}
+ resolution: {integrity: sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w==}
+ peerDependencies:
+ react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
+
resolution: {integrity: sha512-h9bXPmJichP5fLmVQo3PyaGSDE2n3aPuomeAlVRm0JLmt4rY6zmPKd59HYI4LNW8oTK7tlTsuC7l/m7awx9Jcw==}
engines: {node: ^20.19.0 || >=22.12.0}
@@ -1553,6 +1655,9 @@ packages:
resolution: {integrity: sha512-TEU+nJVUUnA4CYJFLvK5X9AOeH4KvDvhIfm0vV1GaQRtchnG0hgK5p8hw/xjv8cunWYCsiPCSDzObPyhEwq3KQ==}
engines: {node: '>=0.4.0'}
+ resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==}
+
resolution: {integrity: sha512-vIYeF1u3CjlhAFekPPAk2h/Kv4T3mAkMox5OymRiJQB0spDP10LHvt+K7G9Ny6NuuMAb25/6n1qyUjAcGNf/AA==}
engines: {node: '>= 6'}
@@ -1640,6 +1745,28 @@ snapshots:
js-tokens: 4.0.0
picocolors: 1.1.1
+ '@babel/[email protected]': {}
+
+ '@babel/[email protected]':
+ dependencies:
+ '@babel/code-frame': 7.29.7
+ '@babel/generator': 7.29.7
+ '@babel/helper-compilation-targets': 7.29.7
+ '@babel/helper-module-transforms': 7.29.7(@babel/[email protected])
+ '@babel/helpers': 7.29.7
+ '@babel/parser': 7.29.7
+ '@babel/template': 7.29.7
+ '@babel/traverse': 7.29.7
+ '@babel/types': 7.29.7
+ '@jridgewell/remapping': 2.3.5
+ convert-source-map: 2.0.0
+ debug: 4.4.3
+ gensync: 1.0.0-beta.2
+ json5: 2.2.3
+ semver: 6.3.1
+ transitivePeerDependencies:
+ - supports-color
+
dependencies:
'@babel/parser': 7.29.7
@@ -1648,6 +1775,14 @@ snapshots:
'@jridgewell/trace-mapping': 0.3.31
jsesc: 3.1.0
+ '@babel/[email protected]':
+ dependencies:
+ '@babel/compat-data': 7.29.7
+ '@babel/helper-validator-option': 7.29.7
+ browserslist: 4.28.2
+ lru-cache: 5.1.1
+ semver: 6.3.1
+
'@babel/[email protected]': {}
@@ -1657,10 +1792,26 @@ snapshots:
transitivePeerDependencies:
- supports-color
+ dependencies:
+ '@babel/core': 7.29.7
+ '@babel/helper-module-imports': 7.29.7
+ '@babel/helper-validator-identifier': 7.29.7
+ '@babel/traverse': 7.29.7
+ transitivePeerDependencies:
+ - supports-color
+
'@babel/[email protected]': {}
'@babel/[email protected]': {}
+ '@babel/[email protected]': {}
+
+ '@babel/[email protected]':
+ dependencies:
+ '@babel/template': 7.29.7
+ '@babel/types': 7.29.7
+
dependencies:
'@babel/types': 7.29.7
@@ -1891,6 +2042,11 @@ snapshots:
'@jridgewell/sourcemap-codec': 1.5.5
'@jridgewell/trace-mapping': 0.3.31
+ '@jridgewell/[email protected]':
+ dependencies:
+ '@jridgewell/gen-mapping': 0.3.13
+ '@jridgewell/trace-mapping': 0.3.31
+
'@jridgewell/[email protected]': {}
'@jridgewell/[email protected]': {}
@@ -2074,6 +2230,15 @@ snapshots:
'@rolldown/[email protected]':
optional: true
+ dependencies:
+ '@babel/core': 7.29.7
+ picomatch: 4.0.4
+ rolldown: 1.0.3
+ optionalDependencies:
+ '@babel/runtime': 7.29.7
+ vite: 8.0.16(@types/[email protected])([email protected])
+
'@rolldown/[email protected]': {}
'@socket.io/[email protected]': {}
@@ -2084,12 +2249,39 @@ snapshots:
dependencies:
tslib: 2.8.1
+ '@tanstack/[email protected]': {}
+
+ dependencies:
+ '@tanstack/history': 1.162.0
+ '@tanstack/react-store': 0.9.3([email protected]([email protected]))([email protected])
+ '@tanstack/router-core': 1.171.13
+ isbot: 5.1.42
+ react: 19.2.7
+ react-dom: 19.2.7([email protected])
+
+ dependencies:
+ '@tanstack/store': 0.9.3
+ react: 19.2.7
+ react-dom: 19.2.7([email protected])
+ use-sync-external-store: 1.6.0([email protected])
+
dependencies:
'@tanstack/virtual-core': 3.17.0
react: 19.2.7
react-dom: 19.2.7([email protected])
+ '@tanstack/[email protected]':
+ dependencies:
+ '@tanstack/history': 1.162.0
+ cookie-es: 3.1.1
+ seroval: 1.5.4
+ seroval-plugins: 1.5.4([email protected])
+
+ '@tanstack/[email protected]': {}
+
'@tanstack/[email protected]': {}
@@ -2120,11 +2312,12 @@ snapshots:
dependencies:
csstype: 3.2.3
dependencies:
'@rolldown/pluginutils': 1.0.1
vite: 8.0.16(@types/[email protected])([email protected])
optionalDependencies:
babel-plugin-react-compiler: 1.0.0
'@vitest/[email protected]':
@@ -2747,14 +2940,28 @@ snapshots:
dependencies:
'@babel/types': 7.29.7
+
+ dependencies:
+ baseline-browser-mapping: 2.10.35
+ caniuse-lite: 1.0.30001797
+ electron-to-chromium: 1.5.371
+ node-releases: 2.0.47
+ update-browserslist-db: 1.2.3([email protected])
+
+
+
dependencies:
'@types/parse-json': 4.0.2
@@ -2771,6 +2978,8 @@ snapshots:
+
dependencies:
'@socket.io/component-emitter': 3.1.2
@@ -2823,6 +3032,8 @@ snapshots:
'@esbuild/win32-x64': 0.27.7
optional: true
+
@@ -2842,6 +3053,8 @@ snapshots:
+
dependencies:
function-bind: 1.1.2
@@ -2861,12 +3074,16 @@ snapshots:
dependencies:
hasown: 2.0.4
+
+
optional: true
@@ -2918,6 +3135,10 @@ snapshots:
+ dependencies:
+ yallist: 3.1.1
+
dependencies:
react: 19.2.7
@@ -2930,6 +3151,8 @@ snapshots:
+
@@ -3058,6 +3281,14 @@ snapshots:
+
+ dependencies:
+ seroval: 1.5.4
+
+
@@ -3109,8 +3340,18 @@ snapshots:
+ dependencies:
+ browserslist: 4.28.2
+ escalade: 3.2.0
+ picocolors: 1.1.1
+
+ dependencies:
+ react: 19.2.7
+
dependencies:
lightningcss: 1.32.0
@@ -3159,6 +3400,8 @@ snapshots:
+
diff --git a/invokeai/frontend/webv2/src/App.tsx b/invokeai/frontend/webv2/src/App.tsx
index 3204dd064a..76e0190d2a 100644
--- a/invokeai/frontend/webv2/src/App.tsx
+++ b/invokeai/frontend/webv2/src/App.tsx
@@ -1,21 +1,13 @@
import { ChakraProvider } from '@chakra-ui/react';
+import { RouterProvider } from '@tanstack/react-router';
+import { router } from './router';
import { system } from './theme/system';
import { AppToaster } from './workbench/components/ui/toaster';
-import { ThemeController } from './workbench/ThemeController';
-import { ModelsRuntime } from './workbench/widgets/models/ModelsRuntime';
-import { WorkbenchProvider } from './workbench/WorkbenchContext';
-import { WorkbenchRuntime } from './workbench/WorkbenchRuntime';
-import { WorkbenchShell } from './workbench/WorkbenchShell';
export const App = () => (
<ChakraProvider value={system}>
<AppToaster />
- <WorkbenchProvider>
- <ThemeController />
- <WorkbenchRuntime />
- <ModelsRuntime />
- <WorkbenchShell />
- </WorkbenchProvider>
+ <RouterProvider router={router} />
</ChakraProvider>
);
diff --git a/invokeai/frontend/webv2/src/WorkbenchApp.tsx b/invokeai/frontend/webv2/src/WorkbenchApp.tsx
new file mode 100644
index 0000000000..c018866671
--- /dev/null
+++ b/invokeai/frontend/webv2/src/WorkbenchApp.tsx
@@ -0,0 +1,21 @@
+import { SessionExpiryGuard } from './workbench/auth/components/SessionExpiryGuard';
+import { ThemeController } from './workbench/ThemeController';
+import { ModelsRuntime } from './workbench/widgets/models/ModelsRuntime';
+import { WorkbenchProvider } from './workbench/WorkbenchContext';
+import { WorkbenchRuntime } from './workbench/WorkbenchRuntime';
+import { WorkbenchShell } from './workbench/WorkbenchShell';
+
+/**
+ * The authenticated application: providers, runtimes, and the shell. Mounted
+ * by the index route once the auth guard has resolved, so the backend socket
+ * always connects with a valid token (or none, in single-user mode).
+ */
+export const WorkbenchApp = () => (
+ <WorkbenchProvider>
+ <ThemeController />
+ <SessionExpiryGuard />
+ <WorkbenchRuntime />
+ <ModelsRuntime />
+ <WorkbenchShell />
+ </WorkbenchProvider>
+);
diff --git a/invokeai/frontend/webv2/src/router.tsx b/invokeai/frontend/webv2/src/router.tsx
new file mode 100644
index 0000000000..1f38d04f0a
--- /dev/null
+++ b/invokeai/frontend/webv2/src/router.tsx
@@ -0,0 +1,99 @@
+import { Center, Spinner } from '@chakra-ui/react';
+import {
+ createHashHistory,
+ createRootRoute,
+ createRoute,
+ createRouter,
+ Navigate,
+ Outlet,
+ redirect,
+} from '@tanstack/react-router';
+
+import { ensureAuthSession } from './workbench/auth/session';
+import { LoginScreen } from './workbench/auth/components/LoginScreen';
+import { SetupScreen } from './workbench/auth/components/SetupScreen';
+import { WorkbenchApp } from './WorkbenchApp';
+
+/**
+ * Code-based route tree. Every guard starts from `ensureAuthSession()`, which
+ * resolves the backend's multi-user status once per app load:
+ *
+ * - multi-user off → the workbench renders directly and /login + /setup bounce home
+ * - setup required → everything funnels to /setup
+ * - signed out → the workbench redirects to /login
+ *
+ * Hash history is used because the bundle is served with a relative base
+ * (`./`), so the app cannot rely on server-side fallback for deep paths.
+ */
+
+const rootRoute = createRootRoute({ component: Outlet });
+
+const workbenchRoute = createRoute({
+ beforeLoad: async () => {
+ const session = await ensureAuthSession();
+
+ if (!session.multiuserEnabled) {
+ return;
+ }
+
+ if (session.setupRequired) {
+ throw redirect({ to: '/setup' });
+ }
+
+ if (session.user === null) {
+ throw redirect({ to: '/login' });
+ }
+ },
+ component: WorkbenchApp,
+ getParentRoute: () => rootRoute,
+ path: '/',
+});
+
+const loginRoute = createRoute({
+ beforeLoad: async () => {
+ const session = await ensureAuthSession();
+
+ if (session.multiuserEnabled && session.setupRequired) {
+ throw redirect({ to: '/setup' });
+ }
+
+ if (!session.multiuserEnabled || session.user !== null) {
+ throw redirect({ to: '/' });
+ }
+ },
+ component: LoginScreen,
+ getParentRoute: () => rootRoute,
+ path: '/login',
+});
+
+const setupRoute = createRoute({
+ beforeLoad: async () => {
+ const session = await ensureAuthSession();
+
+ if (!session.multiuserEnabled || !session.setupRequired) {
+ throw redirect({ to: '/' });
+ }
+ },
+ component: SetupScreen,
+ getParentRoute: () => rootRoute,
+ path: '/setup',
+});
+
+const RouterPending = () => (
+ <Center bg="bg.shell" minH="100dvh">
+ <Spinner color="fg.muted" size="sm" />
+ </Center>
+);
+
+export const router = createRouter({
+ defaultNotFoundComponent: () => <Navigate to="/" />,
+ defaultPendingComponent: RouterPending,
+ history: createHashHistory(),
+ routeTree: rootRoute.addChildren([workbenchRoute, loginRoute, setupRoute]),
+});
+
+declare module '@tanstack/react-router' {
+ interface Register {
+ router: typeof router;
+ }
+}
diff --git a/invokeai/frontend/webv2/src/workbench/ThemeController.tsx b/invokeai/frontend/webv2/src/workbench/ThemeController.tsx
index efde0f951b..ebd2eecd2a 100644
--- a/invokeai/frontend/webv2/src/workbench/ThemeController.tsx
+++ b/invokeai/frontend/webv2/src/workbench/ThemeController.tsx
@@ -12,6 +12,13 @@ import { useWorkbench } from './WorkbenchContext';
* no component re-render. `data-reduce-motion` is read by the global CSS that
* neutralizes transitions. Renders nothing.
*/
+/**
+ * Read by the pre-paint script in index.html. A dedicated key (rather than the
+ * workbench snapshot, which is per-user on multi-user backends) so the first
+ * paint can apply the last-used theme without knowing who is signed in.
+ */
+const THEME_HINT_STORAGE_KEY = 'invokeai:v7:webv2:theme';
+
export const ThemeController = () => {
const { state } = useWorkbench();
const { reduceMotion, themeId } = state.account.preferences;
@@ -26,6 +33,12 @@ export const ThemeController = () => {
// (scrollbars, native pickers) and any Chakra defaults we don't override.
root.classList.toggle('dark', theme.colorScheme === 'dark');
root.classList.toggle('light', theme.colorScheme === 'light');
+
+ try {
+ window.localStorage.setItem(THEME_HINT_STORAGE_KEY, theme.id);
+ } catch {
+ // Storage unavailable — the next load just paints the default theme.
+ }
}, [themeId]);
useEffect(() => {
diff --git a/invokeai/frontend/webv2/src/workbench/auth/api.ts b/invokeai/frontend/webv2/src/workbench/auth/api.ts
new file mode 100644
index 0000000000..d1a329decd
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/auth/api.ts
@@ -0,0 +1,105 @@
+import { apiFetch, apiFetchJson } from '../backend/http';
+
+/**
+ * REST surface for the backend's multi-user endpoints (`/api/v1/auth`). Field
+ * names mirror the backend DTOs verbatim; the session store and components own
+ * any reshaping.
+ */
+
+const AUTH_BASE = '/api/v1/auth';
+
+export interface UserDTO {
+ user_id: string;
+ email: string;
+ display_name: string | null;
+ is_admin: boolean;
+ is_active: boolean;
+ created_at: string;
+ updated_at: string;
+ last_login_at: string | null;
+}
+
+export interface AuthStatus {
+ setup_required: boolean;
+ multiuser_enabled: boolean;
+ strict_password_checking: boolean;
+ admin_email: string | null;
+}
+
+export interface LoginRequest {
+ email: string;
+ password: string;
+ remember_me: boolean;
+}
+
+export interface LoginResult {
+ token: string;
+ user: UserDTO;
+ expires_in: number;
+}
+
+export interface SetupRequest {
+ email: string;
+ display_name: string | null;
+ password: string;
+}
+
+export interface ProfileUpdateRequest {
+ display_name?: string;
+ current_password?: string;
+ new_password?: string;
+}
+
+export interface UserCreateRequest {
+ email: string;
+ display_name: string | null;
+ password: string;
+ is_admin: boolean;
+}
+
+export interface UserUpdateRequest {
+ display_name?: string;
+ password?: string;
+ is_admin?: boolean;
+ is_active?: boolean;
+}
+
+export const getAuthStatus = (): Promise<AuthStatus> => apiFetchJson<AuthStatus>(`${AUTH_BASE}/status`);
+
+export const login = (request: LoginRequest): Promise<LoginResult> =>
+ apiFetchJson<LoginResult>(`${AUTH_BASE}/login`, { body: JSON.stringify(request), method: 'POST' });
+
+export const logout = (): Promise<{ success: boolean }> =>
+ apiFetchJson<{ success: boolean }>(`${AUTH_BASE}/logout`, { method: 'POST' });
+
+export const getCurrentUser = (): Promise<UserDTO> => apiFetchJson<UserDTO>(`${AUTH_BASE}/me`);
+
+export const setupAdmin = (request: SetupRequest): Promise<{ success: boolean; user: UserDTO }> =>
+ apiFetchJson<{ success: boolean; user: UserDTO }>(`${AUTH_BASE}/setup`, {
+ body: JSON.stringify(request),
+ method: 'POST',
+ });
+
+export const updateCurrentUser = (request: ProfileUpdateRequest): Promise<UserDTO> =>
+ apiFetchJson<UserDTO>(`${AUTH_BASE}/me`, { body: JSON.stringify(request), method: 'PATCH' });
+
+export const listUsers = (): Promise<UserDTO[]> => apiFetchJson<UserDTO[]>(`${AUTH_BASE}/users`);
+
+export const createUser = (request: UserCreateRequest): Promise<UserDTO> =>
+ apiFetchJson<UserDTO>(`${AUTH_BASE}/users`, { body: JSON.stringify(request), method: 'POST' });
+
+export const updateUser = (userId: string, changes: UserUpdateRequest): Promise<UserDTO> =>
+ apiFetchJson<UserDTO>(`${AUTH_BASE}/users/${encodeURIComponent(userId)}`, {
+ body: JSON.stringify(changes),
+ method: 'PATCH',
+ });
+
+export const deleteUser = async (userId: string): Promise<void> => {
+ await apiFetch(`${AUTH_BASE}/users/${encodeURIComponent(userId)}`, { method: 'DELETE' });
+};
+
+export const generatePassword = async (): Promise<string> => {
+ const body = await apiFetchJson<{ password: string }>(`${AUTH_BASE}/generate-password`);
+
+ return body.password;
+};
diff --git a/invokeai/frontend/webv2/src/workbench/auth/components/AuthScreen.tsx b/invokeai/frontend/webv2/src/workbench/auth/components/AuthScreen.tsx
new file mode 100644
index 0000000000..126bf2fff3
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/auth/components/AuthScreen.tsx
@@ -0,0 +1,63 @@
+import { Alert, Box, Flex, Heading, Stack, Text } from '@chakra-ui/react';
+import type { ReactNode } from 'react';
+
+/**
+ * Centered scaffold shared by the login and first-run setup screens. These
+ * render outside the workbench shell (and its providers), so they rely only on
+ * semantic tokens.
+ */
+export const AuthScreen = ({
+ children,
+ footer,
+ subtitle,
+ title,
+}: {
+ children: ReactNode;
+ footer?: ReactNode;
+ subtitle: string;
+ title: string;
+}) => (
+ <Flex align="center" bg="bg.shell" color="fg.default" justify="center" minH="100dvh" p="6">
+ <Stack gap="6" maxW="sm" w="full">
+ <Stack align="center" gap="4">
+ <InvokeMark />
+ <Stack align="center" gap="1">
+ <Heading fontSize="lg" fontWeight="700">
+ {title}
+ </Heading>
+ <Text color="fg.muted" fontSize="sm" textAlign="center">
+ {subtitle}
+ </Text>
+ </Stack>
+ </Stack>
+ <Stack bg="bg.surface" borderColor="border.subtle" borderWidth="1px" gap="4" p="6" rounded="xl" shadow="lg">
+ {children}
+ </Stack>
+ {footer ? (
+ <Text color="fg.subtle" fontSize="xs" textAlign="center">
+ {footer}
+ </Text>
+ ) : null}
+ </Stack>
+ </Flex>
+);
+
+/** Inline alert used for form-level failures on the auth screens. */
+export const AuthFormAlert = ({ message, tone }: { message: string; tone: 'error' | 'warning' }) => (
+ <Alert.Root borderRadius="md" size="sm" status={tone}>
+ <Alert.Indicator />
+ <Alert.Title fontSize="xs">{message}</Alert.Title>
+ </Alert.Root>
+);
+
+const InvokeMark = () => (
+ <Box color="accent.invoke">
+ <svg aria-hidden="true" fill="none" height="36" viewBox="0 0 44 44" width="36">
+ <path
+ d="M29.1951 10.6667H42V2H2V10.6667H14.8049L29.1951 33.3333H42V42H2V33.3333H14.8049"
+ stroke="currentColor"
+ strokeWidth="2.8"
+ />
+ </svg>
+ </Box>
+);
diff --git a/invokeai/frontend/webv2/src/workbench/auth/components/LoginScreen.tsx b/invokeai/frontend/webv2/src/workbench/auth/components/LoginScreen.tsx
new file mode 100644
index 0000000000..4ecf829cd9
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/auth/components/LoginScreen.tsx
@@ -0,0 +1,81 @@
+import { chakra, Checkbox, Input } from '@chakra-ui/react';
+import { useNavigate } from '@tanstack/react-router';
+
+import { AuthFormAlert, AuthScreen } from './AuthScreen';
+import { PasswordInput } from './PasswordInput';
+import { getApiErrorMessage } from '../../backend/http';
+import { Button } from '../../components/ui/Button';
+import { Field } from '../../components/ui/Field';
+import { useZodForm } from '../../models/useZodForm';
+import { loginSchema } from '../schemas';
+import { loginWithCredentials, useAuthSession } from '../session';
+
+/** Sign-in screen, shown only when the backend runs in multi-user mode. */
+export const LoginScreen = () => {
+ const session = useAuthSession();
+ const navigate = useNavigate();
+ const form = useZodForm(loginSchema, { email: '', password: '', rememberMe: false });
+
+ const submit = () =>
+ form.handleSubmit(async (values) => {
+ try {
+ await loginWithCredentials(values.email, values.password, values.rememberMe);
+ } catch (error) {
+ throw new Error(getApiErrorMessage(error, 'Sign-in failed. Check your email and password.'));
+ }
+
+ await navigate({ to: '/' });
+ });
+
+ return (
+ <AuthScreen subtitle="Sign in to your workspace to continue." title="Welcome to Invoke">
+ <chakra.form
+ display="flex"
+ flexDirection="column"
+ gap="4"
+ onSubmit={(event) => {
+ event.preventDefault();
+ void submit();
+ }}
+ >
+ {session.sessionExpired ? (
+ <AuthFormAlert message="Your session expired. Sign in again to continue." tone="warning" />
+ ) : null}
+ {form.formError ? <AuthFormAlert message={form.formError} tone="error" /> : null}
+ <Field error={form.errors.email} label="Email">
+ <Input
+ aria-invalid={form.errors.email ? true : undefined}
+ autoComplete="email"
+ autoFocus
+ placeholder="[email protected]"
+ value={form.values.email}
+ onChange={(event) => form.setValue('email', event.target.value)}
+ />
+ </Field>
+ <Field error={form.errors.password} label="Password">
+ <PasswordInput
+ aria-invalid={form.errors.password ? true : undefined}
+ autoComplete="current-password"
+ placeholder="Your password"
+ value={form.values.password}
+ onChange={(event) => form.setValue('password', event.target.value)}
+ />
+ </Field>
+ <Checkbox.Root
+ checked={form.values.rememberMe}
+ size="sm"
+ onCheckedChange={(event) => form.setValue('rememberMe', event.checked === true)}
+ >
+ <Checkbox.HiddenInput />
+ <Checkbox.Control />
+ <Checkbox.Label color="fg.muted" fontWeight="400">
+ Keep me signed in for a week
+ </Checkbox.Label>
+ </Checkbox.Root>
+ <Button loading={form.isSubmitting} size="sm" type="submit" variant="solid">
+ Sign in
+ </Button>
+ </chakra.form>
+ </AuthScreen>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/auth/components/PasswordInput.tsx b/invokeai/frontend/webv2/src/workbench/auth/components/PasswordInput.tsx
new file mode 100644
index 0000000000..97de6f243f
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/auth/components/PasswordInput.tsx
@@ -0,0 +1,65 @@
+import { Box, HStack, Input, InputGroup, Text } from '@chakra-ui/react';
+import { useState, type ComponentProps } from 'react';
+import { EyeIcon, EyeOffIcon } from 'lucide-react';
+
+import { getPasswordStrength, type PasswordStrength } from '../schemas';
+import { IconButton } from '../../components/ui/Button';
+
+type InputProps = ComponentProps<typeof Input>;
+
+/** Password input with an inline visibility toggle. */
+export const PasswordInput = (props: InputProps) => {
+ const [isVisible, setIsVisible] = useState(false);
+
+ return (
+ <InputGroup
+ endElement={
+ <IconButton
+ aria-label={isVisible ? 'Hide password' : 'Show password'}
+ color="fg.muted"
+ size="2xs"
+ variant="ghost"
+ onClick={() => setIsVisible((current) => !current)}
+ >
+ {isVisible ? <EyeOffIcon /> : <EyeIcon />}
+ </IconButton>
+ }
+ >
+ <Input type={isVisible ? 'text' : 'password'} {...props} />
+ </InputGroup>
+ );
+};
+
+const STRENGTH_META: Record<PasswordStrength, { filledSegments: number; label: string; tone: string }> = {
+ moderate: { filledSegments: 2, label: 'Moderate', tone: 'orange.400' },
+ strong: { filledSegments: 3, label: 'Strong', tone: 'green.400' },
+ weak: { filledSegments: 1, label: 'Weak', tone: 'red.400' },
+};
+
+/** Three-segment strength readout; renders nothing until the user types. */
+export const PasswordStrengthMeter = ({ password }: { password: string }) => {
+ if (!password) {
+ return null;
+ }
+
+ const meta = STRENGTH_META[getPasswordStrength(password)];
+
+ return (
+ <HStack gap="2">
+ <HStack flex="1" gap="1">
+ {[0, 1, 2].map((segment) => (
+ <Box
+ key={segment}
+ bg={segment < meta.filledSegments ? meta.tone : 'border.subtle'}
+ flex="1"
+ h="1"
+ rounded="full"
+ />
+ ))}
+ </HStack>
+ <Text color={meta.tone} fontSize="2xs" fontWeight="600">
+ {meta.label}
+ </Text>
+ </HStack>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/auth/components/ProfileDialog.tsx b/invokeai/frontend/webv2/src/workbench/auth/components/ProfileDialog.tsx
new file mode 100644
index 0000000000..30c471ead5
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/auth/components/ProfileDialog.tsx
@@ -0,0 +1,178 @@
+import { Dialog, HStack, Input, Portal, Stack, Text } from '@chakra-ui/react';
+import { useMemo, useState } from 'react';
+import { WandSparklesIcon } from 'lucide-react';
+
+import { AuthFormAlert } from './AuthScreen';
+import { PasswordInput, PasswordStrengthMeter } from './PasswordInput';
+import { getApiErrorMessage } from '../../backend/http';
+import { Button, CloseButton } from '../../components/ui/Button';
+import { Field, FieldLabel } from '../../components/ui/Field';
+import { useZodForm } from '../../models/useZodForm';
+import { useNotify } from '../../useNotify';
+import { generatePassword, updateCurrentUser, type ProfileUpdateRequest, type UserDTO } from '../api';
+import { createProfileSchema, PASSWORD_RULES_HINT, type ProfileFormValues } from '../schemas';
+import { setSessionUser, useAuthSession } from '../session';
+
+/** Account settings: display name and password change for the signed-in user. */
+export const ProfileDialog = ({ isOpen, onClose, user }: { isOpen: boolean; onClose: () => void; user: UserDTO }) => (
+ <Dialog.Root
+ lazyMount
+ open={isOpen}
+ placement="center"
+ scrollBehavior="inside"
+ size="sm"
+ unmountOnExit
+ onOpenChange={(event) => {
+ if (!event.open) {
+ onClose();
+ }
+ }}
+ >
+ <Portal>
+ <Dialog.Backdrop />
+ <Dialog.Positioner>
+ <Dialog.Content bg="bg.surface" borderColor="border.subtle" borderWidth="1px" color="fg.default">
+ <Dialog.Header borderBottomWidth="1px" borderColor="border.subtle">
+ <Stack gap="0.5">
+ <Dialog.Title fontSize="md" fontWeight="700">
+ Account
+ </Dialog.Title>
+ <Text color="fg.subtle" fontSize="xs">
+ Signed in as {user.email}
+ </Text>
+ </Stack>
+ </Dialog.Header>
+ <ProfileForm user={user} onClose={onClose} />
+ <Dialog.CloseTrigger asChild>
+ <CloseButton color="fg.muted" size="sm" />
+ </Dialog.CloseTrigger>
+ </Dialog.Content>
+ </Dialog.Positioner>
+ </Portal>
+ </Dialog.Root>
+);
+
+const ProfileForm = ({ onClose, user }: { onClose: () => void; user: UserDTO }) => {
+ const session = useAuthSession();
+ const notify = useNotify();
+ const [isGenerating, setIsGenerating] = useState(false);
+ const schema = useMemo(() => createProfileSchema(session.strictPasswordChecking), [session.strictPasswordChecking]);
+ const initialValues: ProfileFormValues = useMemo(
+ () => ({ confirmPassword: '', currentPassword: '', displayName: user.display_name ?? '', newPassword: '' }),
+ [user.display_name]
+ );
+ const form = useZodForm(schema, initialValues);
+
+ const fillGeneratedPassword = async () => {
+ setIsGenerating(true);
+
+ try {
+ const password = await generatePassword();
+
+ form.setValue('newPassword', password);
+ form.setValue('confirmPassword', password);
+ notify.info('Password generated', 'Reveal it with the eye icon and store it somewhere safe.');
+ } catch (error) {
+ notify.error('Could not generate a password', getApiErrorMessage(error, 'The backend rejected the request.'));
+ } finally {
+ setIsGenerating(false);
+ }
+ };
+
+ const submit = () =>
+ form.handleSubmit(async (values) => {
+ const changes: ProfileUpdateRequest = {};
+ const displayName = values.displayName.trim();
+
+ if (displayName !== (user.display_name ?? '')) {
+ changes.display_name = displayName;
+ }
+
+ if (values.newPassword !== '') {
+ changes.current_password = values.currentPassword;
+ changes.new_password = values.newPassword;
+ }
+
+ if (Object.keys(changes).length === 0) {
+ onClose();
+ return;
+ }
+
+ try {
+ const updated = await updateCurrentUser(changes);
+
+ setSessionUser(updated);
+ } catch (error) {
+ throw new Error(getApiErrorMessage(error, 'Could not update your account.'));
+ }
+
+ notify.success('Account updated');
+ onClose();
+ });
+
+ return (
+ <>
+ <Dialog.Body>
+ <Stack gap="5" py="2">
+ {form.formError ? <AuthFormAlert message={form.formError} tone="error" /> : null}
+ <Field helpText="Shown instead of your email across the workspace." label="Display name">
+ <Input
+ autoComplete="name"
+ placeholder={user.email}
+ value={form.values.displayName}
+ onChange={(event) => form.setValue('displayName', event.target.value)}
+ />
+ </Field>
+ <Stack gap="3">
+ <HStack justify="space-between">
+ <FieldLabel>Change password</FieldLabel>
+ <Button loading={isGenerating} size="2xs" variant="outline" onClick={() => void fillGeneratedPassword()}>
+ <WandSparklesIcon />
+ Generate
+ </Button>
+ </HStack>
+ <Field error={form.errors.currentPassword} label="Current password">
+ <PasswordInput
+ aria-invalid={form.errors.currentPassword ? true : undefined}
+ autoComplete="current-password"
+ value={form.values.currentPassword}
+ onChange={(event) => form.setValue('currentPassword', event.target.value)}
+ />
+ </Field>
+ <Field
+ error={form.errors.newPassword}
+ helpText={session.strictPasswordChecking ? PASSWORD_RULES_HINT : 'Leave blank to keep your password.'}
+ label="New password"
+ >
+ <Stack gap="1.5">
+ <PasswordInput
+ aria-invalid={form.errors.newPassword ? true : undefined}
+ autoComplete="new-password"
+ value={form.values.newPassword}
+ onChange={(event) => form.setValue('newPassword', event.target.value)}
+ />
+ <PasswordStrengthMeter password={form.values.newPassword} />
+ </Stack>
+ </Field>
+ <Field error={form.errors.confirmPassword} label="Confirm new password">
+ <PasswordInput
+ aria-invalid={form.errors.confirmPassword ? true : undefined}
+ autoComplete="new-password"
+ value={form.values.confirmPassword}
+ onChange={(event) => form.setValue('confirmPassword', event.target.value)}
+ />
+ </Field>
+ </Stack>
+ </Stack>
+ </Dialog.Body>
+ <Dialog.Footer gap="2">
+ <Button size="xs" variant="ghost" onClick={onClose}>
+ Cancel
+ </Button>
+ <Button loading={form.isSubmitting} size="xs" variant="solid" onClick={() => void submit()}>
+ Save changes
+ </Button>
+ </Dialog.Footer>
+ </>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/auth/components/SessionExpiryGuard.tsx b/invokeai/frontend/webv2/src/workbench/auth/components/SessionExpiryGuard.tsx
new file mode 100644
index 0000000000..e2fa55ad47
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/auth/components/SessionExpiryGuard.tsx
@@ -0,0 +1,22 @@
+import { useNavigate } from '@tanstack/react-router';
+import { useEffect } from 'react';
+
+import { useAuthSession } from '../session';
+
+/**
+ * Watches for mid-session token rejection (a 401 on any authenticated request)
+ * and routes back to the login screen, which explains the expiry. Mounted once
+ * inside the workbench route; renders nothing.
+ */
+export const SessionExpiryGuard = () => {
+ const session = useAuthSession();
+ const navigate = useNavigate();
+
+ useEffect(() => {
+ if (session.multiuserEnabled && session.sessionExpired && session.user === null) {
+ void navigate({ to: '/login' });
+ }
+ }, [navigate, session.multiuserEnabled, session.sessionExpired, session.user]);
+
+ return null;
+};
diff --git a/invokeai/frontend/webv2/src/workbench/auth/components/SetupScreen.tsx b/invokeai/frontend/webv2/src/workbench/auth/components/SetupScreen.tsx
new file mode 100644
index 0000000000..28ee85e752
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/auth/components/SetupScreen.tsx
@@ -0,0 +1,100 @@
+import { chakra, Input, Stack } from '@chakra-ui/react';
+import { useNavigate } from '@tanstack/react-router';
+import { useMemo } from 'react';
+
+import { AuthFormAlert, AuthScreen } from './AuthScreen';
+import { PasswordInput, PasswordStrengthMeter } from './PasswordInput';
+import { getApiErrorMessage } from '../../backend/http';
+import { Button } from '../../components/ui/Button';
+import { Field } from '../../components/ui/Field';
+import { useZodForm } from '../../models/useZodForm';
+import { createSetupSchema, PASSWORD_RULES_HINT, type SetupFormValues } from '../schemas';
+import { completeAdminSetup, useAuthSession } from '../session';
+
+const INITIAL_VALUES: SetupFormValues = { confirmPassword: '', displayName: '', email: '', password: '' };
+
+/**
+ * First-run screen for multi-user mode: creates the administrator account and
+ * signs straight into it.
+ */
+export const SetupScreen = () => {
+ const session = useAuthSession();
+ const navigate = useNavigate();
+ const schema = useMemo(() => createSetupSchema(session.strictPasswordChecking), [session.strictPasswordChecking]);
+ const form = useZodForm(schema, INITIAL_VALUES);
+
+ const submit = () =>
+ form.handleSubmit(async (values) => {
+ try {
+ await completeAdminSetup(values.email, values.displayName.trim() || null, values.password);
+ } catch (error) {
+ throw new Error(getApiErrorMessage(error, 'Could not create the administrator account.'));
+ }
+
+ await navigate({ to: '/' });
+ });
+
+ return (
+ <AuthScreen
+ footer="You can add more users later from the user menu."
+ subtitle="Multi-user mode is on. Create the administrator account to get started."
+ title="Set up Invoke"
+ >
+ <chakra.form
+ display="flex"
+ flexDirection="column"
+ gap="4"
+ onSubmit={(event) => {
+ event.preventDefault();
+ void submit();
+ }}
+ >
+ {form.formError ? <AuthFormAlert message={form.formError} tone="error" /> : null}
+ <Field error={form.errors.email} label="Email">
+ <Input
+ aria-invalid={form.errors.email ? true : undefined}
+ autoComplete="email"
+ autoFocus
+ placeholder="[email protected]"
+ value={form.values.email}
+ onChange={(event) => form.setValue('email', event.target.value)}
+ />
+ </Field>
+ <Field helpText="Optional — shown instead of your email." label="Display name">
+ <Input
+ autoComplete="name"
+ placeholder="Administrator"
+ value={form.values.displayName}
+ onChange={(event) => form.setValue('displayName', event.target.value)}
+ />
+ </Field>
+ <Field
+ error={form.errors.password}
+ helpText={session.strictPasswordChecking ? PASSWORD_RULES_HINT : undefined}
+ label="Password"
+ >
+ <Stack gap="1.5">
+ <PasswordInput
+ aria-invalid={form.errors.password ? true : undefined}
+ autoComplete="new-password"
+ value={form.values.password}
+ onChange={(event) => form.setValue('password', event.target.value)}
+ />
+ <PasswordStrengthMeter password={form.values.password} />
+ </Stack>
+ </Field>
+ <Field error={form.errors.confirmPassword} label="Confirm password">
+ <PasswordInput
+ aria-invalid={form.errors.confirmPassword ? true : undefined}
+ autoComplete="new-password"
+ value={form.values.confirmPassword}
+ onChange={(event) => form.setValue('confirmPassword', event.target.value)}
+ />
+ </Field>
+ <Button loading={form.isSubmitting} size="sm" type="submit" variant="solid">
+ Create administrator account
+ </Button>
+ </chakra.form>
+ </AuthScreen>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/auth/components/UserMenu.tsx b/invokeai/frontend/webv2/src/workbench/auth/components/UserMenu.tsx
new file mode 100644
index 0000000000..1d6b7d1e2f
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/auth/components/UserMenu.tsx
@@ -0,0 +1,113 @@
+import { Avatar, Badge, Box, chakra, HStack, Icon, Menu, Portal, Stack, Text } from '@chakra-ui/react';
+import { useNavigate } from '@tanstack/react-router';
+import { useState } from 'react';
+import { ChevronDownIcon, LogOutIcon, UserRoundCogIcon, UsersIcon } from 'lucide-react';
+
+import { ProfileDialog } from './ProfileDialog';
+import { MenuContent } from '../../components/ui/Menu';
+import { useWorkbench } from '../../WorkbenchContext';
+import { logoutSession, useAuthSession } from '../session';
+
+/**
+ * Signed-in account cluster for the top bar: avatar trigger, account dialog,
+ * the admin users view, and sign-out. Renders nothing in single-user mode, so
+ * the shell needs no awareness of whether multi-user is enabled.
+ */
+export const UserMenu = () => {
+ const session = useAuthSession();
+ const { activeProject, dispatch } = useWorkbench();
+ const navigate = useNavigate();
+ const [isProfileOpen, setIsProfileOpen] = useState(false);
+
+ if (!session.multiuserEnabled || session.user === null) {
+ return null;
+ }
+
+ const user = session.user;
+ const label = user.display_name?.trim() || user.email;
+
+ const openUserManagement = () => {
+ const centerRegion = activeProject.widgetRegions.center;
+
+ // Enabling an absent center widget also makes it active.
+ if (centerRegion.enabledWidgetIds.includes('users')) {
+ dispatch({ region: 'center', type: 'selectRegionWidget', widgetId: 'users' });
+ } else {
+ dispatch({ region: 'center', type: 'toggleRegionWidget', widgetId: 'users' });
+ }
+ };
+
+ const signOut = async () => {
+ await logoutSession();
+ await navigate({ to: '/login' });
+ };
+
+ return (
+ <>
+ <Menu.Root positioning={{ placement: 'bottom-end' }}>
+ <Menu.Trigger asChild>
+ <chakra.button
+ alignItems="center"
+ color="fg.default"
+ display="flex"
+ flexShrink={0}
+ gap="1.5"
+ px="1.5"
+ py="1"
+ rounded="md"
+ type="button"
+ _hover={{ bg: 'bg.surface' }}
+ >
+ <Avatar.Root bg="accent.widget" color="fg.default" size="2xs">
+ <Avatar.Fallback fontSize="2xs" name={label} />
+ </Avatar.Root>
+ <Text fontSize="xs" fontWeight="600">
+ {label}
+ </Text>
+ <Icon as={ChevronDownIcon} boxSize="3" color="fg.muted" />
+ </chakra.button>
+ </Menu.Trigger>
+ <Portal>
+ <Menu.Positioner>
+ <MenuContent minW="56">
+ <Box px="3" py="2">
+ <HStack justify="space-between">
+ <Stack gap="0">
+ <Text fontSize="xs" fontWeight="600">
+ {label}
+ </Text>
+ <Text color="fg.muted" fontSize="2xs">
+ {user.email}
+ </Text>
+ </Stack>
+ {user.is_admin ? (
+ <Badge colorPalette="purple" fontSize="2xs" variant="surface">
+ Admin
+ </Badge>
+ ) : null}
+ </HStack>
+ </Box>
+ <Menu.Separator />
+ <Menu.Item value="account" onClick={() => setIsProfileOpen(true)}>
+ <Icon as={UserRoundCogIcon} boxSize="3.5" />
+ Account settings
+ </Menu.Item>
+ {user.is_admin ? (
+ <Menu.Item value="users" onClick={openUserManagement}>
+ <Icon as={UsersIcon} boxSize="3.5" />
+ Manage users
+ </Menu.Item>
+ ) : null}
+ <Menu.Separator />
+ <Menu.Item value="sign-out" onClick={() => void signOut()}>
+ <Icon as={LogOutIcon} boxSize="3.5" />
+ Sign out
+ </Menu.Item>
+ </MenuContent>
+ </Menu.Positioner>
+ </Portal>
+ </Menu.Root>
+ <ProfileDialog isOpen={isProfileOpen} user={user} onClose={() => setIsProfileOpen(false)} />
+ </>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/auth/schemas.test.ts b/invokeai/frontend/webv2/src/workbench/auth/schemas.test.ts
new file mode 100644
index 0000000000..e73a89ed31
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/auth/schemas.test.ts
@@ -0,0 +1,127 @@
+import { describe, expect, it } from 'vitest';
+
+import { ApiError, getApiErrorMessage } from '../backend/http';
+import {
+ createProfileSchema,
+ createSetupSchema,
+ createUserFormSchema,
+ getPasswordStrength,
+ loginSchema,
+} from './schemas';
+
+describe('password strength', () => {
+ it('mirrors the backend rules', () => {
+ expect(getPasswordStrength('short')).toBe('weak');
+ expect(getPasswordStrength('alllowercase')).toBe('moderate');
+ expect(getPasswordStrength('NoDigitsHere')).toBe('moderate');
+ expect(getPasswordStrength('Str0ngEnough')).toBe('strong');
+ });
+});
+
+describe('login schema', () => {
+ it('requires a valid email and a password', () => {
+ expect(loginSchema.safeParse({ email: 'not-an-email', password: 'x', rememberMe: false }).success).toBe(false);
+ expect(loginSchema.safeParse({ email: '[email protected]', password: '', rememberMe: false }).success).toBe(false);
+ expect(loginSchema.safeParse({ email: '[email protected]', password: 'pw', rememberMe: true }).success).toBe(true);
+ });
+
+ it('accepts special-use domains, matching the backend', () => {
+ expect(loginSchema.safeParse({ email: 'admin@localhost', password: 'pw', rememberMe: false }).success).toBe(true);
+ expect(loginSchema.safeParse({ email: '[email protected]', password: 'pw', rememberMe: false }).success).toBe(true);
+ });
+});
+
+describe('setup schema', () => {
+ it('enforces strength only in strict mode', () => {
+ const base = { confirmPassword: 'simple', displayName: '', email: '[email protected]', password: 'simple' };
+
+ expect(createSetupSchema(false).safeParse(base).success).toBe(true);
+ expect(createSetupSchema(true).safeParse(base).success).toBe(false);
+ expect(
+ createSetupSchema(true).safeParse({ ...base, confirmPassword: 'Str0ngEnough', password: 'Str0ngEnough' }).success
+ ).toBe(true);
+ });
+
+ it('rejects mismatched confirmation', () => {
+ const result = createSetupSchema(false).safeParse({
+ confirmPassword: 'other',
+ displayName: '',
+ email: '[email protected]',
+ password: 'simple',
+ });
+
+ expect(result.success).toBe(false);
+ });
+});
+
+describe('profile schema', () => {
+ it('treats an empty new password as no change', () => {
+ const result = createProfileSchema(true).safeParse({
+ confirmPassword: '',
+ currentPassword: '',
+ displayName: 'Me',
+ newPassword: '',
+ });
+
+ expect(result.success).toBe(true);
+ });
+
+ it('requires the current password and confirmation when changing', () => {
+ const schema = createProfileSchema(false);
+
+ expect(
+ schema.safeParse({ confirmPassword: 'newpw', currentPassword: '', displayName: '', newPassword: 'newpw' }).success
+ ).toBe(false);
+ expect(
+ schema.safeParse({ confirmPassword: 'nope', currentPassword: 'old', displayName: '', newPassword: 'newpw' })
+ .success
+ ).toBe(false);
+ expect(
+ schema.safeParse({ confirmPassword: 'newpw', currentPassword: 'old', displayName: '', newPassword: 'newpw' })
+ .success
+ ).toBe(true);
+ });
+});
+
+describe('user form schema', () => {
+ it('requires email and password when creating', () => {
+ const schema = createUserFormSchema(true, true);
+
+ expect(schema.safeParse({ displayName: '', email: '', isAdmin: false, password: 'Str0ngEnough' }).success).toBe(
+ false
+ );
+ expect(schema.safeParse({ displayName: '', email: '[email protected]', isAdmin: false, password: 'weak' }).success).toBe(
+ false
+ );
+ expect(
+ schema.safeParse({ displayName: '', email: '[email protected]', isAdmin: true, password: 'Str0ngEnough' }).success
+ ).toBe(true);
+ });
+
+ it('allows an empty password when editing', () => {
+ const schema = createUserFormSchema(true, false);
+
+ expect(schema.safeParse({ displayName: 'New Name', email: '', isAdmin: false, password: '' }).success).toBe(true);
+ expect(schema.safeParse({ displayName: '', email: '', isAdmin: false, password: 'weak' }).success).toBe(false);
+ });
+});
+
+describe('getApiErrorMessage', () => {
+ it('unwraps FastAPI detail strings', () => {
+ expect(getApiErrorMessage(new ApiError('{"detail":"Incorrect email or password"}', 401), 'fallback')).toBe(
+ 'Incorrect email or password'
+ );
+ });
+
+ it('unwraps the first validation issue', () => {
+ const body = JSON.stringify({ detail: [{ loc: ['body', 'email'], msg: 'value is not a valid email address' }] });
+
+ expect(getApiErrorMessage(new ApiError(body, 422), 'fallback')).toBe('value is not a valid email address');
+ });
+
+ it('falls back for non-JSON bodies and unknown errors', () => {
+ expect(getApiErrorMessage(new ApiError('', 500), 'fallback')).toBe('fallback');
+ expect(getApiErrorMessage(new ApiError('plain text', 500), 'fallback')).toBe('plain text');
+ expect(getApiErrorMessage('nope', 'fallback')).toBe('fallback');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/auth/schemas.ts b/invokeai/frontend/webv2/src/workbench/auth/schemas.ts
new file mode 100644
index 0000000000..d1ee8bc4ed
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/auth/schemas.ts
@@ -0,0 +1,107 @@
+import { z } from 'zod';
+
+/**
+ * Form schemas for the auth surfaces. Password rules mirror the backend's
+ * `validate_password_strength`: 8+ characters with an uppercase letter, a
+ * lowercase letter, and a digit. When strict checking is off the backend
+ * accepts any non-empty password, so the schemas relax to match.
+ */
+
+export type PasswordStrength = 'weak' | 'moderate' | 'strong';
+
+export const getPasswordStrength = (password: string): PasswordStrength => {
+ if (password.length < 8) {
+ return 'weak';
+ }
+
+ const hasUpper = /[A-Z]/.test(password);
+ const hasLower = /[a-z]/.test(password);
+ const hasDigit = /\d/.test(password);
+
+ return hasUpper && hasLower && hasDigit ? 'strong' : 'moderate';
+};
+
+export const PASSWORD_RULES_HINT = 'At least 8 characters, with an uppercase letter, a lowercase letter, and a digit.';
+
+/**
+ * Deliberately lenient: the backend accepts special-use domains (`@localhost`,
+ * `.local`) for development setups, so the form only catches obvious mistakes
+ * and leaves real validation to the server.
+ */
+const emailSchema = z
+ .string()
+ .trim()
+ .refine((value) => {
+ const atIndex = value.indexOf('@');
+
+ return atIndex > 0 && atIndex < value.length - 1;
+ }, 'Enter a valid email address.');
+
+const createPasswordSchema = (strict: boolean) =>
+ strict
+ ? z
+ .string()
+ .min(8, 'Password must be at least 8 characters long.')
+ .refine((value) => getPasswordStrength(value) === 'strong', PASSWORD_RULES_HINT)
+ : z.string().min(1, 'Enter a password.');
+
+/** Optional-password variant: empty string means "leave unchanged". */
+const createOptionalPasswordSchema = (strict: boolean) =>
+ z.string().refine((value) => value === '' || !strict || getPasswordStrength(value) === 'strong', PASSWORD_RULES_HINT);
+
+export const loginSchema = z.object({
+ email: emailSchema,
+ password: z.string().min(1, 'Enter your password.'),
+ rememberMe: z.boolean(),
+});
+
+export type LoginFormValues = z.infer<typeof loginSchema>;
+
+export const createSetupSchema = (strict: boolean) =>
+ z
+ .object({
+ confirmPassword: z.string(),
+ displayName: z.string(),
+ email: emailSchema,
+ password: createPasswordSchema(strict),
+ })
+ .refine((values) => values.password === values.confirmPassword, {
+ message: 'Passwords do not match.',
+ path: ['confirmPassword'],
+ });
+
+export type SetupFormValues = z.infer<ReturnType<typeof createSetupSchema>>;
+
+export const createProfileSchema = (strict: boolean) =>
+ z
+ .object({
+ confirmPassword: z.string(),
+ currentPassword: z.string(),
+ displayName: z.string(),
+ newPassword: createOptionalPasswordSchema(strict),
+ })
+ .refine((values) => values.newPassword === '' || values.currentPassword !== '', {
+ message: 'Enter your current password to set a new one.',
+ path: ['currentPassword'],
+ })
+ .refine((values) => values.newPassword === '' || values.newPassword === values.confirmPassword, {
+ message: 'Passwords do not match.',
+ path: ['confirmPassword'],
+ });
+
+export type ProfileFormValues = z.infer<ReturnType<typeof createProfileSchema>>;
+
+/**
+ * One shape serves both admin user-form modes. Creating requires email and
+ * password; editing ignores the email field and treats an empty password as
+ * "leave unchanged".
+ */
+export const createUserFormSchema = (strict: boolean, requireCredentials: boolean) =>
+ z.object({
+ displayName: z.string(),
+ email: requireCredentials ? emailSchema : z.string(),
+ isAdmin: z.boolean(),
+ password: requireCredentials ? createPasswordSchema(strict) : createOptionalPasswordSchema(strict),
+ });
+
+export type UserFormValues = z.infer<ReturnType<typeof createUserFormSchema>>;
diff --git a/invokeai/frontend/webv2/src/workbench/auth/session.ts b/invokeai/frontend/webv2/src/workbench/auth/session.ts
new file mode 100644
index 0000000000..0b41c656be
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/auth/session.ts
@@ -0,0 +1,165 @@
+import { ApiError, clearAuthToken, getAuthToken, setAuthToken, setUnauthorizedHandler } from '../backend/http';
+import { createExternalStore } from '../externalStore';
+import { getAuthStatus, getCurrentUser, login, logout, setupAdmin, type AuthStatus, type UserDTO } from './api';
+
+/**
+ * Session-lived auth state shared by the router guards and shell chrome. When
+ * multi-user is disabled on the backend the snapshot stays at its defaults
+ * (`multiuserEnabled: false`, `user: null`) and the entire auth surface — login
+ * screen, user menu, expiry handling — stays dormant.
+ */
+export interface AuthSession {
+ /** 'unknown' until the first `/auth/status` round-trip resolves. */
+ phase: 'unknown' | 'ready';
+ multiuserEnabled: boolean;
+ setupRequired: boolean;
+ strictPasswordChecking: boolean;
+ user: UserDTO | null;
+ /** Set when a stored token is rejected mid-session; shown on the login screen. */
+ sessionExpired: boolean;
+}
+
+const store = createExternalStore<AuthSession>({
+ multiuserEnabled: false,
+ phase: 'unknown',
+ sessionExpired: false,
+ setupRequired: false,
+ strictPasswordChecking: false,
+ user: null,
+});
+
+export const useAuthSession = (): AuthSession => store.useSnapshot();
+
+/**
+ * Imperative read for non-reactive callers (e.g. the widget registry). Safe
+ * inside the workbench: the route guard resolves the session before mounting,
+ * and a user change remounts the whole workbench route.
+ */
+export const getAuthSession = (): AuthSession => store.getSnapshot();
+
+/**
+ * Sticky across sign-out: a debounced autosave can still fire during the
+ * logout transition, and it must land in the bucket of the user whose data
+ * was loaded — never the shared single-user bucket.
+ */
+let activeUserScope = '';
+
+const setActiveUserScope = (user: UserDTO | null): void => {
+ if (user !== null) {
+ activeUserScope = `:user:${user.user_id}`;
+ }
+};
+
+/**
+ * Suffix for localStorage keys holding user-owned state (projects, account
+ * preferences, personal API keys — see the spec's State Ownership section).
+ * Empty in single-user mode, so existing keys keep working unchanged.
+ */
+export const getUserStorageScope = (): string => (store.getSnapshot().multiuserEnabled ? activeUserScope : '');
+
+const fetchAuthStatus = async (): Promise<AuthStatus> => {
+ try {
+ return await getAuthStatus();
+ } catch {
+ // Backend unreachable: let the shell mount in single-user shape. The
+ // connection banner reports the outage, and a 401 once the backend returns
+ // in multi-user mode routes through the session-expiry path to login.
+ return { admin_email: null, multiuser_enabled: false, setup_required: false, strict_password_checking: false };
+ }
+};
+
+const resolveSession = async (): Promise<AuthSession> => {
+ const status = await fetchAuthStatus();
+ let user: UserDTO | null = null;
+
+ if (status.multiuser_enabled && !status.setup_required && getAuthToken()) {
+ try {
+ user = await getCurrentUser();
+ } catch (error) {
+ if (error instanceof ApiError && (error.status === 401 || error.status === 403)) {
+ clearAuthToken();
+ }
+ // Any other failure leaves `user` null; the route guard lands on login.
+ }
+ }
+
+ setActiveUserScope(user);
+ store.patchSnapshot({
+ multiuserEnabled: status.multiuser_enabled,
+ phase: 'ready',
+ setupRequired: status.setup_required,
+ strictPasswordChecking: status.strict_password_checking,
+ user,
+ });
+
+ return store.getSnapshot();
+};
+
+let pendingResolve: Promise<AuthSession> | null = null;
+
+/** Resolve the session exactly once per app load; later calls reuse the snapshot. */
+export const ensureAuthSession = (): Promise<AuthSession> => {
+ const current = store.getSnapshot();
+
+ if (current.phase === 'ready') {
+ return Promise.resolve(current);
+ }
+
+ pendingResolve ??= resolveSession().finally(() => {
+ pendingResolve = null;
+ });
+
+ return pendingResolve;
+};
+
+export const loginWithCredentials = async (email: string, password: string, rememberMe: boolean): Promise<void> => {
+ // A stale token must not ride along on the login request itself.
+ clearAuthToken();
+
+ const result = await login({ email, password, remember_me: rememberMe });
+
+ setAuthToken(result.token);
+ setActiveUserScope(result.user);
+ store.patchSnapshot({ sessionExpired: false, user: result.user });
+};
+
+export const logoutSession = async (): Promise<void> => {
+ try {
+ await logout();
+ } catch {
+ // Tokens are stateless on the backend; local sign-out always wins.
+ }
+
+ clearAuthToken();
+ store.patchSnapshot({ sessionExpired: false, user: null });
+};
+
+/** Create the initial admin account, then sign straight in with it. */
+export const completeAdminSetup = async (
+ email: string,
+ displayName: string | null,
+ password: string
+): Promise<void> => {
+ await setupAdmin({ display_name: displayName, email, password });
+ store.patchSnapshot({ setupRequired: false });
+ await loginWithCredentials(email, password, false);
+};
+
+/** Reflect a profile edit (display name, password) into the session snapshot. */
+export const setSessionUser = (user: UserDTO): void => {
+ store.patchSnapshot({ user });
+};
+
+// A 401 on any authenticated request means the stored token expired or was
+// revoked. Only react while an authenticated multi-user session is live, so
+// failed login attempts and single-user mode never trip it.
+setUnauthorizedHandler(() => {
+ const session = store.getSnapshot();
+
+ if (!session.multiuserEnabled || session.user === null) {
+ return;
+ }
+
+ clearAuthToken();
+ store.patchSnapshot({ sessionExpired: true, user: null });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/backend/http.ts b/invokeai/frontend/webv2/src/workbench/backend/http.ts
index a3eee45c7a..58a75737d2 100644
--- a/invokeai/frontend/webv2/src/workbench/backend/http.ts
+++ b/invokeai/frontend/webv2/src/workbench/backend/http.ts
@@ -16,6 +16,33 @@ export const getAuthToken = (): string | null => {
}
};
+export const setAuthToken = (token: string): void => {
+ try {
+ window.localStorage.setItem(AUTH_TOKEN_STORAGE_KEY, token);
+ } catch {
+ // Storage unavailable (private mode, quota): the session lasts until reload.
+ }
+};
+
+export const clearAuthToken = (): void => {
+ try {
+ window.localStorage.removeItem(AUTH_TOKEN_STORAGE_KEY);
+ } catch {
+ // Nothing to clear if storage is unavailable.
+ }
+};
+
+/**
+ * Called when an authenticated request comes back 401 — the stored token is no
+ * longer valid. The auth session store registers itself here so the HTTP layer
+ * stays unaware of session semantics.
+ */
+let unauthorizedHandler: (() => void) | null = null;
+
+export const setUnauthorizedHandler = (handler: (() => void) | null): void => {
+ unauthorizedHandler = handler;
+};
+
export const getBackendSocketUrl = (): string => {
if (!API_BASE_URL.trim()) {
return window.location.origin;
@@ -66,8 +93,47 @@ export const apiFetchRaw = (path: string, init?: RequestInit): Promise<Response>
return fetch(buildApiUrl(path), { ...init, headers });
};
-export const apiFetch = async (path: string, init?: RequestInit): Promise<Response> =>
- assertOk(await apiFetchRaw(path, init));
+export const apiFetch = async (path: string, init?: RequestInit): Promise<Response> => {
+ const hadToken = getAuthToken() !== null;
+ const response = await apiFetchRaw(path, init);
+
+ if (response.status === 401 && hadToken) {
+ unauthorizedHandler?.();
+ }
+
+ return assertOk(response);
+};
+
+/**
+ * Backend errors arrive as FastAPI JSON (`{"detail": "..."}`); `ApiError`
+ * carries the raw body. This unwraps `detail` into a human-readable message.
+ */
+export const getApiErrorMessage = (error: unknown, fallback: string): string => {
+ if (error instanceof ApiError) {
+ try {
+ const parsed = JSON.parse(error.message) as { detail?: unknown };
+
+ if (typeof parsed.detail === 'string' && parsed.detail) {
+ return parsed.detail;
+ }
+
+ // Validation errors come as a list of issues; surface the first one.
+ if (Array.isArray(parsed.detail)) {
+ const first = parsed.detail[0] as { msg?: unknown } | undefined;
+
+ if (first && typeof first.msg === 'string') {
+ return first.msg;
+ }
+ }
+ } catch {
+ // Not JSON — fall through to the raw message.
+ }
+
+ return error.message || fallback;
+ }
+
+ return error instanceof Error && error.message ? error.message : fallback;
+};
export const apiFetchJson = async <T>(path: string, init?: RequestInit): Promise<T> => {
const headers = new Headers(init?.headers);
diff --git a/invokeai/frontend/webv2/src/workbench/components/TopBar.tsx b/invokeai/frontend/webv2/src/workbench/components/TopBar.tsx
index a6a86d52cb..50708d356b 100644
--- a/invokeai/frontend/webv2/src/workbench/components/TopBar.tsx
+++ b/invokeai/frontend/webv2/src/workbench/components/TopBar.tsx
@@ -1,11 +1,12 @@
-import { Badge, Box, Flex, Group, HStack, Icon, Menu, NumberInput, Portal, Text } from '@chakra-ui/react';
-import { BoxIcon, ChevronDownIcon, CircleUserIcon, ListOrderedIcon, PauseIcon, PlayIcon, XIcon } from 'lucide-react';
+import { Badge, Box, Flex, Group, Icon, Menu, NumberInput, Portal } from '@chakra-ui/react';
+import { ChevronDownIcon, ListOrderedIcon, PauseIcon, PlayIcon, XIcon } from 'lucide-react';
import { InvokeControl } from './InvokeControl';
import { LayoutPresetMenu } from './LayoutPresetMenu';
import { ProjectTabs } from './ProjectTabs';
import { SettingsButton } from './SettingsDialog';
import { IconButton } from './ui/Button';
+import { UserMenu } from '../auth/components/UserMenu';
import { useWorkbench } from '../WorkbenchContext';
import { DEFAULT_THEME_ID, THEMES_BY_ID } from '../../theme/themes';
import { Tooltip } from './ui/Tooltip';
@@ -32,24 +33,8 @@ export const TopBar = () => (
<Box w="1px" h="5" bg="border.subtle" mx="1" flexShrink={0} />
<ProjectTabs />
<LayoutPresetMenu />
- <HStack gap="0.5" flexShrink={0}>
- <IconButton
- aria-label="Model manager"
- color="fg.muted"
- size="sm"
- variant="ghost"
- _hover={{ color: 'fg.default' }}
- >
- <BoxIcon />
- </IconButton>
- <SettingsButton />
- </HStack>
- <HStack as="button" gap="1.5" color="fg.default" flexShrink={0} px="1">
- <Icon as={CircleUserIcon} boxSize="4" />
- <Text fontSize="xs" fontWeight="600">
- Josh
- </Text>
- </HStack>
+ <SettingsButton />
+ <UserMenu />
</Flex>
);
diff --git a/invokeai/frontend/webv2/src/workbench/gallery/api.ts b/invokeai/frontend/webv2/src/workbench/gallery/api.ts
index c067916b84..e32ced946b 100644
--- a/invokeai/frontend/webv2/src/workbench/gallery/api.ts
+++ b/invokeai/frontend/webv2/src/workbench/gallery/api.ts
@@ -14,6 +14,8 @@ export interface BackendBoardDTO {
asset_count: number;
archived: boolean;
cover_image_name?: string | null;
+ /** Board owner's display name; populated only for admins on multi-user backends. */
+ owner_username?: string | null;
}
/**
@@ -32,6 +34,8 @@ export interface GalleryBoard {
archived: boolean;
coverImageName?: string | null;
coverThumbnailUrl?: string;
+ /** Owner display name when the backend exposes it (admins in multi-user mode). */
+ ownerName?: string | null;
}
const DATE_BOARD_ID_PREFIX = 'by_date:';
@@ -102,6 +106,7 @@ const mapBoard = (board: BackendBoardDTO): GalleryBoard => ({
imageCount: board.image_count,
kind: 'board',
name: board.board_name,
+ ownerName: board.owner_username ?? null,
});
const getGalleryTotal = async ({ boardId, categories }: { boardId: string; categories: string[] }): Promise<number> => {
diff --git a/invokeai/frontend/webv2/src/workbench/iconResolver.tsx b/invokeai/frontend/webv2/src/workbench/iconResolver.tsx
index 68e4d27081..766448becc 100644
--- a/invokeai/frontend/webv2/src/workbench/iconResolver.tsx
+++ b/invokeai/frontend/webv2/src/workbench/iconResolver.tsx
@@ -20,6 +20,7 @@ const iconImporters = {
'lucide-react:plug-zap': () => import('lucide-react/dist/esm/icons/plug-zap.mjs'),
'lucide-react:sliders-horizontal': () => import('lucide-react/dist/esm/icons/sliders-horizontal.mjs'),
'lucide-react:undo-2': () => import('lucide-react/dist/esm/icons/undo-2.mjs'),
+ 'lucide-react:users': () => import('lucide-react/dist/esm/icons/users.mjs'),
'lucide-react:wand-sparkles': () => import('lucide-react/dist/esm/icons/wand-sparkles.mjs'),
'lucide-react:workflow': () => import('lucide-react/dist/esm/icons/workflow.mjs'),
} satisfies Partial<Record<WidgetIconId, IconImporter>>;
diff --git a/invokeai/frontend/webv2/src/workbench/models/apiKeys.ts b/invokeai/frontend/webv2/src/workbench/models/apiKeys.ts
index 546d0c3211..41d107407f 100644
--- a/invokeai/frontend/webv2/src/workbench/models/apiKeys.ts
+++ b/invokeai/frontend/webv2/src/workbench/models/apiKeys.ts
@@ -1,15 +1,20 @@
+import { getUserStorageScope } from '../auth/session';
+
/**
* Client-side API key storage for remote model sources. The HuggingFace token
* lives on the backend (`/api/v2/models/hf_login`); the Civitai key has no
* backend home, so it is kept in this browser's localStorage and passed as the
- * `access_token` query param when installing from a matching URL.
+ * `access_token` query param when installing from a matching URL. The key is
+ * personal, so it is scoped per signed-in user on multi-user backends.
*/
-const CIVITAI_KEY_STORAGE_KEY = 'invokeai-webv2-civitai-api-key';
+const CIVITAI_KEY_BASE_STORAGE_KEY = 'invokeai-webv2-civitai-api-key';
+
+const getStorageKey = (): string => `${CIVITAI_KEY_BASE_STORAGE_KEY}${getUserStorageScope()}`;
export const getCivitaiApiKey = (): string | null => {
try {
- return window.localStorage.getItem(CIVITAI_KEY_STORAGE_KEY);
+ return window.localStorage.getItem(getStorageKey());
} catch {
return null;
}
@@ -17,7 +22,7 @@ export const getCivitaiApiKey = (): string | null => {
export const setCivitaiApiKey = (key: string): void => {
try {
- window.localStorage.setItem(CIVITAI_KEY_STORAGE_KEY, key);
+ window.localStorage.setItem(getStorageKey(), key);
} catch {
// Storage unavailable (private mode/quota) — the key just is not persisted.
}
@@ -25,7 +30,7 @@ export const setCivitaiApiKey = (key: string): void => {
export const clearCivitaiApiKey = (): void => {
try {
- window.localStorage.removeItem(CIVITAI_KEY_STORAGE_KEY);
+ window.localStorage.removeItem(getStorageKey());
} catch {
// Ignore: nothing to clear if storage is unavailable.
}
diff --git a/invokeai/frontend/webv2/src/workbench/persistence.ts b/invokeai/frontend/webv2/src/workbench/persistence.ts
index 37c60722da..241df3a8e7 100644
--- a/invokeai/frontend/webv2/src/workbench/persistence.ts
+++ b/invokeai/frontend/webv2/src/workbench/persistence.ts
@@ -1,8 +1,17 @@
+import { getUserStorageScope } from './auth/session';
import type { Project, WorkbenchPersistenceSnapshot, WorkbenchState } from './types';
-const STORAGE_KEY = 'invokeai:v7:webv2:workbench';
+const BASE_STORAGE_KEY = 'invokeai:v7:webv2:workbench';
const WORKBENCH_SCHEMA_VERSION = 1;
+/**
+ * Projects, account preferences, and active layout are account-owned on
+ * multi-user backends (spec: State Ownership), so each signed-in user gets
+ * their own storage bucket on this browser. Single-user mode keeps the
+ * unscoped key, so existing data is untouched.
+ */
+const getStorageKey = (): string => `${BASE_STORAGE_KEY}${getUserStorageScope()}`;
+
export interface WorkbenchPersistenceService {
loadWorkbench(): Promise<WorkbenchPersistenceSnapshot | null>;
saveWorkbench(state: WorkbenchState): Promise<WorkbenchPersistenceSnapshot>;
@@ -58,7 +67,7 @@ export const localStorageWorkbenchPersistence: WorkbenchPersistenceService = {
return Promise.resolve();
}
- window.localStorage.removeItem(STORAGE_KEY);
+ window.localStorage.removeItem(getStorageKey());
return Promise.resolve();
},
@@ -67,7 +76,7 @@ export const localStorageWorkbenchPersistence: WorkbenchPersistenceService = {
return Promise.resolve(null);
}
- const value = window.localStorage.getItem(STORAGE_KEY);
+ const value = window.localStorage.getItem(getStorageKey());
if (!value) {
return Promise.resolve(null);
@@ -82,7 +91,7 @@ export const localStorageWorkbenchPersistence: WorkbenchPersistenceService = {
return Promise.resolve(snapshot);
}
- window.localStorage.setItem(STORAGE_KEY, JSON.stringify(snapshot));
+ window.localStorage.setItem(getStorageKey(), JSON.stringify(snapshot));
return Promise.resolve(snapshot);
},
diff --git a/invokeai/frontend/webv2/src/workbench/types.ts b/invokeai/frontend/webv2/src/workbench/types.ts
index 9b21e99d9a..9d2d97c99d 100644
--- a/invokeai/frontend/webv2/src/workbench/types.ts
+++ b/invokeai/frontend/webv2/src/workbench/types.ts
@@ -20,6 +20,7 @@ export type WidgetId =
| 'preview'
| 'queue'
| 'server-status'
+ | 'users'
| 'version-status'
| 'workflow';
@@ -129,6 +130,8 @@ export interface WidgetManifest {
icon: WidgetIconId;
bottomPanel?: 'expandable' | 'tooltip';
centerPlacement?: 'toolbar' | 'view';
+ /** Only offered while an admin is signed in to a multi-user backend. */
+ requiresAdmin?: boolean;
chrome?: {
header?: 'hidden' | 'visible';
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgetRegistry.ts b/invokeai/frontend/webv2/src/workbench/widgetRegistry.ts
index 38c73d8cb2..ee08b36697 100644
--- a/invokeai/frontend/webv2/src/workbench/widgetRegistry.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgetRegistry.ts
@@ -1,3 +1,4 @@
+import { getAuthSession } from './auth/session';
import { isSupportedIconId } from './iconResolver';
import type { RegisteredWidget, WidgetFailure, WidgetId, WidgetManifest, WorkbenchRegion } from './types';
import { autosaveStatusWidgetManifest } from './widgets/autosave-status';
@@ -13,6 +14,7 @@ import { notificationsWidgetManifest } from './widgets/notifications';
import { previewWidgetManifest } from './widgets/preview';
import { queueWidgetManifest } from './widgets/queue';
import { serverStatusWidgetManifest } from './widgets/server-status';
+import { usersWidgetManifest } from './widgets/users';
import { versionStatusWidgetManifest } from './widgets/version-status';
import { workflowWidgetManifest } from './widgets/workflow';
@@ -32,6 +34,7 @@ const firstPartyWidgetManifests: WidgetManifest[] = [
historyControlsWidgetManifest,
layoutActionsWidgetManifest,
versionStatusWidgetManifest,
+ usersWidgetManifest,
];
const createFailure = (widgetId: WidgetId, error: unknown): WidgetFailure => ({
@@ -73,8 +76,26 @@ export const registerFirstPartyWidgets = (): RegisteredWidget[] =>
export const registeredWidgets = registerFirstPartyWidgets();
+/**
+ * Admin-only widgets are offered only while an admin is signed in to a
+ * multi-user backend. The imperative session read is safe here: the route
+ * guard resolves the session before the workbench mounts, and a user change
+ * remounts the workbench route.
+ */
+const isWidgetAvailable = (widget: RegisteredWidget): boolean => {
+ if (!widget.manifest.requiresAdmin) {
+ return true;
+ }
+
+ const session = getAuthSession();
+
+ return session.multiuserEnabled && session.user?.is_admin === true;
+};
+
export const getWidgetsForRegion = (region: WorkbenchRegion): RegisteredWidget[] =>
- registeredWidgets.filter((widget) => widget.status !== 'hidden' && widget.manifest.regions.includes(region));
+ registeredWidgets.filter(
+ (widget) => widget.status !== 'hidden' && widget.manifest.regions.includes(region) && isWidgetAvailable(widget)
+ );
export const getWidgetById = (widgetId: WidgetId): RegisteredWidget | undefined =>
registeredWidgets.find((widget) => widget.manifest.id === widgetId);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryBoardSelect.tsx b/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryBoardSelect.tsx
index df858cdd0a..2102d7317a 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryBoardSelect.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryBoardSelect.tsx
@@ -361,7 +361,7 @@ const BoardRow = ({
: undefined
}
>
- <BoardOptionContent badge={badge} board={board} isSelected={isSelected} />
+ <BoardOptionContent badge={badge} board={board} isSelected={isSelected} showOwner />
{onOpenMenu && (
<IconButton
aria-label={`Board actions for ${board.name}`}
@@ -392,19 +392,29 @@ const BoardOptionContent = ({
badge,
board,
isSelected,
+ showOwner = false,
}: {
badge?: 'Project' | 'Archived';
board: GalleryBoard;
isSelected: boolean;
+ /** Render the owner line (admins on multi-user backends); off in the compact trigger. */
+ showOwner?: boolean;
}) => {
const counts = getBoardCounts(board);
return (
<HStack gap="2" minW="0" w="full">
<BoardCover board={board} />
- <Text flex="1" fontSize="xs" fontWeight={isSelected ? '700' : '500'} minW="0" truncate>
- {board.name}
- </Text>
+ <Stack flex="1" gap="1" minW="0">
+ <Text fontSize="xs" fontWeight={isSelected ? '700' : '500'} minW="0" lineHeight={1} truncate>
+ {board.name}
+ </Text>
+ {showOwner && board.ownerName ? (
+ <Text color="fg.subtle" fontSize="2xs" minW="0" lineHeight={1} truncate>
+ {board.ownerName}
+ </Text>
+ ) : null}
+ </Stack>
{badge && (
<Badge colorPalette={badge === 'Project' ? 'blue' : 'gray'} flexShrink={0} size="xs" variant="subtle">
{badge}
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/users/UserFormDialog.tsx b/invokeai/frontend/webv2/src/workbench/widgets/users/UserFormDialog.tsx
new file mode 100644
index 0000000000..76144e1660
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/users/UserFormDialog.tsx
@@ -0,0 +1,251 @@
+import { Dialog, HStack, Input, Portal, Stack, Switch, Text } from '@chakra-ui/react';
+import { useMemo, useState } from 'react';
+import { WandSparklesIcon } from 'lucide-react';
+
+import { createUser, generatePassword, updateUser, type UserDTO, type UserUpdateRequest } from '../../auth/api';
+import { AuthFormAlert } from '../../auth/components/AuthScreen';
+import { PasswordInput, PasswordStrengthMeter } from '../../auth/components/PasswordInput';
+import { createUserFormSchema, PASSWORD_RULES_HINT, type UserFormValues } from '../../auth/schemas';
+import { useAuthSession } from '../../auth/session';
+import { getApiErrorMessage } from '../../backend/http';
+import { Button, CloseButton } from '../../components/ui/Button';
+import { Field } from '../../components/ui/Field';
+import { useZodForm } from '../../models/useZodForm';
+import { useNotify } from '../../useNotify';
+
+export type UserFormTarget = { mode: 'create' } | { mode: 'edit'; user: UserDTO };
+
+const getTargetKey = (target: UserFormTarget): string => (target.mode === 'edit' ? target.user.user_id : 'create');
+
+/**
+ * Create/edit user form for the users widget. The dialog root stays mounted
+ * and is driven by `target` (null = closed); the inner form is keyed by the
+ * target so each open starts from a fresh state.
+ */
+export const UserFormDialog = ({
+ onClose,
+ onSaved,
+ target,
+}: {
+ onClose: () => void;
+ onSaved: () => void;
+ target: UserFormTarget | null;
+}) => (
+ <Dialog.Root
+ lazyMount
+ open={target !== null}
+ placement="center"
+ scrollBehavior="inside"
+ size="sm"
+ unmountOnExit
+ onOpenChange={(event) => {
+ if (!event.open) {
+ onClose();
+ }
+ }}
+ >
+ <Portal>
+ <Dialog.Backdrop />
+ <Dialog.Positioner>
+ <Dialog.Content bg="bg.surface" borderColor="border.subtle" borderWidth="1px" color="fg.default">
+ {target ? (
+ <>
+ <Dialog.Header borderBottomWidth="1px" borderColor="border.subtle">
+ <Stack gap="0.5">
+ <Dialog.Title fontSize="md" fontWeight="700">
+ {target.mode === 'create' ? 'Add user' : 'Edit user'}
+ </Dialog.Title>
+ {target.mode === 'edit' ? (
+ <Text color="fg.subtle" fontSize="xs">
+ {target.user.email}
+ </Text>
+ ) : null}
+ </Stack>
+ </Dialog.Header>
+ <UserForm key={getTargetKey(target)} target={target} onClose={onClose} onSaved={onSaved} />
+ </>
+ ) : null}
+ <Dialog.CloseTrigger asChild>
+ <CloseButton color="fg.muted" size="sm" />
+ </Dialog.CloseTrigger>
+ </Dialog.Content>
+ </Dialog.Positioner>
+ </Portal>
+ </Dialog.Root>
+);
+
+const UserForm = ({
+ onClose,
+ onSaved,
+ target,
+}: {
+ onClose: () => void;
+ onSaved: () => void;
+ target: UserFormTarget;
+}) => {
+ const session = useAuthSession();
+ const notify = useNotify();
+ const [isGenerating, setIsGenerating] = useState(false);
+ const isCreate = target.mode === 'create';
+ const editedUser = target.mode === 'edit' ? target.user : null;
+ const isSelf = editedUser !== null && editedUser.user_id === session.user?.user_id;
+
+ const schema = useMemo(
+ () => createUserFormSchema(session.strictPasswordChecking, isCreate),
+ [isCreate, session.strictPasswordChecking]
+ );
+ const initialValues: UserFormValues = useMemo(
+ () => ({
+ displayName: editedUser?.display_name ?? '',
+ email: '',
+ isAdmin: editedUser?.is_admin ?? false,
+ password: '',
+ }),
+ [editedUser]
+ );
+ const form = useZodForm(schema, initialValues);
+
+ const fillGeneratedPassword = async () => {
+ setIsGenerating(true);
+
+ try {
+ form.setValue('password', await generatePassword());
+ notify.info('Password generated', 'Reveal it with the eye icon and share it with the user securely.');
+ } catch (error) {
+ notify.error('Could not generate a password', getApiErrorMessage(error, 'The backend rejected the request.'));
+ } finally {
+ setIsGenerating(false);
+ }
+ };
+
+ const submit = () =>
+ form.handleSubmit(async (values) => {
+ try {
+ if (isCreate) {
+ await createUser({
+ display_name: values.displayName.trim() || null,
+ email: values.email,
+ is_admin: values.isAdmin,
+ password: values.password,
+ });
+ } else if (editedUser) {
+ const changes: UserUpdateRequest = {};
+ const displayName = values.displayName.trim();
+
+ if (displayName !== (editedUser.display_name ?? '')) {
+ changes.display_name = displayName;
+ }
+
+ if (values.password !== '') {
+ changes.password = values.password;
+ }
+
+ if (values.isAdmin !== editedUser.is_admin) {
+ changes.is_admin = values.isAdmin;
+ }
+
+ if (Object.keys(changes).length === 0) {
+ onClose();
+ return;
+ }
+
+ await updateUser(editedUser.user_id, changes);
+ }
+ } catch (error) {
+ throw new Error(
+ getApiErrorMessage(error, isCreate ? 'Could not create the user.' : 'Could not update the user.')
+ );
+ }
+
+ notify.success(isCreate ? 'User created' : 'User updated');
+ onSaved();
+ onClose();
+ });
+
+ return (
+ <>
+ <Dialog.Body>
+ <Stack gap="4" py="2">
+ {form.formError ? <AuthFormAlert message={form.formError} tone="error" /> : null}
+ {isCreate ? (
+ <Field error={form.errors.email} label="Email">
+ <Input
+ aria-invalid={form.errors.email ? true : undefined}
+ autoComplete="off"
+ autoFocus
+ placeholder="[email protected]"
+ value={form.values.email}
+ onChange={(event) => form.setValue('email', event.target.value)}
+ />
+ </Field>
+ ) : null}
+ <Field helpText="Optional — shown instead of the email." label="Display name">
+ <Input
+ autoComplete="off"
+ value={form.values.displayName}
+ onChange={(event) => form.setValue('displayName', event.target.value)}
+ />
+ </Field>
+ <Field
+ error={form.errors.password}
+ helpText={
+ isCreate
+ ? session.strictPasswordChecking
+ ? PASSWORD_RULES_HINT
+ : undefined
+ : 'Leave blank to keep the current password.'
+ }
+ label={isCreate ? 'Password' : 'New password'}
+ >
+ <Stack gap="1.5">
+ <HStack gap="2">
+ <PasswordInput
+ aria-invalid={form.errors.password ? true : undefined}
+ autoComplete="new-password"
+ flex="1"
+ value={form.values.password}
+ onChange={(event) => form.setValue('password', event.target.value)}
+ />
+ <Button loading={isGenerating} size="xs" variant="outline" onClick={() => void fillGeneratedPassword()}>
+ <WandSparklesIcon />
+ Generate
+ </Button>
+ </HStack>
+ <PasswordStrengthMeter password={form.values.password} />
+ </Stack>
+ </Field>
+ <Switch.Root
+ alignItems="center"
+ checked={form.values.isAdmin}
+ disabled={isSelf}
+ display="flex"
+ justifyContent="space-between"
+ w="full"
+ onCheckedChange={(event) => form.setValue('isAdmin', event.checked)}
+ >
+ <Stack gap="0.5">
+ <Switch.Label color="fg.default" fontSize="sm" fontWeight="500" m="0">
+ Administrator
+ </Switch.Label>
+ <Text color="fg.subtle" fontSize="xs">
+ {isSelf ? 'You cannot change your own role.' : 'Can manage users and all workspace settings.'}
+ </Text>
+ </Stack>
+ <Switch.HiddenInput />
+ <Switch.Control _checked={{ bg: 'accent.invoke' }}>
+ <Switch.Thumb />
+ </Switch.Control>
+ </Switch.Root>
+ </Stack>
+ </Dialog.Body>
+ <Dialog.Footer gap="2">
+ <Button size="xs" variant="ghost" onClick={onClose}>
+ Cancel
+ </Button>
+ <Button loading={form.isSubmitting} size="xs" variant="solid" onClick={() => void submit()}>
+ {isCreate ? 'Create user' : 'Save changes'}
+ </Button>
+ </Dialog.Footer>
+ </>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/users/UsersWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/users/UsersWidgetView.tsx
new file mode 100644
index 0000000000..faafbefab6
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/users/UsersWidgetView.tsx
@@ -0,0 +1,271 @@
+import { Avatar, Badge, Box, Center, Flex, HStack, Spinner, Stack, Switch, Table, Text } from '@chakra-ui/react';
+import { useCallback, useEffect, useState } from 'react';
+import { PencilIcon, Trash2Icon, UserPlusIcon } from 'lucide-react';
+
+import { deleteUser, listUsers, updateUser, type UserDTO } from '../../auth/api';
+import { useAuthSession } from '../../auth/session';
+import { getApiErrorMessage } from '../../backend/http';
+import { Button, IconButton } from '../../components/ui/Button';
+import { ConfirmDialog } from '../../components/ui/ConfirmDialog';
+import { Scrollable } from '../../components/ui/Scrollable';
+import { Tooltip } from '../../components/ui/Tooltip';
+import { useNotify } from '../../useNotify';
+import { UserFormDialog, type UserFormTarget } from './UserFormDialog';
+
+/**
+ * Admin-only center view: the workspace user directory with create, edit,
+ * activate/deactivate, and delete. The widget is already hidden for
+ * non-admins via `requiresAdmin`; the inline guard covers stale persisted
+ * layouts that still point at it.
+ */
+export const UsersWidgetView = () => {
+ const session = useAuthSession();
+
+ if (!session.multiuserEnabled || session.user?.is_admin !== true) {
+ return (
+ <Center h="full" w="full">
+ <Text color="fg.subtle" fontSize="sm">
+ User management is available to administrators only.
+ </Text>
+ </Center>
+ );
+ }
+
+ return <UsersDirectory currentUserId={session.user.user_id} />;
+};
+
+const UsersDirectory = ({ currentUserId }: { currentUserId: string }) => {
+ const notify = useNotify();
+ const [users, setUsers] = useState<UserDTO[] | null>(null);
+ const [loadError, setLoadError] = useState<string | null>(null);
+ const [formTarget, setFormTarget] = useState<UserFormTarget | null>(null);
+ const [deleteTarget, setDeleteTarget] = useState<UserDTO | null>(null);
+
+ const refresh = useCallback(async () => {
+ try {
+ setUsers(await listUsers());
+ setLoadError(null);
+ } catch (error) {
+ setLoadError(getApiErrorMessage(error, 'Could not load users.'));
+ }
+ }, []);
+
+ useEffect(() => {
+ void refresh();
+ }, [refresh]);
+
+ const setUserActive = async (user: UserDTO, isActive: boolean) => {
+ try {
+ await updateUser(user.user_id, { is_active: isActive });
+ await refresh();
+ } catch (error) {
+ notify.error(
+ isActive ? 'Could not activate the user' : 'Could not deactivate the user',
+ getApiErrorMessage(error, 'The backend rejected the change.')
+ );
+ }
+ };
+
+ const confirmDelete = async () => {
+ if (!deleteTarget) {
+ return;
+ }
+
+ try {
+ await deleteUser(deleteTarget.user_id);
+ notify.success('User deleted');
+ await refresh();
+ } catch (error) {
+ notify.error('Could not delete the user', getApiErrorMessage(error, 'The backend rejected the request.'));
+ }
+ };
+
+ return (
+ <>
+ <Scrollable flex="1" h="full" label="User management">
+ <Flex justify="center" px="4" py="6" w="full">
+ <Stack gap="4" w="full">
+ <HStack align="flex-start" justify="space-between">
+ <Stack gap="0.5">
+ <Text fontSize="md" fontWeight="700">
+ Users
+ </Text>
+ <Text color="fg.subtle" fontSize="xs">
+ {users
+ ? `${users.length} ${users.length === 1 ? 'account' : 'accounts'} in this workspace.`
+ : 'Manage workspace accounts and roles.'}
+ </Text>
+ </Stack>
+ <Button size="xs" variant="solid" onClick={() => setFormTarget({ mode: 'create' })}>
+ <UserPlusIcon />
+ Add user
+ </Button>
+ </HStack>
+ <Box bg="bg.surface" borderColor="border.subtle" borderWidth="1px" overflow="hidden" rounded="lg">
+ {users === null ? (
+ <Center minH="40">
+ {loadError ? (
+ <Stack align="center" gap="2" p="4">
+ <Text color="fg.error" fontSize="xs" textAlign="center">
+ {loadError}
+ </Text>
+ <Button size="xs" variant="outline" onClick={() => void refresh()}>
+ Retry
+ </Button>
+ </Stack>
+ ) : (
+ <Spinner color="fg.muted" size="sm" />
+ )}
+ </Center>
+ ) : (
+ <Table.Root size="sm">
+ <Table.Header>
+ <Table.Row bg="bg.surfaceRaised">
+ <Table.ColumnHeader borderColor="border.subtle" color="fg.muted" ps="4">
+ User
+ </Table.ColumnHeader>
+ <Table.ColumnHeader borderColor="border.subtle" color="fg.muted">
+ Role
+ </Table.ColumnHeader>
+ <Table.ColumnHeader borderColor="border.subtle" color="fg.muted">
+ Last sign-in
+ </Table.ColumnHeader>
+ <Table.ColumnHeader borderColor="border.subtle" color="fg.muted">
+ Active
+ </Table.ColumnHeader>
+ <Table.ColumnHeader borderColor="border.subtle" pe="4" />
+ </Table.Row>
+ </Table.Header>
+ <Table.Body>
+ {users.map((user) => (
+ <UserRow
+ key={user.user_id}
+ isSelf={user.user_id === currentUserId}
+ user={user}
+ onDelete={() => setDeleteTarget(user)}
+ onEdit={() => setFormTarget({ mode: 'edit', user })}
+ onSetActive={(isActive) => void setUserActive(user, isActive)}
+ />
+ ))}
+ </Table.Body>
+ </Table.Root>
+ )}
+ </Box>
+ </Stack>
+ </Flex>
+ </Scrollable>
+ <UserFormDialog target={formTarget} onClose={() => setFormTarget(null)} onSaved={() => void refresh()} />
+ <ConfirmDialog
+ body={`Delete ${deleteTarget ? getUserLabel(deleteTarget) : 'this user'}? Their account is removed permanently.`}
+ confirmLabel="Delete user"
+ isOpen={deleteTarget !== null}
+ title="Delete user?"
+ onClose={() => setDeleteTarget(null)}
+ onConfirm={confirmDelete}
+ />
+ </>
+ );
+};
+
+const getUserLabel = (user: UserDTO): string => user.display_name?.trim() || user.email;
+
+const formatLastSignIn = (lastLoginAt: string | null): string => {
+ if (!lastLoginAt) {
+ return 'Never';
+ }
+
+ const date = new Date(lastLoginAt);
+
+ return Number.isNaN(date.getTime()) ? 'Never' : date.toLocaleString();
+};
+
+const UserRow = ({
+ isSelf,
+ onDelete,
+ onEdit,
+ onSetActive,
+ user,
+}: {
+ isSelf: boolean;
+ onDelete: () => void;
+ onEdit: () => void;
+ onSetActive: (isActive: boolean) => void;
+ user: UserDTO;
+}) => (
+ <Table.Row bg="transparent" _hover={{ bg: 'bg.surfaceRaised' }}>
+ <Table.Cell borderColor="border.subtle" ps="4">
+ <HStack gap="2.5">
+ <Avatar.Root bg="accent.widget" color="fg.default" size="2xs">
+ <Avatar.Fallback fontSize="2xs" name={getUserLabel(user)} />
+ </Avatar.Root>
+ <Stack gap="0">
+ <HStack gap="1.5">
+ <Text fontSize="xs" fontWeight="600">
+ {getUserLabel(user)}
+ </Text>
+ {isSelf ? (
+ <Badge colorPalette="theme" fontSize="2xs" variant="surface">
+ You
+ </Badge>
+ ) : null}
+ </HStack>
+ <Text color="fg.muted" fontSize="2xs">
+ {user.email}
+ </Text>
+ </Stack>
+ </HStack>
+ </Table.Cell>
+ <Table.Cell borderColor="border.subtle">
+ <Badge colorPalette={user.is_admin ? 'purple' : 'gray'} fontSize="2xs" variant="surface">
+ {user.is_admin ? 'Admin' : 'User'}
+ </Badge>
+ </Table.Cell>
+ <Table.Cell borderColor="border.subtle">
+ <Text color="fg.muted" fontSize="2xs">
+ {formatLastSignIn(user.last_login_at)}
+ </Text>
+ </Table.Cell>
+ <Table.Cell borderColor="border.subtle">
+ <Tooltip content="You cannot deactivate your own account." disabled={!isSelf} showArrow>
+ <Switch.Root
+ aria-label={`${getUserLabel(user)} active`}
+ checked={user.is_active}
+ disabled={isSelf}
+ size="sm"
+ onCheckedChange={(event) => onSetActive(event.checked)}
+ >
+ <Switch.HiddenInput />
+ <Switch.Control _checked={{ bg: 'accent.invoke' }}>
+ <Switch.Thumb />
+ </Switch.Control>
+ </Switch.Root>
+ </Tooltip>
+ </Table.Cell>
+ <Table.Cell borderColor="border.subtle" pe="4" textAlign="end">
+ <HStack gap="0.5" justify="flex-end">
+ <IconButton
+ aria-label={`Edit ${getUserLabel(user)}`}
+ color="fg.muted"
+ size="2xs"
+ variant="ghost"
+ onClick={onEdit}
+ >
+ <PencilIcon />
+ </IconButton>
+ <Tooltip content="You cannot delete your own account." disabled={!isSelf} showArrow>
+ <IconButton
+ aria-label={`Delete ${getUserLabel(user)}`}
+ color="fg.muted"
+ disabled={isSelf}
+ size="2xs"
+ variant="ghost"
+ _hover={{ color: 'fg.error' }}
+ onClick={onDelete}
+ >
+ <Trash2Icon />
+ </IconButton>
+ </Tooltip>
+ </HStack>
+ </Table.Cell>
+ </Table.Row>
+);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/users/index.ts b/invokeai/frontend/webv2/src/workbench/widgets/users/index.ts
new file mode 100644
index 0000000000..ea68091baa
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/users/index.ts
@@ -0,0 +1,14 @@
+import type { WidgetManifest } from '../../types';
+import { UsersWidgetView } from './UsersWidgetView';
+
+export const usersWidgetManifest: WidgetManifest = {
+ failurePolicy: { isolateRenderFailure: true, onRegistrationFailure: 'disable' },
+ icon: 'lucide-react:users',
+ id: 'users',
+ label: 'Users',
+ labelText: 'Users',
+ regions: ['center'],
+ requiresAdmin: true,
+ version: 1,
+ view: UsersWidgetView,
+};
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
index 595bfee0e8..e087d1afde 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
@@ -313,6 +313,7 @@ const cloneWidgetStates = (
preview: cloneWidgetState(widgetStates.preview ?? defaultWidgetStates.preview),
queue: cloneWidgetState(widgetStates.queue ?? defaultWidgetStates.queue),
'server-status': cloneWidgetState(widgetStates['server-status'] ?? defaultWidgetStates['server-status']),
+ users: cloneWidgetState(widgetStates.users ?? defaultWidgetStates.users),
'version-status': cloneWidgetState(widgetStates['version-status'] ?? defaultWidgetStates['version-status']),
workflow: cloneWidgetState(widgetStates.workflow ?? defaultWidgetStates.workflow),
};
@@ -409,6 +410,7 @@ const createWidgetStates = (): Record<WidgetId, WidgetStateContract> => ({
preview: { id: 'preview', label: 'Preview', values: {}, version: 1 },
queue: { id: 'queue', label: 'Queue', values: {}, version: 1 },
'server-status': { id: 'server-status', label: 'Server Status', values: {}, version: 1 },
+ users: { id: 'users', label: 'Users', values: {}, version: 1 },
'version-status': { id: 'version-status', label: 'Version', values: {}, version: 1 },
workflow: { graphId: 'workflow-graph', id: 'workflow', label: 'Workflow', values: {}, version: 1 },
});