Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(license): tell the user what the RELEASE did, and nothing false about the license
enes77dd5e8c7e04
diff --git a/src/renderer/components/settings/sections/LicenseSection.test.tsx b/src/renderer/components/settings/sections/LicenseSection.test.tsxnew file mode 100644index 000000000..38ef464be--- /dev/null+++ b/src/renderer/components/settings/sections/LicenseSection.test.tsx@@ -0,0 +1,268 @@+// @vitest-environment jsdom+//+// Settings → License, rendered. The pure copy is pinned in `renderer/lib/licenseCopy.test.ts`; what+// this file exists for is the wiring around it, where every defect in the final review round lived:+// which sentence lands beside which data, what a destructive button does before it does it, and+// whether a failed ACTION is reported as a failed READ.+import { describe, it, expect, beforeEach, afterEach, vi, type Mock } from 'vitest'+import { act } from 'react'+import { createRoot, type Root } from 'react-dom/client'+import type { LicenseDetail, LicenseStatus } from '@shared/types'++;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true++const PRO: LicenseStatus = { tier: 'pro', active: true, expiresAt: null, seats: 3, error: null }+const FREE: LicenseStatus = { tier: null, active: false, expiresAt: null, seats: 0, error: null }+/** A healthy keygen read with room to spare. */+const KEYGEN: LicenseDetail = { key: 'NT-KEY-1', used: 2, seats: 3, source: 'keygen', error: null }++let root: Root+let host: HTMLElement+let detail: Mock<() => Promise<LicenseDetail>>+let releaseOthers: Mock<() => Promise<LicenseDetail>>+let deactivate: Mock<() => Promise<LicenseStatus>>+let activate: Mock<(key: string) => Promise<LicenseStatus>>+let writeText: Mock<(text: string) => void>++/**+ * The store subscribes to `license.onChange` at IMPORT time, so the bridge has to exist before the+ * module graph does — hence the reset + dynamic import, the same shape as `entitlement.test.ts`.+ * Returns the section already mounted with `status` applied, so the mount-time `loadDetail` effect+ * runs exactly as it does in the app.+ */+async function mount(status: LicenseStatus, read: LicenseDetail = KEYGEN): Promise<void> {+ vi.resetModules()+ detail = vi.fn(async () => read)+ releaseOthers = vi.fn(async () => ({ key: null, used: 1, seats: 3, source: null, error: null }))+ deactivate = vi.fn(async () => FREE)+ activate = vi.fn(async () => FREE)+ writeText = vi.fn()+ ;(window as unknown as { nodeTerminal: unknown }).nodeTerminal = {+ license: {+ getStatus: vi.fn(async () => status),+ onChange: vi.fn(() => () => undefined),+ // Indirected so a test can swap the resolved value AFTER mounting (the store captured the+ // bridge object at import time, not these mocks).+ detail: () => detail(),+ releaseOthers: () => releaseOthers(),+ deactivate,+ activate,+ upgrade: vi.fn(async () => status)+ },+ clipboard: { writeText }+ }+ const { useEntitlement } = await import('../../../state/entitlement')+ const { LicenseSection } = await import('./LicenseSection')+ await act(async () => {+ await useEntitlement.getState().hydrate()+ })+ await act(async () => {+ root.render(<LicenseSection isActive />)+ })+ await act(async () => undefined) // the mount-time detail read+}++/** Everything on screen, the portalled dialogs included. */+function screenText(): string {+ return document.body.textContent ?? ''+}++function click(label: string, from: ParentNode = document.body): void {+ const el = [...from.querySelectorAll('button')].find((b) => b.textContent?.trim() === label)+ expect(el, `a rendered "${label}" button`).toBeTruthy()+ ;(el as HTMLButtonElement).click()+}++/** The confirm dialog's own button, which portals onto body after everything else. */+function confirmDialog(label: string): void {+ const all = [...document.body.querySelectorAll('.confirm button')].filter(+ (b) => b.textContent?.trim() === label+ )+ expect(all.length, `a "${label}" button inside the confirm dialog`).toBeGreaterThan(0)+ ;(all[all.length - 1] as HTMLButtonElement).click()+}++beforeEach(() => {+ host = document.createElement('div')+ document.body.appendChild(host)+ root = createRoot(host)+})++afterEach(() => {+ act(() => root.unmount())+ host.remove()+ vi.restoreAllMocks()+ vi.unstubAllGlobals()+})++describe('LicenseSection — a release that did not land', () => {+ it('reports the RELEASE, and keeps saying the truth about the license', async () => {+ await mount(PRO)+ expect(screenText()).toContain('2 of 3 devices in use')++ // The laptop lost wifi between opening Settings and pressing the button.+ releaseOthers.mockResolvedValue({ key: null, used: 0, seats: 0, source: null, error: 'offline' })+ await act(async () => click('Release other devices'))+ await act(async () => confirmDialog('Release others'))+ await act(async () => undefined)++ const text = screenText()+ // 1. The user is told about the thing they just pressed…+ expect(text).toMatch(/Could not confirm the release/)+ // …including that it may in fact have happened. "Nothing was changed" here sends them to a+ // retry that hits the 30-day throttle with their one release already spent.+ expect(text).toMatch(/may or may not/)+ // 2. …and is told nothing FALSE about the license. This is the shipped bug: the offline code+ // was merged onto `detail`, so the device-count line was replaced by "Could not read this+ // license right now" while the real key sat in the box directly above it.+ expect(text).not.toMatch(/Could not read this license/)+ expect(text).toContain('2 of 3 devices in use')+ expect((document.querySelector('input[readonly]') as HTMLInputElement).value).toBe('NT-KEY-1')+ // 3. …and the button is usable again, not stuck on "Releasing…".+ expect(text).toContain('Release other devices')+ })++ it('leaves the throttle refusal to the license sentence, with no second voice', async () => {+ await mount(PRO)+ releaseOthers.mockResolvedValue({+ key: null,+ used: 0,+ seats: 0,+ source: null,+ error: 'too_soon',+ retryAfterDays: 12+ })+ await act(async () => click('Release other devices'))+ await act(async () => confirmDialog('Release others'))+ await act(async () => undefined)++ const text = screenText()+ expect(text).toContain('You can release devices again in 12 days.')+ // The refusal rides `detail`; a release note beside it would print the same fact twice in two+ // different wordings.+ expect(text).not.toMatch(/Could not confirm the release/)+ expect(text).not.toMatch(/Could not release the other devices/)+ })++ it('clears the last failure when the release is tried again', async () => {+ await mount(PRO)+ releaseOthers.mockResolvedValue({ key: null, used: 0, seats: 0, source: null, error: 'offline' })+ await act(async () => click('Release other devices'))+ await act(async () => confirmDialog('Release others'))+ await act(async () => undefined)+ expect(screenText()).toMatch(/Could not confirm the release/)++ releaseOthers.mockResolvedValue({ key: null, used: 1, seats: 3, source: null, error: null })+ await act(async () => click('Release other devices'))+ await act(async () => confirmDialog('Release others'))+ await act(async () => undefined)++ // A stale warning over a release that just worked is its own false statement.+ expect(screenText()).not.toMatch(/Could not confirm the release/)+ expect(screenText()).toContain('1 of 3 devices in use')+ })+})++describe('LicenseSection — confirming the destructive actions', () => {+ it('does not release anything until the user confirms, and says what will be released', async () => {+ await mount(PRO)+ await act(async () => click('Release other devices'))++ // One click used to deactivate every other machine AND every paired phone, irreversibly for+ // 30 days, with nothing on screen saying so beforehand.+ expect(releaseOthers).not.toHaveBeenCalled()+ const dialog = screenText()+ expect(dialog).toMatch(/paired phone/)+ expect(dialog).toMatch(/once every 30 days/)+ expect(dialog).toMatch(/this Mac keeps it/)++ await act(async () => confirmDialog('Cancel'))+ expect(releaseOthers).not.toHaveBeenCalled()+ expect(screenText()).not.toMatch(/once every 30 days/)++ await act(async () => click('Release other devices'))+ await act(async () => confirmDialog('Release others'))+ await act(async () => undefined)+ expect(releaseOthers).toHaveBeenCalledTimes(1)+ })++ it('warns to copy the key before deactivating, and deactivates only on confirm', async () => {+ await mount(PRO)+ await act(async () => click('Deactivate on this device'))++ // After deactivating, the detail read has no entitlement to authorize it — the key is+ // unrecoverable in-app, which is exactly the support queue this screen exists to end.+ expect(deactivate).not.toHaveBeenCalled()+ expect(screenText()).toMatch(/Copy your license key first/)++ await act(async () => confirmDialog('Deactivate'))+ expect(deactivate).toHaveBeenCalledTimes(1)+ })++ it('does not tell a license with no key to copy one', async () => {+ // An App Store entitlement: nothing to copy, so that sentence would be nonsense.+ await mount(PRO, { key: null, used: 0, seats: 0, source: 'apple', error: null })+ await act(async () => click('Deactivate on this device'))++ expect(screenText()).not.toMatch(/Copy your license key first/)+ expect(screenText()).toMatch(/Pro features stop here/)+ })+})++describe('LicenseSection — the key field and the paste-elsewhere line', () => {+ it('copies through the app clipboard channel and says it copied', async () => {+ await mount(PRO)+ await act(async () => click('Copy'))++ expect(writeText).toHaveBeenCalledWith('NT-KEY-1')+ expect(screenText()).toContain('Copied')+ })++ it('offers no key field at all when the stated source has none', async () => {+ await mount(PRO, { key: null, used: 0, seats: 0, source: 'apple', error: null })++ const text = screenText()+ // "not available" means "exists, could not be fetched" — beside a sentence that says there is+ // no key at all, the two halves of the first screen an App Store subscriber sees disagree.+ expect(text).not.toContain('not available')+ expect(text).not.toContain('License key')+ expect(document.querySelector('input[readonly]')).toBeNull()+ expect(text).toContain('comes from the App Store subscription on your paired phone')+ })++ it('stops inviting the user to paste the key elsewhere once the cap is full', async () => {+ await mount(PRO, { ...KEYGEN, used: 3, seats: 3 })++ const text = screenText()+ expect(text).toContain('All 3 devices are in use.')+ // The line used to render on `detail.key` alone — directly under that sentence. Following it+ // lands the user on `seat_limit` on the other Mac, which is where this whole task started.+ expect(text).not.toMatch(/paste this key/)+ // The key itself is still shown and copyable; it is the ADVICE that is wrong here.+ expect((document.querySelector('input[readonly]') as HTMLInputElement).value).toBe('NT-KEY-1')+ })++ it('still invites it while there is room', async () => {+ await mount(PRO)+ expect(screenText()).toMatch(/paste this key/)+ })+})++describe('LicenseSection — activation failures', () => {+ it('renders seat_limit as a way out, never as a code', async () => {+ await mount({ ...FREE, error: 'seat_limit' })++ const text = screenText()+ expect(text).not.toContain('seat_limit')+ expect(text).toContain('This license already has all its devices in use.')+ expect(text).toMatch(/Release other devices/)+ })++ it('renders an unknown reason as an apology with an action, not as a code', async () => {+ await mount({ ...FREE, error: 'gremlins' })++ const text = screenText()+ expect(text).not.toContain('gremlins')+ expect(text).toContain('Could not activate this key.')+ })+})diff --git a/src/renderer/components/settings/sections/LicenseSection.tsx b/src/renderer/components/settings/sections/LicenseSection.tsxindex 12bbb74ed..c335693a6 100644--- a/src/renderer/components/settings/sections/LicenseSection.tsx+++ b/src/renderer/components/settings/sections/LicenseSection.tsx@@ -3,10 +3,20 @@ import { useEntitlement } from '../../../state/entitlement'import { SettingsSection } from '../SettingsSection'import { SearchableRow } from '../SearchableRow'import { FieldRow } from '../FieldRow'+import { ConfirmDialog } from '../../ConfirmDialog'import { ProCompare } from './ProCompare'import { Button } from '@renderer/ui/Button'import { Input } from '@renderer/ui/Input'-import { licenseSentence, canReleaseDevices } from '@renderer/lib/licenseCopy'+import {+ licenseSentence,+ canReleaseDevices,+ canUseKeyElsewhere,+ releaseFailureSentence,+ activationErrorSentence+} from '@renderer/lib/licenseCopy'++/** How long the Copy button reports success before returning to its label. */+const COPIED_MS = 1600const ROWS = {license: {@@ -36,7 +46,12 @@ export function LicenseSection({ isActive }: { isActive: boolean }): React.JSX.Econst [licenseKey, setLicenseKey] = useState('')const [upgrading, setUpgrading] = useState(false)const [releasing, setReleasing] = useState(false)- const [releaseFailed, setReleaseFailed] = useState(false)+ const [copied, setCopied] = useState(false)+ const [confirming, setConfirming] = useState<'release' | 'deactivate' | null>(null)+ // The reason code of a release that did not land — NOT a boolean, and NOT merged into `detail`:+ // "offline" and "this Mac is not authorized" owe the user different sentences, and neither of+ // them is a statement about the license the panel is displaying. See `releaseFailureSentence`.+ const [releaseError, setReleaseError] = useState<string | null>(null)// `loadDetail` REJECTS on the Server Edition (`E_UNSUPPORTED` — there is no license layer in// src/server), and the store deliberately does not swallow it. Catching here is not optional:// uncaught, this is an unhandled rejection on every browser session. And what we show there is@@ -49,8 +64,44 @@ export function LicenseSection({ isActive }: { isActive: boolean }): React.JSX.E// eslint-disable-next-line react-hooks/exhaustive-deps}, [ent.isPremium])+ // The receipt yields to a clipboard FAILURE. Only the browser build can fail (the desktop+ // preload writes synchronously and cannot), and it reports that as a `nodeterm:toast` error+ // banner — a green "Copied" beside a red banner is the app contradicting itself in one glance.+ // Same rule as the terminal's copy pill (`terminal/useCopyFeedback.ts`).+ useEffect(() => {+ if (!copied) return+ const timer = setTimeout(() => setCopied(false), COPIED_MS)+ const onToast = (e: Event): void => {+ if ((e as CustomEvent<{ kind?: string }>).detail?.kind === 'error') setCopied(false)+ }+ window.addEventListener('nodeterm:toast', onToast)+ return () => {+ clearTimeout(timer)+ window.removeEventListener('nodeterm:toast', onToast)+ }+ }, [copied])+const detail = detailUnavailable ? null : ent.detailconst sentence = licenseSentence(detail)+ const releaseNote = releaseFailureSentence(releaseError)+ // Read out here, not off `detail` inside the click handler: TypeScript drops a property+ // narrowing at a closure boundary, and the key must not be re-read at click time anyway.+ const keyOnFile = detail?.key ?? null++ const runRelease = (): void => {+ setConfirming(null)+ setReleasing(true)+ setReleaseError(null)+ void ent+ .releaseOthers()+ // Resolves to null when the release landed (or was refused on terms the sentence above+ // already carries), else the reason code. Same uncaught-rejection rule as `loadDetail` —+ // plus an IPC failure here would otherwise leave the button stuck on "Releasing…". A+ // rejection is not a code, so it takes the "we do not know what happened" branch.+ .then((code) => setReleaseError(code))+ .catch(() => setReleaseError('unknown'))+ .finally(() => setReleasing(false))+ }return (<SettingsSectionid="license"@@ -72,60 +123,52 @@ export function LicenseSection({ isActive }: { isActive: boolean }): React.JSX.E</p>{detail ? (<>- <FieldRow- label="License key"- control={- <div className="flex items-center gap-2">- <Input- className="w-64"- readOnly- value={detail.key ?? ''}- placeholder={detail.key ? undefined : 'not available'}- />- <Button- disabled={!detail.key}- onClick={() => {- if (detail.key) void navigator.clipboard.writeText(detail.key)- }}- >- Copy- </Button>- </div>- }- />+ {/* No key ⇒ no field. A row reading "not available" beside a sentence saying there+ IS no key (an App Store subscription, a failed read) contradicts itself on the+ first screen those users ever see — "not available" means "exists, could not be+ fetched". The sentence below is the whole story in every keyless case. */}+ {keyOnFile ? (+ <FieldRow+ label="License key"+ control={+ <div className="flex items-center gap-2">+ <Input className="w-64" readOnly value={keyOnFile} />+ <Button+ onClick={() => {+ // The app's own clipboard channel, not `navigator.clipboard`: it+ // returns void (no unhandled rejection) and the browser bridge raises+ // its own error banner when a copy cannot happen.+ window.nodeTerminal.clipboard.writeText(keyOnFile)+ setCopied(true)+ }}+ >+ {copied ? 'Copied' : 'Copy'}+ </Button>+ </div>+ }+ />+ ) : null}{sentence ? <p className="text-sm text-muted">{sentence}</p> : null}- {detail.key ? (+ {canUseKeyElsewhere(detail) ? (<p className="text-sm text-muted">To use Pro on another Mac, open Settings → License there and paste this key.</p>) : null}{canReleaseDevices(detail) ? (<div className="space-y-2">- <Button- disabled={releasing}- onClick={() => {- setReleasing(true)- setReleaseFailed(false)- void ent- .releaseOthers()- // Same uncaught-rejection rule as `loadDetail` above — plus an ordinary- // IPC failure here would otherwise leave the button stuck on "Releasing…".- .catch(() => setReleaseFailed(true))- .finally(() => setReleasing(false))- }}- >+ <Button disabled={releasing} onClick={() => setConfirming('release')}>{releasing ? 'Releasing…' : 'Release other devices'}</Button>- {releaseFailed ? (+ {releaseNote ? (<p className="text-sm" style={{ color: '#ff9f0a' }}>- Could not release the other devices. Nothing was changed.+ {releaseNote}</p>) : null}</div>) : null}</>) : null}- <Button onClick={() => void ent.deactivate()}>Deactivate on this device</Button>+ <Button onClick={() => setConfirming('deactivate')}>Deactivate on this device</Button></div>) : (<div className="space-y-3">@@ -165,9 +208,12 @@ export function LicenseSection({ isActive }: { isActive: boolean }): React.JSX.E>Activate</Button>+ {/* The server's reason code is never rendered raw. A buyer at the device cap is+ exactly who this screen exists for, and `Could not activate (seat_limit).` is+ a dead end: the word is unsearchable and names no way out. */}{ent.status.error ? (<p className="text-sm" style={{ color: '#ff9f0a' }}>- Could not activate ({ent.status.error}).+ {activationErrorSentence(ent.status.error)}</p>) : null}</div>@@ -175,6 +221,35 @@ export function LicenseSection({ isActive }: { isActive: boolean }): React.JSX.E</div>)}</SearchableRow>++ {/* Both actions are destructive, one-click and hard to undo, so both are confirmed — the+ house pattern (a single phone revoke gets a ConfirmDialog; these are larger). */}+ {confirming === 'release' ? (+ <ConfirmDialog+ message="Release every other device on this license? Your other Macs and every paired phone lose Pro until they are activated again — this Mac keeps it. Devices can only be released once every 30 days."+ confirmLabel="Release others"+ onConfirm={runRelease}+ onCancel={() => setConfirming(null)}+ />+ ) : null}+ {confirming === 'deactivate' ? (+ <ConfirmDialog+ // Deactivating clears the stored entitlement, and with it the only in-app copy of the+ // key: the detail read that produced it needs that entitlement to authorize. Without+ // this sentence the buyer is back in the support queue this whole screen exists to end.+ message={+ keyOnFile+ ? 'Deactivate Pro on this Mac? Copy your license key first — it is shown here only while Pro is active, and you need it to activate again.'+ : 'Deactivate Pro on this Mac? Pro features stop here until this device is activated again.'+ }+ confirmLabel="Deactivate"+ onConfirm={() => {+ setConfirming(null)+ void ent.deactivate()+ }}+ onCancel={() => setConfirming(null)}+ />+ ) : null}</SettingsSection>)}diff --git a/src/renderer/lib/licenseCopy.test.ts b/src/renderer/lib/licenseCopy.test.tsindex 0e243dd95..453cf454b 100644--- a/src/renderer/lib/licenseCopy.test.ts+++ b/src/renderer/lib/licenseCopy.test.ts@@ -1,6 +1,13 @@import { describe, it, expect } from 'vitest'import type { LicenseDetail } from '@shared/types'-import { licenseSentence, canReleaseDevices } from './licenseCopy'+import {+ licenseSentence,+ canReleaseDevices,+ canUseKeyElsewhere,+ isReleaseRefusal,+ releaseFailureSentence,+ activationErrorSentence+} from './licenseCopy'// `detail.error` carries TWO families and only the code word separates them: a read that FAILED// (its counts are placeholder zeros) and a release that was REFUSED (its counts are the last good@@ -81,10 +88,10 @@ describe('licenseSentence — sources that have no key and no device count', ()describe('licenseSentence — a read that FAILED', () => {// Every code in this family arrives with placeholder zeros and a null key.- const failures = ['unauthorized', 'inactive', 'offline', 'disabled', 'network'] as const+ const couldNotLook = ['offline', 'disabled', 'network'] as constconst FAILED = 'Could not read this license right now, so the key and device count are unknown. Your Pro access is unaffected.'- for (const error of failures) {+ for (const error of couldNotLook) {it(`renders "${error}" as a failed read, never as a device count`, () => {const s = licenseSentence({ key: null, used: 0, seats: 0, source: null, error })expect(s).toBe(FAILED)@@ -94,6 +101,37 @@ describe('licenseSentence — a read that FAILED', () => {})}+ // "Your Pro access is unaffected." is a PROMISE ABOUT THE FUTURE, and only these three codes back+ // it: we never got to look, so nothing about the license changed. The two below are answers.+ it('does not promise Pro is unaffected when the server said the license is inactive', () => {+ const s = licenseSentence({ key: null, used: 0, seats: 0, source: null, error: 'inactive' })+ expect(s).toBe(+ 'This license is not active, so there is no key or device count to show — and Pro on this Mac will stop when its current entitlement expires.'+ )+ // A suspended/refunded license DOES drop Pro at the next refresh — the old shared sentence+ // told that user the opposite, in the one place they came to find out.+ expect(s).not.toContain('unaffected')+ expect(s).not.toContain('0 of 0')+ })++ it('does not promise Pro is unaffected when this Mac was refused', () => {+ const s = licenseSentence({ key: null, used: 0, seats: 0, source: null, error: 'unauthorized' })+ expect(s).toBe(+ 'This Mac is not authorized on this license, so the key and device count are unavailable — and Pro here may stop when its current entitlement expires.'+ )+ expect(s).not.toContain('unaffected')+ // "may", not "will": a later refresh can re-mint. Overstating is the other half of the lie.+ expect(s).toContain('may stop')+ })++ it('makes no promise at all for a code it does not recognize', () => {+ // A reason word the server grew after this build shipped. Saying "unaffected" would be a+ // guess about a state we cannot read; saying nothing more than what happened is not.+ const s = licenseSentence({ key: null, used: 0, seats: 0, source: null, error: 'teapot' })+ expect(s).toBe('Could not read this license right now, so the key and device count are unknown.')+ expect(s).not.toContain('unaffected')+ })+it('still renders the failure when the failed read carried a source and stale-looking counts', () => {// ORDERING PIN: if the `source` check ran before the `error` check, this would render the// keygen usage sentence over a read that never came back — a fabricated device count.@@ -188,3 +226,138 @@ describe('canReleaseDevices', () => {expect(canReleaseDevices(keygen({ error: 'too_soon', retryAfterDays: 12 }))).toBe(true)})})++describe('canUseKeyElsewhere', () => {+ it('is true while the license still has room', () => {+ expect(canUseKeyElsewhere(keygen({ used: 2, seats: 3 }))).toBe(true)+ })++ it('is false AT the cap — the activation it invites would be refused', () => {+ // This line used to render under "All 3 devices are in use": we told the user to go and paste+ // the key on another Mac, where the server answers seat_limit. Advice that cannot work.+ expect(canUseKeyElsewhere(keygen({ used: 3, seats: 3 }))).toBe(false)+ })++ it('is false OVER the cap (a cap lowered after activation)', () => {+ // `used > seats` is further from having room, not closer. A `!==` or a `used === seats` check+ // reads it as "not at the cap" and shows the line again.+ expect(canUseKeyElsewhere(keygen({ used: 4, seats: 3 }))).toBe(false)+ })++ it('is false with no key to paste, whatever the counts say', () => {+ expect(canUseKeyElsewhere(keygen({ key: null, used: 0, seats: 3 }))).toBe(false)+ expect(canUseKeyElsewhere(null)).toBe(false)+ })+})++describe('isReleaseRefusal — which codes are about the LICENSE', () => {+ it('is true for exactly the two the release route answers about the license itself', () => {+ expect(isReleaseRefusal('too_soon')).toBe(true)+ expect(isReleaseRefusal('not_applicable')).toBe(true)+ })++ it('is false for every transport / standing code', () => {+ // These are the codes the release route ALSO produces (core/license.ts). Treating them as+ // refusals is what merged an offline release onto `detail` and rendered it as a failed READ,+ // with a real key sitting in the box above it.+ for (const code of ['unauthorized', 'inactive', 'offline', 'disabled', 'network', 'teapot']) {+ expect(isReleaseRefusal(code), code).toBe(false)+ }+ })++ it('is false for "no error at all"', () => {+ expect(isReleaseRefusal(null)).toBe(false)+ expect(isReleaseRefusal(undefined)).toBe(false)+ expect(isReleaseRefusal('')).toBe(false)+ })+})++describe('releaseFailureSentence', () => {+ it('says nothing when the release did not fail', () => {+ expect(releaseFailureSentence(null)).toBe('')+ expect(releaseFailureSentence(undefined)).toBe('')+ })++ it('says nothing for a refusal — those ride the detail and licenseSentence owns them', () => {+ // Two owners for one message would print the throttle twice, in two different wordings.+ expect(releaseFailureSentence('too_soon')).toBe('')+ expect(releaseFailureSentence('not_applicable')).toBe('')+ })++ it('states that nothing was released when the server ANSWERED and refused', () => {+ expect(releaseFailureSentence('unauthorized')).toBe(+ 'Could not release the other devices — this Mac is not authorized on this license. Nothing was released.'+ )+ expect(releaseFailureSentence('inactive')).toBe(+ 'Could not release the other devices — this license is not active. Nothing was released.'+ )+ expect(releaseFailureSentence('disabled')).toBe(+ 'Could not release the other devices — license requests are switched off in this build. Nothing was released.'+ )+ })++ it('does NOT claim nothing happened when the reply was merely lost', () => {+ // The request may have landed and only the answer gone missing. "Nothing was changed" sends+ // the user to a retry that hits the 30-day throttle, having already spent their one release.+ for (const code of ['offline', 'network', 'teapot']) {+ const s = releaseFailureSentence(code)+ expect(s, code).not.toContain('Nothing was released')+ expect(s, code).toContain('may or may not')+ // …and it must say what to do next, including the cost of the ambiguity.+ expect(s, code).toContain('30 days')+ }+ })++ it('never renders the bare code', () => {+ for (const code of ['unauthorized', 'inactive', 'disabled', 'offline', 'network', 'teapot']) {+ // Same rule as the activation copy: what would read as machine output is the snake_case+ // shape, and none of these sentences may carry one.+ expect(releaseFailureSentence(code), code).not.toMatch(/[a-z]+_[a-z]+/)+ }+ })+})++describe('activationErrorSentence', () => {+ it('says nothing when the activation did not fail', () => {+ expect(activationErrorSentence(null)).toBe('')+ expect(activationErrorSentence('')).toBe('')+ })++ it('turns seat_limit into the remedy, and points it at a machine that HAS Pro', () => {+ // The flow this whole feature exists for. It used to dead-end in `Could not activate+ // (seat_limit).` — a word the buyer cannot look up, on the screen where they are stuck.+ const s = activationErrorSentence('seat_limit')+ expect(s).toBe(+ 'This license already has all its devices in use. On a Mac (or phone) where Pro is active, open Settings → License and choose “Release other devices”, then activate here again.'+ )+ // The release action does not exist on THIS machine (it has no Pro yet), so the sentence must+ // send the user elsewhere — advice to "release below" would point at a button that isn't there.+ expect(s).toContain('where Pro is active')+ })++ it('gives every other named code its own sentence, none of them a code', () => {+ const codes = ['suspended', 'expired', 'not_found', 'invalid', 'offline', 'network', 'disabled']+ const seen = new Set<string>()+ for (const code of codes) {+ const s = activationErrorSentence(code)+ expect(s, code).not.toBe('')+ // A raw reason code is snake_case; English is not. `not.toContain(code)` cannot be used for+ // codes that are also ordinary words ("suspended", "expired"), and this catches the ones+ // that would actually read as machine output.+ expect(s, code).not.toMatch(/[a-z]+_[a-z]+/)+ // Not one apology reused for everything: a shared string would tell an expired license and+ // an offline laptop the same untrue thing.+ seen.add(s)+ }+ // offline and network are deliberately ONE sentence (both mean "we could not check"), so six.+ expect(seen.size).toBe(codes.length - 1)+ })++ it('falls back to an actionable sentence for a code it does not know, printing no code', () => {+ const s = activationErrorSentence('gremlins')+ expect(s).toBe(+ 'Could not activate this key. Check it was pasted in full and try again — get in touch if it keeps failing.'+ )+ expect(s).not.toContain('gremlins')+ })+})diff --git a/src/renderer/lib/licenseCopy.ts b/src/renderer/lib/licenseCopy.tsindex 645b2d792..5af900960 100644--- a/src/renderer/lib/licenseCopy.ts+++ b/src/renderer/lib/licenseCopy.ts@@ -4,16 +4,24 @@ import type { LicenseDetail } from '@shared/types'* Settings → License wording, derived from the data in ONE place so a sentence cannot promise* something the numbers do not say.*- * Two facts shape every branch below:+ * Three facts shape the branches below:*- * 1. **`error` carries TWO families and only the code word separates them.** A READ that failed- * (`unauthorized` | `inactive` | `offline` | `disabled` | `network`) arrives with placeholder- * zeros and a null key — rendering those as a device count is the bug this module exists to- * prevent. A refused RELEASE (`too_soon` | `not_applicable`) rides on top of the LAST GOOD- * read, so its key, source and counts are real; telling that user "could not read your- * license" would be equally wrong in the other direction. Hence: error first, then which- * family, then the source.- * 2. **Seats and devices are the same thing by design**, so the copy says "devices" and names+ * 1. **A reason code is either about the LICENSE or about the CALL, and both arrive in the same+ * `error` field.** A refused RELEASE (`too_soon` | `not_applicable`) is about the license: it+ * rides on top of the LAST GOOD read, so its key, source and counts are real, and it belongs+ * beside them. Everything else — `unauthorized` | `inactive` | `offline` | `disabled` |+ * `network` — is about a call that did not deliver, and the route it failed on decides what to+ * say: on a READ it means the key and counts are unknown, on a RELEASE it means the action did+ * not happen (and, offline, may or may not have). The store therefore never merges a release's+ * transport failure onto `detail` (it hands the code back instead), and `releaseFailureSentence`+ * is the one place that speaks for it. `isReleaseRefusal` is the shared split so the store and+ * the panel cannot disagree about which family a code is in.+ * 2. **"Your Pro access is unaffected" is a forward-looking promise, so only codes that back it may+ * say it.** `offline`/`network`/`disabled` mean we could not look — the entitlement is verified+ * locally and nothing changed. `inactive`/`unauthorized` are ANSWERS that this license is not in+ * good standing, and the very next refresh may drop Pro; telling that user they are unaffected+ * is the same class of lie as rendering a placeholder zero as a device count.+ * 3. **Seats and devices are the same thing by design**, so the copy says "devices" and names* phones explicitly — a paired phone holds a seat too, and a user who does not know that reads* the cap as broken.*/@@ -21,7 +29,7 @@ export function licenseSentence(detail: LicenseDetail | null): string {if (!detail) return '' // Before the first read there is nothing to say.if (detail.error) {- // --- Family 2 first: the read was FINE, the action was refused. -----------------------------+ // --- The read was FINE, the release was refused on terms about the license itself. ----------if (detail.error === 'too_soon') {const days = detail.retryAfterDays// No `?? 30` fallback: a window the server never stated is a date the user would plan@@ -39,11 +47,28 @@ export function licenseSentence(detail: LicenseDetail | null): string {return 'Releasing devices does not apply to this license.'}- // --- Family 1: the READ failed. The counts beside this are placeholders, not a measurement. --- // Deliberately not "could not reach the server": `unauthorized` / `inactive` / `disabled` are- // answers we DID receive. What is true across the whole family is that we do not know the key- // or the count — and that Pro keeps working either way (the entitlement is verified locally).- return 'Could not read this license right now, so the key and device count are unknown. Your Pro access is unaffected.'+ // --- The READ failed. The counts beside this are placeholders, not a measurement. -----------+ // A RELEASE failure never reaches here: the store keeps those off `detail` (see the module doc+ // and `isReleaseRefusal`), because "could not read this license" printed over a real key and+ // real counts is false in both halves.+ if (detail.error === 'inactive') {+ // A server ANSWER, not a failure to look. Pro is verified locally so it still works right+ // now, and saying "unaffected" would promise it keeps working — which it will not.+ return 'This license is not active, so there is no key or device count to show — and Pro on this Mac will stop when its current entitlement expires.'+ }+ if (detail.error === 'unauthorized') {+ // Also an answer: the server refused this Mac's entitlement. It may recover on the next+ // refresh, hence "may" — but it is not the "nothing changed" story the codes below tell.+ return 'This Mac is not authorized on this license, so the key and device count are unavailable — and Pro here may stop when its current entitlement expires.'+ }+ if (detail.error === 'offline' || detail.error === 'network' || detail.error === 'disabled') {+ // Deliberately not "could not reach the server": `disabled` is a build that never asked.+ // What is true across these three is that we did not get to LOOK — and that Pro keeps+ // working either way, because the entitlement is verified locally.+ return 'Could not read this license right now, so the key and device count are unknown. Your Pro access is unaffected.'+ }+ // An unrecognized code. Say the part that is certainly true and make no promise we cannot back.+ return 'Could not read this license right now, so the key and device count are unknown.'}// --- A clean read. What can be said depends entirely on the source the SERVER stated. ---------@@ -88,3 +113,91 @@ export function licenseSentence(detail: LicenseDetail | null): string {export function canReleaseDevices(detail: LicenseDetail | null): boolean {return detail?.source === 'keygen'}++/**+ * Whether to tell the user they can paste this key on another Mac.+ *+ * A key with no free device is an invitation to an activation that CANNOT succeed — the server+ * answers `seat_limit` and the user is left holding a key and an error. So the line appears only+ * while the license has room. `used > seats` (a cap lowered after activation) is over the cap, not+ * under it, and is excluded by the same comparison.+ */+export function canUseKeyElsewhere(detail: LicenseDetail | null): boolean {+ return !!detail?.key && detail.used < detail.seats+}++/**+ * Is this reason code a REFUSAL of the release (about the license), rather than a failure of the+ * call (about the network / this Mac's standing)?+ *+ * The store asks this to decide what may be merged onto `detail`, and the panel's release note is+ * the complement of it. One definition, because two copies of "which codes are refusals" is+ * exactly how a transport failure ended up rendered as "could not read this license".+ */+export function isReleaseRefusal(code: string | null | undefined): boolean {+ return code === 'too_soon' || code === 'not_applicable'+}++/**+ * What to tell the user when "Release other devices" did not deliver.+ *+ * Two families, and conflating them is the whole point of this function existing:+ * - the server ANSWERED and refused (`unauthorized` | `inactive`) or we never asked (`disabled`)+ * ⇒ nothing was released, and we can say so.+ * - the reply never arrived (`offline` | `network`, and any code we do not recognize) ⇒ the+ * request may well have LANDED. Claiming "nothing was changed" there sends the user to a retry+ * that hits the 30-day throttle, having already spent their release.+ *+ * A refusal code returns '' — those ride `detail` and `licenseSentence` speaks for them. One owner+ * per message; two would print the throttle twice.+ */+export function releaseFailureSentence(code: string | null | undefined): string {+ if (!code || isReleaseRefusal(code)) return ''+ if (code === 'unauthorized') {+ return 'Could not release the other devices — this Mac is not authorized on this license. Nothing was released.'+ }+ if (code === 'inactive') {+ return 'Could not release the other devices — this license is not active. Nothing was released.'+ }+ if (code === 'disabled') {+ return 'Could not release the other devices — license requests are switched off in this build. Nothing was released.'+ }+ return 'Could not confirm the release — the server could not be reached, so the other devices may or may not have been released. Close and reopen Settings to see the current device count; if the release did land, the next one is only possible after 30 days.'+}++/**+ * What to tell someone whose key would not activate.+ *+ * The codes come from the server verbatim (`core/license.ts` keeps them), and rendering them+ * verbatim is what left the flow this whole feature exists for — a buyer at the device cap —+ * dead-ended in `Could not activate (seat_limit).` Every branch below names an ACTION; the+ * fallback names one too, and never prints the code, because a word the user cannot look up is+ * worse than a plain apology.+ */+export function activationErrorSentence(code: string | null | undefined): string {+ if (!code) return ''+ if (code === 'seat_limit') {+ // The one code this feature was built around. The remedy lives on a machine that HAS Pro —+ // this one does not, so "release devices here" would be advice the user cannot follow.+ return 'This license already has all its devices in use. On a Mac (or phone) where Pro is active, open Settings → License and choose “Release other devices”, then activate here again.'+ }+ if (code === 'suspended') {+ return 'This license has been suspended, so it cannot be activated. Get in touch and we will sort it out.'+ }+ if (code === 'expired') {+ return 'This license has expired. Renew it and then activate again.'+ }+ if (code === 'not_found') {+ return 'No license was found for that key. Check it was pasted in full, or copy it again from your purchase email.'+ }+ if (code === 'invalid') {+ return 'That is not a valid license key. Check it was pasted in full, or copy it again from your purchase email.'+ }+ if (code === 'offline' || code === 'network') {+ return 'Could not reach the server, so the key could not be checked. Check your connection and try again.'+ }+ if (code === 'disabled') {+ return 'License activation is switched off in this build.'+ }+ return 'Could not activate this key. Check it was pasted in full and try again — get in touch if it keeps failing.'+}diff --git a/src/renderer/state/entitlement.test.ts b/src/renderer/state/entitlement.test.tsindex 05dabb7e1..103dec5e1 100644--- a/src/renderer/state/entitlement.test.ts+++ b/src/renderer/state/entitlement.test.ts@@ -2,10 +2,15 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'import type { LicenseDetail, NodeTerminalApi } from '@shared/types'// The license routes answer two DIFFERENT shapes, and that asymmetry is what these tests are about:-// `detail` states every field, while `release` answers with COUNTS ONLY — no key, no source (and a-// FAILED release changed nothing on the server at all). So the store replaces on the first and-// merges on the second; getting that backwards silently blanks the key the user came to copy, or-// renders "0 of 0 devices" from a call that never ran.+// `detail` states every field, while `release` answers with COUNTS ONLY — no key, no source. So the+// store replaces on the first and merges on the second; getting that backwards silently blanks the+// key the user came to copy, or renders "0 of 0 devices" from a call that never ran.+//+// The release's ERROR is split a second time, and that split is the other half of this file: a+// refusal (`too_soon` / `not_applicable`) is a fact about the license and rides `detail`; anything+// else is a fact about the CALL, is handed back to the caller, and must leave `detail` alone. Note+// what is NOT claimed anywhere below: that a failed release changed nothing on the server. For+// `offline`/`network` the request may well have landed and only the reply been lost.const detail = vi.fn<() => Promise<LicenseDetail>>()const releaseOthers = vi.fn<() => Promise<LicenseDetail>>()@@ -49,7 +54,7 @@ describe('entitlement store — detail read vs release merge', () => {// The wire's answer to a successful release: counts only.releaseOthers.mockResolvedValue({ ...ZEROS, used: 1, seats: 3, error: null })- await useEntitlement.getState().releaseOthers()+ expect(await useEntitlement.getState().releaseOthers()).toBeNull()const d = useEntitlement.getState().detail!// The key is the ORIGINAL string — not merely truthy, and not absent. A merge that wrote the@@ -66,7 +71,9 @@ describe('entitlement store — detail read vs release merge', () => {await useEntitlement.getState().loadDetail()releaseOthers.mockResolvedValue({ ...ZEROS, error: 'too_soon', retryAfterDays: 12 })- await useEntitlement.getState().releaseOthers()+ // Null: a refusal is a fact about the license, it rides `detail`, and licenseSentence speaks+ // for it. Returning it here as well would print the throttle twice, in two wordings.+ expect(await useEntitlement.getState().releaseOthers()).toBeNull()const d = useEntitlement.getState().detail!// Specifically the PRE-release values: 3, not 0. "Kept the old detail" and "wrote the reply's@@ -78,6 +85,48 @@ describe('entitlement store — detail read vs release merge', () => {expect(d.retryAfterDays).toBe(12)})+ it('a release that FAILED leaves the detail untouched and hands the code back', async () => {+ const useEntitlement = await freshStore()+ detail.mockResolvedValue(LOADED)+ await useEntitlement.getState().loadDetail()++ // Pressing "Release other devices" on a laptop that just lost wifi. Before this split, the+ // 'offline' code was merged onto `detail` and the panel replaced the device-count line with+ // "Could not read this license right now…" — while the real key sat in the box above it and+ // nothing on screen mentioned the release at all.+ releaseOthers.mockResolvedValue({ ...ZEROS, error: 'offline' })+ expect(await useEntitlement.getState().releaseOthers()).toBe('offline')++ // Byte for byte the last good read: not the reply's zeros, and not the last read plus an+ // `error`. An implementation that merges the code and ALSO returns it passes a bare+ // "returns the code" assertion and still shows the user a failed-read sentence.+ expect(useEntitlement.getState().detail).toEqual(LOADED)+ })++ it('does the same for every non-refusal code the release route can answer', async () => {+ const useEntitlement = await freshStore()+ detail.mockResolvedValue(LOADED)+ await useEntitlement.getState().loadDetail()++ // core/license.ts produces all of these on the release route too — the module doc that named+ // only too_soon/not_applicable was wrong about its own seam, which is how this shipped.+ for (const error of ['unauthorized', 'inactive', 'disabled', 'network']) {+ releaseOthers.mockResolvedValue({ ...ZEROS, error })+ expect(await useEntitlement.getState().releaseOthers(), error).toBe(error)+ expect(useEntitlement.getState().detail, error).toEqual(LOADED)+ }+ })++ it('a failed release with nothing read yet leaves detail null rather than inventing zeros', async () => {+ const useEntitlement = await freshStore()+ releaseOthers.mockResolvedValue({ ...ZEROS, error: 'offline' })++ expect(await useEntitlement.getState().releaseOthers()).toBe('offline')+ // Merging over EMPTY_DETAIL here would publish "0 of 0 devices, no key" as the license's+ // state, produced entirely by a call that never reached the server.+ expect(useEntitlement.getState().detail).toBeNull()+ })+it('a 400 not_applicable likewise does not zero the counts', async () => {const useEntitlement = await freshStore()detail.mockResolvedValue(LOADED)diff --git a/src/renderer/state/entitlement.ts b/src/renderer/state/entitlement.tsindex 61f8b09e3..767737f69 100644--- a/src/renderer/state/entitlement.ts+++ b/src/renderer/state/entitlement.ts@@ -1,5 +1,6 @@import { create } from 'zustand'import type { LicenseDetail, LicenseStatus } from '@shared/types'+import { isReleaseRefusal } from '@renderer/lib/licenseCopy'interface EntitlementState {status: LicenseStatus@@ -11,7 +12,8 @@ interface EntitlementState {/*** The license key + device usage, or null before the first read.*- * **`detail.error` carries TWO different facts, and only the code word separates them:**+ * **`detail.error` here means ONE thing: the last DETAIL READ, or a release refusal about the+ * license itself.** Only two kinds of code can be in it:* - **The read failed** — `unauthorized` | `inactive` | `offline` | `disabled` | `network`.* Everything beside it is a placeholder: the zeros are NOT a device count and the null key is* not "no key". Render the failure, never the numbers.@@ -20,6 +22,11 @@ interface EntitlementState {* `source` and the counts are real and worth showing — say the action was refused, not that* the license could not be read. (The counts are the last good read's; if nothing was ever* read successfully they are still EMPTY_DETAIL's zeros, so call `loadDetail` first.)+ *+ * A release that failed for any OTHER reason never lands here — `releaseOthers` hands that code+ * back to its caller instead. It said nothing about the license, and merging it made the panel+ * replace a real key and real counts with "could not read this license", while saying nothing+ * about the action the user had just pressed.*/detail: LicenseDetail | nullhydrate(): Promise<void>@@ -34,9 +41,18 @@ interface EntitlementState {* layer in `src/server`), and neither this nor `releaseOthers` catches it. A caller that fires* this on mount must `.catch(…)`, or it is an unhandled rejection on every browser session. */loadDetail(): Promise<void>- /** Deactivate every other device on this license, then fold the new counts into `detail`.- * Rejects on the Server Edition exactly like `loadDetail` — see there. */- releaseOthers(): Promise<void>+ /**+ * Deactivate every other device on this license, then fold the new counts into `detail`.+ *+ * Resolves to `null` when the release landed, or when the server refused it on terms `detail`+ * can carry (`too_soon` / `not_applicable` — merged onto the last good read, where+ * `licenseSentence` speaks for them). Any OTHER reason code is resolved AS the value and+ * `detail` is left exactly as it was: that code is about the call, not the license, so only the+ * caller — which knows a release was attempted — can say anything true about it.+ *+ * Rejects on the Server Edition exactly like `loadDetail` — see there.+ */+ releaseOthers(): Promise<string | null>}const EMPTY: LicenseStatus = { tier: null, active: false, expiresAt: null, seats: 0, error: null }@@ -77,15 +93,22 @@ export const useEntitlement = create<EntitlementState>((set, get) => {async releaseOthers() {const r = await window.nodeTerminal.license.releaseOthers()const prev = get().detail ?? EMPTY_DETAIL+ // A release that did not land tells us nothing about the license, and for `offline`/`network`+ // it does not even tell us the server did nothing — the request may have arrived and only+ // the reply been lost. So `detail` keeps the last good read untouched (its key and counts are+ // still the best thing we know) and the code goes back to the caller, which is the only+ // place that knows a RELEASE was pressed and can say so.+ if (r.error && !isReleaseRefusal(r.error)) return r.error// The release route answers with COUNTS ONLY — no key, no source. Replacing `detail`// wholesale would blank the key the user came to this screen to copy, and drop the source- // that decides whether this action is offered at all. And a FAILED release changed nothing- // on the server, so its zeroed counts must not land either: only the reason code rides.+ // that decides whether this action is offered at all. A refusal carries no counts either+ // (its zeros are placeholders), so only its reason code rides.set({detail: r.error? { ...prev, error: r.error, retryAfterDays: r.retryAfterDays }: { ...prev, used: r.used, seats: r.seats, error: null, retryAfterDays: undefined }})+ return null}}})