From e89e123e50e72ddd685303c1a4cd2ee401e6b390 Mon Sep 17 00:00:00 2001 From: Luc Bocahut Date: Sat, 7 Nov 2026 14:40:51 +0100 Subject: [PATCH 01/13] Use compact select menus for repository choices --- ui/app/components/RepositoryChoiceSetting.vue | 14 ++++--- ui/tests/e2e/repository-settings.spec.mjs | 39 ++++++++++++------- .../components/repository-choice.nuxt.test.ts | 32 ++++++++++++++- .../components/steward-policy.nuxt.test.ts | 7 ++-- 4 files changed, 68 insertions(+), 24 deletions(-) diff --git a/ui/app/components/RepositoryChoiceSetting.vue b/ui/app/components/RepositoryChoiceSetting.vue index 57fb85e8..5cfa08ac 100644 --- a/ui/app/components/RepositoryChoiceSetting.vue +++ b/ui/app/components/RepositoryChoiceSetting.vue @@ -28,12 +28,16 @@ async function submit() {
- - Save + + Saved - Unsaved change
diff --git a/ui/tests/e2e/repository-settings.spec.mjs b/ui/tests/e2e/repository-settings.spec.mjs index 5ffb7749..2000ef29 100644 --- a/ui/tests/e2e/repository-settings.spec.mjs +++ b/ui/tests/e2e/repository-settings.spec.mjs @@ -6,24 +6,28 @@ export default async function (page, { base, scenario, requests }) { await page.getByLabel('Merging', { exact: true }).waitFor() await page.waitForFunction(() => document.querySelector('#__nuxt')?.__vue_app__?.config.globalProperties.$nuxt?.isHydrating === false) assert.equal(await page.getByRole('button', { name: 'Review setup', exact: true }).count(), 0) - assert.equal(await page.locator('#merge-policy').inputValue(), 'human') - assert.equal(await page.locator('#review-scope').inputValue(), 'forge') - assert.match(await page.locator('#review-scope-help').innerText(), /only the pull requests it creates/) - assert.equal(await page.locator('#mirror-denied, #test-databases, #deployment').count(), 0, 'advanced sections mount only on demand') - await page.locator('#merge-policy').selectOption('auto') + assert.match(await page.locator('#merge-policy').innerText(), /Require human approval/) + assert.equal(await page.getByRole('button', { name: 'Save merging', exact: true }).count(), 0) + assert.equal(await page.locator('#review-scope, #recovery-policy, #mirror-denied, #test-databases, #deployment').count(), 0, 'more settings mount only on demand') + await page.getByRole('button', { name: 'Merging', exact: true }).click() + await page.getByRole('option', { name: 'Merge after checks', exact: true }).click() assert.equal((await requests()).filter(r => r.method === 'POST' && r.path.endsWith('/merge-policy')).length, 0) await page.getByRole('button', { name: 'Save merging', exact: true }).click() await page.locator('form').filter({ has: page.locator('#merge-policy') }).getByRole('status').waitFor() const save = (await requests()).find(r => r.method === 'POST' && r.path.endsWith('/merge-policy')) assert.deepEqual(save.body, { repo_id: 2, revision: 'runtime-rev-1', mode: 'auto' }) await page.reload() - assert.equal(await page.locator('#merge-policy').inputValue(), 'auto') - assert.equal(await page.locator('#review-scope').inputValue(), 'forge', 'saving merge policy preserves review scope') - await page.locator('#review-scope').selectOption('all') + assert.match(await page.locator('#merge-policy').innerText(), /Merge after checks/) + await page.locator('summary').filter({ hasText: 'More settings' }).click() + assert.match(await page.locator('#review-scope').innerText(), /Forge pull requests/, 'saving merge policy preserves review scope') + await page.getByRole('button', { name: 'Review pull requests', exact: true }).click() + await page.getByRole('option', { name: 'All pull requests', exact: true }).click() await page.getByRole('button', { name: 'Save review pull requests', exact: true }).click() await page.locator('form').filter({ has: page.locator('#review-scope') }).getByRole('status').waitFor() - assert.match(await page.locator('#review-scope-help').innerText(), /both its own/) - await page.locator('#recovery-policy').selectOption('manual') + const scopeSave = (await requests()).find(r => r.method === 'POST' && r.path.endsWith('/review-scope')) + assert.equal(scopeSave.body.scope, 'all') + await page.getByRole('button', { name: 'Recovery', exact: true }).click() + await page.getByRole('option', { name: 'Ask me', exact: true }).click() await page.getByRole('button', { name: 'Save recovery', exact: true }).click() await page.locator('form').filter({ has: page.locator('#recovery-policy') }).getByRole('status').waitFor() await page.locator('summary').filter({ hasText: 'Deployment tracking' }).click() @@ -42,10 +46,17 @@ export default async function (page, { base, scenario, requests }) { assert.equal((await requests()).filter(r => r.method === 'POST' && r.path.endsWith('/disable')).length, 0) await page.locator('summary').filter({ hasText: 'Dependency access' }).click() await page.locator('summary').filter({ hasText: 'Deployment tracking' }).click() + await page.locator('summary').filter({ hasText: 'More settings' }).click() await page.evaluate(() => window.scrollTo(0, 0)) await page.screenshot({ path: '/tmp/forge-settings-desktop.png', fullPage: true, animations: 'disabled' }) - await page.setViewportSize({ width: 390, height: 844 }) - await page.evaluate(() => window.scrollTo(0, 0)) - await page.screenshot({ path: '/tmp/forge-settings-mobile.png', fullPage: true, animations: 'disabled' }) - assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)) + for (const width of [390, 320]) { + await page.setViewportSize({ width, height: 844 }) + await page.evaluate(() => window.scrollTo(0, 0)) + await page.screenshot({ path: `/tmp/forge-settings-mobile-${width}.png`, fullPage: true, animations: 'disabled' }) + assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)) + await page.getByRole('button', { name: 'Merging', exact: true }).click() + await page.getByRole('option', { name: 'Require human approval', exact: true }).waitFor() + assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)) + await page.keyboard.press('Escape') + } } diff --git a/ui/tests/unit/components/repository-choice.nuxt.test.ts b/ui/tests/unit/components/repository-choice.nuxt.test.ts index e836aaef..68293710 100644 --- a/ui/tests/unit/components/repository-choice.nuxt.test.ts +++ b/ui/tests/unit/components/repository-choice.nuxt.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it, vi } from 'vitest' import { mountSuspended } from '@nuxt/test-utils/runtime' import { flushPromises } from '@vue/test-utils' +import SelectMenu from '@nuxt/ui/components/SelectMenu.vue' import RepositoryChoiceSetting from '../../../app/components/RepositoryChoiceSetting.vue' describe('repository choices', () => { @@ -11,7 +12,8 @@ describe('repository choices', () => { id: 'scope', label: 'Review pull requests', value: 'all', save, options: [{ value: 'all', label: 'All pull requests' }, { value: 'forge', label: 'Forge only' }], } }) - await wrapper.get('select').setValue('forge') + expect(wrapper.find('[type=submit]').exists()).toBe(false) + wrapper.getComponent(SelectMenu).vm.$emit('update:modelValue', 'forge'); await flushPromises() expect(save).not.toHaveBeenCalled() await wrapper.setProps({ disabled: true }) await wrapper.get('form').trigger('submit') @@ -20,8 +22,34 @@ describe('repository choices', () => { await wrapper.get('form').trigger('submit'); await flushPromises() expect(save).toHaveBeenCalledExactlyOnceWith('forge') expect(wrapper.get('[role="alert"]').text()).toContain('Settings changed') - expect((wrapper.get('select').element as HTMLSelectElement).value).toBe('forge') + expect(wrapper.getComponent(SelectMenu).props('modelValue')).toBe('forge') expect(wrapper.text()).not.toContain('Saved') wrapper.unmount() }) + it('preserves edits across observations, supports discard, and prevents duplicate saves', async () => { + let finish!: () => void + const save = vi.fn(() => new Promise(resolve => { finish = resolve })) + const wrapper = await mountSuspended(RepositoryChoiceSetting, { props: { + id: 'merge-policy', label: 'Merging', value: 'human', save, + options: [{ value: 'human', label: 'Require approval' }, { value: 'auto', label: 'Automatic' }], + } }) + const menu = wrapper.getComponent(SelectMenu) + menu.vm.$emit('update:modelValue', 'auto'); await flushPromises() + await wrapper.setProps({ value: 'human' }) + expect(menu.props('modelValue')).toBe('auto') + await wrapper.get('[aria-label="Discard merging changes"]').trigger('click') + expect(menu.props('modelValue')).toBe('human') + expect(wrapper.find('[type=submit]').exists()).toBe(false) + menu.vm.$emit('update:modelValue', 'auto'); await flushPromises() + await wrapper.get('form').trigger('submit') + expect(menu.props('disabled')).toBe(true) + await wrapper.get('form').trigger('submit') + expect(save).toHaveBeenCalledExactlyOnceWith('auto') + await wrapper.setProps({ value: 'auto' }) + finish(); await flushPromises() + expect(wrapper.find('[type=submit]').exists()).toBe(false) + expect(wrapper.get('[role="status"]').text()).toBe('Saved') + wrapper.unmount() + }) + }) diff --git a/ui/tests/unit/components/steward-policy.nuxt.test.ts b/ui/tests/unit/components/steward-policy.nuxt.test.ts index 6e66a267..3f7ad717 100644 --- a/ui/tests/unit/components/steward-policy.nuxt.test.ts +++ b/ui/tests/unit/components/steward-policy.nuxt.test.ts @@ -2,6 +2,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { mountSuspended, mockNuxtImport } from '@nuxt/test-utils/runtime' import { flushPromises } from '@vue/test-utils' +import SelectMenu from '@nuxt/ui/components/SelectMenu.vue' import RepositoryStewardPolicy from '../../../app/components/RepositoryStewardPolicy.vue' const { get, act } = vi.hoisted(() => ({ get: vi.fn(), act: vi.fn() })) mockNuxtImport('useForgeApi', () => () => ({ get, act })) @@ -17,9 +18,9 @@ describe('steward repository policy', () => { const wrapper = await mountSuspended(RepositoryStewardPolicy, { props: { repoId } }) await flushPromises() expect(get).toHaveBeenCalledWith(`/api/repositories/steward?repo_id=${repoId}`) - await wrapper.get('select').setValue('manual'); await wrapper.get('form').trigger('submit'); await flushPromises() + wrapper.getComponent(SelectMenu).vm.$emit('update:modelValue', 'manual'); await flushPromises(); await wrapper.get('form').trigger('submit'); await flushPromises() expect(act).toHaveBeenCalledWith('/api/repositories/steward', { repo_id: repoId, revision: 2, policy: 'manual' }) - expect(wrapper.get('select').element.value).toBe('manual') + expect(wrapper.getComponent(SelectMenu).props('modelValue')).toBe('manual') expect(wrapper.text()).toContain('Saved') wrapper.unmount() }) @@ -28,7 +29,7 @@ describe('steward repository policy', () => { get.mockResolvedValue({ ok: true, repo_id: repoId, name: 'owner/repo', policy: 'manual', revision: 3 }) act.mockRejectedValue(new Error('lost reply')) const wrapper = await mountSuspended(RepositoryStewardPolicy, { props: { repoId } }) - await flushPromises(); await wrapper.get('select').setValue('reversible'); await wrapper.get('form').trigger('submit'); await flushPromises() + await flushPromises(); wrapper.getComponent(SelectMenu).vm.$emit('update:modelValue', 'reversible'); await flushPromises(); await wrapper.get('form').trigger('submit'); await flushPromises() expect(wrapper.text()).toContain('lost reply') expect(act).toHaveBeenCalledTimes(1) wrapper.unmount() From 92a76d2d62a22385e67dc0c55dd7c479a1a85c09 Mon Sep 17 00:00:00 2001 From: Luc Bocahut Date: Sat, 7 Nov 2026 14:42:12 +0100 Subject: [PATCH 02/13] Open advanced repository settings in browser journeys --- ui/tests/e2e/deployment.spec.mjs | 2 ++ ui/tests/e2e/migration-followups.spec.mjs | 1 + ui/tests/e2e/repository-environment.spec.mjs | 8 ++++++++ 3 files changed, 11 insertions(+) diff --git a/ui/tests/e2e/deployment.spec.mjs b/ui/tests/e2e/deployment.spec.mjs index 462a49f6..6b3c3505 100644 --- a/ui/tests/e2e/deployment.spec.mjs +++ b/ui/tests/e2e/deployment.spec.mjs @@ -26,6 +26,7 @@ export default async function (page, { base, scenario, requests }) { // Proposed: what the strategist read, with the domain it found prefilled // and nothing saved yet. await page.goto(base + '/settings/repositories/1') + await page.locator('summary').filter({ hasText: 'More settings' }).click() await page.locator('summary').filter({ hasText: 'Deployment tracking' }).click() await page.getByText('Inspection details', { exact: true }).click() await waitForText(page, 'Proposal ready') @@ -54,6 +55,7 @@ export default async function (page, { base, scenario, requests }) { // Confirmed: the profile as one line, and what Forge last observed. await page.goto(base + '/settings/repositories/2') + await page.locator('summary').filter({ hasText: 'More settings' }).click() await page.locator('summary').filter({ hasText: 'Deployment tracking' }).click() await waitForText(page, 'Tracked') assert.equal( diff --git a/ui/tests/e2e/migration-followups.spec.mjs b/ui/tests/e2e/migration-followups.spec.mjs index 9b82c55c..4ad1cc8e 100644 --- a/ui/tests/e2e/migration-followups.spec.mjs +++ b/ui/tests/e2e/migration-followups.spec.mjs @@ -68,6 +68,7 @@ export default async function (page, { base, scenario, observeIssue }) { }) await page.goto(base + '/settings/repositories/2') await page.getByRole('button', { name: 'Continue setup', exact: true }).waitFor() + await page.locator('summary').filter({ hasText: 'More settings' }).click() await page.locator('summary').filter({ hasText: 'Diagnostics' }).click() await page.waitForFunction(() => [...document.querySelectorAll('button')].some(button => button.textContent.trim() === 'Refresh repository' && button.disabled)) await page.unroute('**/api/repositories?repo_id=2') diff --git a/ui/tests/e2e/repository-environment.spec.mjs b/ui/tests/e2e/repository-environment.spec.mjs index 7b6769d2..f2670782 100644 --- a/ui/tests/e2e/repository-environment.spec.mjs +++ b/ui/tests/e2e/repository-environment.spec.mjs @@ -7,6 +7,7 @@ export default async function (page, { base, scenario, requests }) { await page.goto(base + path) await page.locator('#repository-platform-notice').waitFor() assert.ok((await page.locator('#repository-platform-notice').innerText()).includes('verification on a Mac')) + await page.locator('summary').filter({ hasText: 'More settings' }).click() await page.locator('summary').filter({ hasText: 'Test environment' }).click() assert.ok((await page.locator('#test-databases').innerText()).includes('Workers run Linux')) assert.ok((await page.locator('#test-databases').innerText()).includes('App.xcodeproj/project.pbxproj')) @@ -14,6 +15,7 @@ export default async function (page, { base, scenario, requests }) { await scenario('environment-idle') await page.goto(base + path) + await page.locator('summary').filter({ hasText: 'More settings' }).click() await page.locator('summary').filter({ hasText: 'Test environment' }).click() const card = page.locator('#test-databases') await card.getByRole('button', { name: 'Scan requirements' }).click() @@ -35,6 +37,7 @@ export default async function (page, { base, scenario, requests }) { const saved = (await requests()).filter(r => r.method === 'POST' && r.path === endpoint) assert.deepEqual(saved[0].body, { repo_id: 2, revision: 'settings-rev-1', environment_revision: 'env-proposed', action: 'confirm' }) await page.reload() + await page.locator('summary').filter({ hasText: 'More settings' }).click() await page.locator('summary').filter({ hasText: 'Test environment' }).click() await page.waitForFunction(() => document.querySelector('#test-databases')?.textContent.includes('Repository default: MongoDB')) assert.equal(await card.getByRole('button', { name: 'Save repository default' }).count(), 0) @@ -43,6 +46,7 @@ export default async function (page, { base, scenario, requests }) { await scenario('environment-saved') await page.goto(base + path) + await page.locator('summary').filter({ hasText: 'More settings' }).click() await page.locator('summary').filter({ hasText: 'Test environment' }).click() await card.getByRole('button', { name: 'Use automatic selection' }).click() await page.waitForFunction(() => document.querySelector('#test-databases')?.textContent.includes('Automatic selection is enabled')) @@ -51,6 +55,7 @@ export default async function (page, { base, scenario, requests }) { await scenario('environment-failed') await page.goto(base + path) + await page.locator('summary').filter({ hasText: 'More settings' }).click() await page.locator('summary').filter({ hasText: 'Test environment' }).click() await card.getByRole('alert').waitFor() assert.ok((await card.innerText()).includes('Repository default: MongoDB'), 'failure must preserve saved requirements') @@ -59,6 +64,7 @@ export default async function (page, { base, scenario, requests }) { await scenario('environment-unavailable') await page.goto(base + path) + await page.locator('summary').filter({ hasText: 'More settings' }).click() await page.locator('summary').filter({ hasText: 'Test environment' }).click() await card.getByText('Optional repository default', { exact: true }).click() await card.getByRole('button', { name: 'Save repository default' }).waitFor() @@ -68,6 +74,7 @@ export default async function (page, { base, scenario, requests }) { await scenario('environment-empty') await page.setViewportSize({ width: 390, height: 844 }) await page.goto(base + path) + await page.locator('summary').filter({ hasText: 'More settings' }).click() await page.locator('summary').filter({ hasText: 'Test environment' }).click() await card.getByText('Optional repository default', { exact: true }).click() await card.getByRole('button', { name: 'Save repository default' }).click() @@ -83,6 +90,7 @@ export default async function (page, { base, scenario, requests }) { await scenario('environment-proposed') await page.setViewportSize({ width: 1440, height: 1000 }) await page.goto(base + path) + await page.locator('summary').filter({ hasText: 'More settings' }).click() await page.locator('summary').filter({ hasText: 'Test environment' }).click() await card.getByText('Optional repository default', { exact: true }).click() await card.getByRole('button', { name: 'Save repository default' }).waitFor() From 4caf638fdfffd247388485144b8a75aa64e51492 Mon Sep 17 00:00:00 2001 From: Luc Bocahut Date: Sat, 7 Nov 2026 14:42:26 +0100 Subject: [PATCH 03/13] Show configured factory name in navigation and browser titles --- docs/installation.md | 17 ++++++ forge/factory_identity.py | 22 ++++++++ forge/host_setup.py | 12 +++-- forge_client/_install_host.py | 2 +- legacy/forge-status.py | 2 + tests/test_factory_identity.py | 67 ++++++++++++++++++++++++ tests/test_operator_auth.py | 12 ++++- ui/app/app.vue | 4 ++ ui/app/components/AppHeader.vue | 9 ++-- ui/app/composables/useFactoryIdentity.ts | 12 +++++ ui/app/composables/useOperator.ts | 1 + ui/app/pages/login.vue | 5 +- ui/app/pages/reset.vue | 2 +- ui/app/utils/factoryIdentity.ts | 5 ++ ui/tests/e2e/factory-identity.spec.mjs | 39 ++++++++++++++ ui/tests/e2e/mock-api.mjs | 1 + ui/tests/unit/factoryIdentity.test.ts | 15 ++++++ 17 files changed, 216 insertions(+), 11 deletions(-) create mode 100644 forge/factory_identity.py create mode 100644 tests/test_factory_identity.py create mode 100644 ui/app/composables/useFactoryIdentity.ts create mode 100644 ui/app/utils/factoryIdentity.ts create mode 100644 ui/tests/e2e/factory-identity.spec.mjs create mode 100644 ui/tests/unit/factoryIdentity.test.ts diff --git a/docs/installation.md b/docs/installation.md index 0d7ed494..0311b710 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -309,3 +309,20 @@ For host requirements, isolation qualification, capacity and upgrades, see Official login references: [Codex authentication](https://learn.chatgpt.com/docs/auth) and [Claude Code CLI](https://code.claude.com/docs/en/cli-reference). + +## Factory name + +The header and browser tab show the name chosen during `forge install`, for +example **Anvil** and **Settings · Anvil · Forge**. The sign-in page shows the +same name. Older factories without a saved display name show **Forge**. + +After updating an existing Anvil installation using the standard service paths, +copy its original installation name into the runtime once: + +```sh +ssh anvil 'sudo -u forge /home/forge/forge/bin/forge setup initialize --root /home/forge/.local/share/forge --name Anvil' +``` + +Use the original name from the approved installation, not an inferred hostname. +This preserves existing factory data. Repeating the same name has no effect; +a different name is refused. Reload the web page afterward. diff --git a/forge/factory_identity.py b/forge/factory_identity.py new file mode 100644 index 00000000..88edc486 --- /dev/null +++ b/forge/factory_identity.py @@ -0,0 +1,22 @@ +"""The operator's factory name, separate from machine and credential identity.""" +import re + +from .store.configuration import Configuration +from .store.runtime import required + + +def initialize(root, name): + if not isinstance(name, str) or not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9 ._-]{0,63}', name): + raise ValueError('Choose a factory name of 1–64 letters, digits, spaces, dots, underscores or hyphens') + configuration = Configuration(required(root)) + current = configuration.get('factory_identity') + if current: + if current['settings']['name'] != name: + raise ValueError('This factory already has a different name; initialization cannot rename it') + return + configuration.replace('factory_identity', {'name': name}, expected_revision=0) + + +def display_name(root): + value = Configuration(required(root)).get('factory_identity') + return value['settings']['name'] if value else None diff --git a/forge/host_setup.py b/forge/host_setup.py index 3cabc357..6e2eb56d 100644 --- a/forge/host_setup.py +++ b/forge/host_setup.py @@ -74,7 +74,7 @@ def user_manager(): '(sudo loginctl enable-linger ' + getpass.getuser() + '), then rerun setup; see docs/installation.md') from None -def initialize(root): +def initialize(root, name=None): """Prepare the qualified SQLite authority before fresh-install services.""" from .store.db import qualified_sqlite if not qualified_sqlite(): @@ -82,9 +82,12 @@ def initialize(root): prepared = prepare(root) environment = {**os.environ, 'LD_LIBRARY_PATH': prepared['library_directory']} os.execve(sys.executable, [sys.executable, '-m', 'forge.launch', 'forge.host_setup', - 'initialize', '--root', str(root)], environment) + 'initialize', '--root', str(root), *(['--name', name] if name is not None else [])], environment) from .store.fresh import initialize as initialize_store store = initialize_store(root) + if name is not None: + from .factory_identity import initialize as initialize_identity + initialize_identity(root, name) print('SQLite initialized for instance ' + store.instance_id) @@ -378,6 +381,7 @@ def main(): parser.add_argument('action', nargs='?', choices=['initialize', 'install', 'update', 'login', 'check', 'status', 'full-environment'], default=None) parser.add_argument('provider', nargs='?', choices=list(manifests())) parser.add_argument('--root', default=str(Path.home() / '.local/share/forge')) + parser.add_argument('--name', help='initialize: factory display name; cannot rename an existing factory') parser.add_argument('--bind', help='Operator UI address: loopback (default) or a private tailnet address; kept across updates') parser.add_argument('--no-pull', action='store_true', help='update: apply the checkout as it is, without fetching') parser.add_argument('--yes', action='store_true', help='Replace service or policy files that were edited outside Forge') @@ -388,11 +392,13 @@ def main(): auth.add_argument('--import-login') parser.add_argument('--model', action='append', help='Repeat to rotate equally between models of this harness') args = parser.parse_args() + if args.name is not None and args.action != 'initialize': + parser.error('--name is only supported with initialize') os.umask(0o077) try: root = private_root(args.root) if args.action == 'initialize': - initialize(root) + initialize(root, args.name) if args.action == 'update': if not args.no_pull and host_update.pull(): # Run the reconciliation that shipped with the new source, not this one. diff --git a/forge_client/_install_host.py b/forge_client/_install_host.py index 272c6fba..b2f5108f 100644 --- a/forge_client/_install_host.py +++ b/forge_client/_install_host.py @@ -334,7 +334,7 @@ def install_step(step, data): prepare_service_cache(data) need(service(['git', '-C', str(SOURCE), 'rev-parse', 'HEAD'], capture=True) == data['intent']['revision'], 'source_conflict') need(not service(['git', '-C', str(SOURCE), 'status', '--porcelain', '--untracked-files=no'], capture=True), 'source_conflict') - service([str(SOURCE / 'bin/forge'), 'setup', 'initialize', '--root', str(ROOT)]) + service([str(SOURCE / 'bin/forge'), 'setup', 'initialize', '--root', str(ROOT), '--name', data['intent']['name']]) service([str(SOURCE / 'bin/forge'), 'setup', 'install', '--root', str(ROOT), '--bind', '127.0.0.1']) for name in ('forge-status', 'forge-ui', 'forge-supervisor'): need(service(['systemctl', '--user', 'is-active', name], capture=True) == 'active', 'services_unavailable') diff --git a/legacy/forge-status.py b/legacy/forge-status.py index 25200acb..e35d3990 100755 --- a/legacy/forge-status.py +++ b/legacy/forge-status.py @@ -240,9 +240,11 @@ def _signed_in(self): def _auth_get(self, url): from forge.operator_auth import read_cookie, FLOW_COOKIE, cookie, failure_reason if url.path == '/api/auth/session': + from forge.factory_identity import display_name mode = self._auth.identity_settings()['mode'] if self._auth_config else None self._send(json.dumps({'ok': True, 'enabled': bool(self._auth_config), 'operator': self._session['operator'] if self._session else None, + 'factory_name': display_name(WD), **({'mode': mode} if self._auth_config else {}), **({'controls_token': self._action_token, 'via': self._session.get('via', 'github')} if self._session else {})})) return True diff --git a/tests/test_factory_identity.py b/tests/test_factory_identity.py new file mode 100644 index 00000000..3c841063 --- /dev/null +++ b/tests/test_factory_identity.py @@ -0,0 +1,67 @@ +"""Factory display names are explicit configuration, independent of hostnames.""" +from contextlib import redirect_stdout +from io import StringIO +from pathlib import Path +import tempfile +import unittest +from unittest.mock import patch + +from forge.factory_identity import initialize, display_name +from forge.store.fresh import initialize as initialize_store +from forge.store.configuration import Configuration + + +class FactoryIdentityTests(unittest.TestCase): + def setUp(self): + temporary = tempfile.TemporaryDirectory() + self.addCleanup(temporary.cleanup) + self.root = Path(temporary.name) + self.store = initialize_store(self.root) + + def test_missing_name_stays_missing_without_using_hostname(self): + self.assertIsNone(display_name(self.root)) + self.assertIsNone(Configuration(self.store).get('factory_identity')) + + def test_initialize_is_idempotent_and_cannot_rename_or_change_unrelated_settings(self): + configuration = Configuration(self.store) + configuration.replace('unrelated', {'keep': 'value'}, expected_revision=0) + initialize(self.root, 'Anvil') + initialize(self.root, 'Anvil') + self.assertEqual(display_name(self.root), 'Anvil') + self.assertEqual(configuration.get('factory_identity')['revision'], 1) + with self.assertRaisesRegex(ValueError, 'cannot rename'): + initialize(self.root, 'Another factory') + self.assertEqual(display_name(self.root), 'Anvil') + self.assertEqual(configuration.get('unrelated')['settings'], {'keep': 'value'}) + + def test_invalid_names_are_rejected(self): + for name in ('', 'x' * 65, '\nAnvil', 'Anvil', None): + with self.subTest(name=name), self.assertRaises(ValueError): + initialize(self.root, name) + self.assertIsNone(display_name(self.root)) + + def test_host_initialize_publishes_approved_name(self): + from forge.host_setup import initialize as initialize_host + with patch('forge.store.db.qualified_sqlite', return_value=True), redirect_stdout(StringIO()): + initialize_host(self.root, 'Anvil') + self.assertEqual(display_name(self.root), 'Anvil') + + def test_sqlite_runtime_reexec_preserves_name(self): + from forge.host_setup import initialize as initialize_host + with patch('forge.store.db.qualified_sqlite', return_value=False), \ + patch('forge.store.migration.runtime.prepare', return_value={'library_directory': '/test/sqlite'}), \ + patch('forge.host_setup.os.execve', side_effect=RuntimeError('exec')) as execute: + with self.assertRaisesRegex(RuntimeError, 'exec'): + initialize_host(self.root, 'Anvil') + self.assertEqual(execute.call_args.args[1][-2:], ['--name', 'Anvil']) + + def test_fresh_installer_passes_its_approved_name_to_host_setup(self): + from forge_client import _install_host as remote + from unittest.mock import Mock + service = Mock(side_effect=lambda argv, **kwargs: 'a' * 40 if 'rev-parse' in argv else + 'active' if 'is-active' in argv else '') + with patch.object(remote, 'prepare_service_cache'), patch.object(remote, 'service', service): + remote.install_step('host', {'intent': {'name': 'Anvil', 'revision': 'a' * 40}}) + calls = [call.args[0] for call in service.call_args_list] + self.assertIn([str(remote.SOURCE / 'bin/forge'), 'setup', 'initialize', '--root', + str(remote.ROOT), '--name', 'Anvil'], calls) diff --git a/tests/test_operator_auth.py b/tests/test_operator_auth.py index 4db657e6..ed2de5f4 100644 --- a/tests/test_operator_auth.py +++ b/tests/test_operator_auth.py @@ -243,10 +243,20 @@ def test_signed_out_reads_and_mutations_are_protected_before_services(self): def test_public_session_has_no_action_capability_or_config(self): handler = self.request('/api/auth/session') result = json.loads(handler._send.call_args.args[0]) - self.assertEqual(result, {'ok': True, 'enabled': True, 'operator': None, 'mode': 'github'}) + self.assertEqual(result, {'ok': True, 'enabled': True, 'operator': None, 'mode': 'github', 'factory_name': None}) handler = self.request('/api/auth/session', signed=True) self.assertEqual(json.loads(handler._send.call_args.args[0])['controls_token'], self.session['csrf']) + def test_factory_name_is_available_before_signin_without_private_configuration(self): + from forge.factory_identity import initialize + initialize(dashboard.WD, 'Anvil') + handler = self.request('/api/auth/session') + result = json.loads(handler._send.call_args.args[0]) + self.assertEqual(result, {'ok': True, 'enabled': True, 'operator': None, + 'mode': 'github', 'factory_name': 'Anvil'}) + handler = self.request('/api/auth/session', signed=True) + self.assertEqual(json.loads(handler._send.call_args.args[0])['factory_name'], 'Anvil') + def test_github_callback_accepts_optional_matching_issuer(self): from urllib.parse import urlencode original = OperatorAuth.callback diff --git a/ui/app/app.vue b/ui/app/app.vue index 5acf3c17..2eeab53e 100644 --- a/ui/app/app.vue +++ b/ui/app/app.vue @@ -1,3 +1,7 @@ +