diff --git a/packages/client/ui-cli-account/package.json b/packages/client/ui-cli-account/package.json index 996ff82e14..134a5c9554 100644 --- a/packages/client/ui-cli-account/package.json +++ b/packages/client/ui-cli-account/package.json @@ -44,10 +44,12 @@ "@deepseek-ai/dsh-api-remotes": "workspace:*", "@deepseek-ai/dsh-cli-account": "workspace:*", "@deepseek-ai/dsh-client-store": "workspace:*", + "@deepseek-ai/dsh-client-test-runtime": "workspace:*", "@deepseek-ai/dsh-client-ui-plugin-manager": "workspace:*", "@deepseek-ai/dsh-client-ui-primitives": "workspace:*", "@deepseek-ai/dsh-client-ui-slots": "workspace:*", "@deepseek-ai/dsh-typert-protocol": "workspace:*", + "@testing-library/react": "^16.3.3", "@types/react": "~18.3.1", "react": "^18.2.0", "react-dom": "^18.2.0" diff --git a/packages/client/ui-cli-account/tests/components.client.spec.tsx b/packages/client/ui-cli-account/tests/components.client.spec.tsx new file mode 100644 index 0000000000..2f37df5037 --- /dev/null +++ b/packages/client/ui-cli-account/tests/components.client.spec.tsx @@ -0,0 +1,161 @@ +// @vitest-environment jsdom +/** The section, tag, activation prompt, confirmation, and notice render a plugin's display phase with the copy it translates. */ +import { cleanup, fireEvent, render, screen } from '@testing-library/react' +import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' +import type { PluginPackageRef, PluginsSubject } from '@deepseek-ai/dsh-client-ui-plugin-manager/client' +import { afterEach, expect, it, vi } from 'vitest' +import { + CliAccountActivation, CliAccountBadge, CliAccountConfirm, CliAccountSection, CliAccountToast, + type CliAccountKey, type CliAccountPhase, type CliAccountSectionProps, +} from '../src/client/components.tsx' +import { apply as applyClient } from '../src/client/index.ts' +import { apply as applyHost } from '../src/index.ts' + +afterEach(cleanup) + +const PACKAGE = '@acme/fixture' + +const copy: Record = { + 'section.title': 'Fixture account', + hint: 'Shared with the terminal.', + close: 'Close', + 'action.cancel': 'Cancel', + 'action.connect': 'Connect', + 'activation.title': 'Connect Fixture', + 'activation.body': 'The plugin is on.', + 'activation.later': 'Later', + 'failure.details': 'Diagnostic: {details}', + 'failure.exitCode': 'exit {code}', + 'badge.connecting': 'Tag connecting', + 'badge.connected': 'Tag connected', + 'badge.disconnected': 'Tag disconnected', + 'badge.unavailable': 'Tag unavailable', + 'badge.stopped': 'Tag stopped', + 'status.checking': 'Checking', + 'status.connected': 'Connected', + 'status.disconnected': 'Not connected', + 'status.unavailable': 'Cannot confirm', + 'status.stopped': 'Not running', + 'notice.connected': 'Fixture connected', + 'notice.action-failed': 'Try again', +} +const t = makeTranslate(copy) +const button = (name: string) => screen.getByRole('button', { name }) + +function section(props: Partial = {}) { + return +} + +it('labels each phase from the shared copy unless the plugin passes a step', () => { + const { container, rerender } = render(section()) + expect(screen.getByText('Fixture account')).toBeTruthy() + expect(screen.getByText('Not connected')).toBeTruthy() + expect(screen.getByText('Shared with the terminal.')).toBeTruthy() + expect(container.querySelector('[data-cli-account="disconnected"][data-cli-account-package="@acme/fixture"]')).toBeTruthy() + rerender(section({ phase: 'connecting' })) + expect(screen.getByText('Checking')).toBeTruthy() + rerender(section({ phase: 'connecting', status: 'Step 1' })) + expect(screen.getByText('Step 1')).toBeTruthy() +}) + +it('renders the plugin buttons, detail, notes, and children, and disables buttons while acting or offline', () => { + const connect = vi.fn() + const replace = vi.fn() + const props: Partial = { + actions: [{ label: 'Link', onClick: connect, variant: 'primary' }, { label: 'Retry', onClick: vi.fn() }], + detail: 'Link an app first.', + notes: [{ text: 'App: cli_a', action: { label: 'Change', onClick: replace, variant: 'ghost' } }, { text: 'Plain note' }], + children: child, + } + const { rerender } = render(section(props)) + expect(screen.getByText('Link an app first.')).toBeTruthy() + expect(screen.getByText('Plain note')).toBeTruthy() + expect(screen.getByText('child')).toBeTruthy() + fireEvent.click(button('Link')) + fireEvent.click(button('Change')) + expect(connect).toHaveBeenCalledOnce() + expect(replace).toHaveBeenCalledOnce() + + const disabled = (): boolean[] => screen.getAllByRole('button').map(element => (element as HTMLButtonElement).disabled) + rerender(section({ ...props, busy: true })) + expect(disabled()).toEqual([true, true, true]) + rerender(section({ ...props, linked: false })) + expect(disabled()).toEqual([true, true, true]) + rerender(section({ ...props, linked: false, phase: 'stopped' })) + expect(disabled()).toEqual([false, false, false]) +}) + +it.each<[string, CliAccountSectionProps['failure'], string]>([ + ['the failed command, exit code, and plugin details', { text: 'Failed.', command: { command: 'login', exitCode: 3 }, details: ['internal', undefined, 'sdk_error'] }, 'Failed. Diagnostic: login · exit 3 · internal · sdk_error'], + ['a command that produced no exit', { text: 'Failed.', command: { command: 'status', exitCode: null } }, 'Failed. Diagnostic: status'], + ['a failure without a command', { text: 'Failed.', command: undefined }, 'Failed.'], +])('reports %s', (_name, failure, expected) => { + render(section({ failure })) + expect(screen.getByRole('alert').textContent).toBe(expected) +}) + +it('tags only the enabled bundle with a settled phase', () => { + const pkg = (name: string, enabled = true): PluginPackageRef => ({ name, installed: true, availability: 'profile', official: false, enabled, rows: [] }) + const badge = (subject: PluginsSubject, phase: CliAccountPhase = 'connected') => + + const { rerender } = render(badge({ kind: 'bundle', pkg: pkg(PACKAGE) })) + expect(screen.getByText('Tag connected')).toBeTruthy() + rerender(badge({ kind: 'bundle', pkg: pkg(PACKAGE) }, 'unavailable')) + expect(screen.getByText('Tag unavailable')).toBeTruthy() + const hidden: PluginsSubject[] = [ + { kind: 'bundle', pkg: pkg(PACKAGE, false) }, + { kind: 'bundle', pkg: pkg('@acme/other') }, + { kind: 'item', id: 'marketplace' }, + ] + for (const subject of hidden) { + rerender(badge(subject)) + expect(document.body.textContent).toBe('') + } + rerender(badge({ kind: 'bundle', pkg: pkg(PACKAGE) }, 'checking')) + expect(document.body.textContent).toBe('') +}) + +it('prompts to connect only while disconnected and steps aside once the phase settles elsewhere', () => { + const onDismiss = vi.fn() + const onConnect = vi.fn() + const prompt = (phase: CliAccountPhase) => + const { rerender } = render(prompt('checking')) + expect(screen.queryByRole('dialog')).toBeNull() + expect(onDismiss).not.toHaveBeenCalled() + rerender(prompt('disconnected')) + expect(screen.getByRole('dialog', { name: 'Connect Fixture' })).toBeTruthy() + expect(screen.getByText('The plugin is on.')).toBeTruthy() + fireEvent.click(button('Connect')) + expect(onConnect).toHaveBeenCalledOnce() + fireEvent.click(button('Later')) + expect(onDismiss).toHaveBeenCalledOnce() + rerender(prompt('connected')) + expect(onDismiss).toHaveBeenCalledTimes(2) +}) + +it('confirms an action only after the user accepts it', () => { + const onClose = vi.fn() + const onConfirm = vi.fn() + render() + expect(screen.getByText('This signs out the terminal too.')).toBeTruthy() + fireEvent.click(button('Cancel')) + expect(onConfirm).not.toHaveBeenCalled() + fireEvent.click(button('Sign out')) + expect(onClose).toHaveBeenCalledTimes(2) + expect(onConfirm).toHaveBeenCalledOnce() +}) + +it('shows the latest notice with the success or failure tone', () => { + const onDone = vi.fn() + const { rerender } = render( t={t} notice={undefined} onDone={onDone} />) + expect(document.body.textContent).toBe('') + rerender( t={t} notice={{ seq: 1, kind: 'connected' }} onDone={onDone} />) + expect(screen.getByText('Fixture connected')).toBeTruthy() + rerender( t={t} notice={{ seq: 2, kind: 'action-failed' }} onDone={onDone} />) + expect(screen.getByText('Try again')).toBeTruthy() +}) + +it('mounts as a module row with no Host or browser behavior of its own', () => { + expect(applyHost()).toBeUndefined() + expect(applyClient()).toBeUndefined() +}) diff --git a/packages/client/ui-cli-account/tests/connection.client.spec.ts b/packages/client/ui-cli-account/tests/connection.client.spec.ts new file mode 100644 index 0000000000..bdc6c59c6d --- /dev/null +++ b/packages/client/ui-cli-account/tests/connection.client.spec.ts @@ -0,0 +1,195 @@ +// @vitest-environment jsdom +/** The connection mirror follows a plugin's Host view and drives its account operations through the plugin's Remote. */ +import { Context } from '@deepseek-ai/cordis' +import type { RemoteStreamOptions } from '@deepseek-ai/dsh-api-gateway/client' +import type { CliAccountView, CliOperationId } from '@deepseek-ai/dsh-cli-account/types' +import { RemoteError, type RemoteResult } from '@deepseek-ai/dsh-typert-protocol' +import { expect, it, onTestFinished, vi } from 'vitest' +import { CliAccountConnection } from '../src/client/connection.ts' + +type View = CliAccountView<{ readonly state: 'out' | 'in' }, 'check' | 'connect' | 'leave', 'authorizing' | 'leaving'> +type Notice = 'connected' | 'left' + +const OP = 'op-1' as CliOperationId +const OUT: View = { account: { state: 'out' } } + +type Operation = NonNullable + +function operation( + kind: Operation['kind'], phase: Operation['phase'], options: { url?: string; cancellable?: boolean; id?: CliOperationId } = {}, +): Operation { + const link = options.url === undefined ? {} : { authorizationUrl: options.url } + return { id: options.id ?? OP, kind, phase, cancellable: options.cancellable ?? false, ...link } +} + +function fixture() { + const queue: View[] = [] + let wake: (() => void) | undefined, closed = false, failure: Error | undefined, accepted = 0 + let options!: RemoteStreamOptions + const open = () => ({ + async *[Symbol.asyncIterator]() { + for (;;) { + if (failure !== undefined) throw failure + if (closed) return + const next = queue.shift() + if (next === undefined) { await new Promise((resolve) => { wake = resolve }); continue } + yield { value: next, accept: () => { accepted++ } } + } + }, + dispose: vi.fn(async () => { closed = true; wake?.() }), + }) + const streams: Array> = [] + const ok = (value: T): RemoteResult => ({ ok: true, value }) + const follow = vi.fn() + const cancel = vi.fn(async (_id: CliOperationId) => ok(undefined)) + const start = vi.fn(async () => ok(OP)) + const ctx = new Context() + ctx.provide('remote', { + $stream: (value: typeof options) => { + options = value + closed = false + failure = undefined + streams.push(open()) + return streams.at(-1) + }, + }) + const windowOpen = vi.spyOn(window, 'open').mockReturnValue(null) + const connection = new CliAccountConnection(ctx, { + name: 'Fixture connection', follow, cancel, notices: { connect: 'connected', leave: 'left' }, + }) + onTestFinished(async () => { await connection.dispose(); windowOpen.mockRestore(); await ctx.fiber.dispose() }) + return { + connection, follow, cancel, start, open: windowOpen, streams, options: () => options, + snapshot: () => connection.state.getSnapshot(), + get stream() { return streams.at(-1)! }, + async publish(view: View) { + const target = accepted + 1 + queue.push(view) + wake?.() + await vi.waitFor(() => { expect(accepted).toBe(target) }) + }, + failOnClose(error: Error) { failure = error }, + fail(error: Error) { failure = error; wake?.() }, + } +} + +const settle = async (b: ReturnType) => { await vi.waitFor(() => { expect(b.snapshot().busy).toBe(false) }) } + +it('mirrors the Host view through the plugin stream', async () => { + const b = fixture() + const signal = new AbortController().signal + void b.options().open(signal) + expect(b.follow).toHaveBeenCalledWith(signal) + expect(b.options().name).toBe('Fixture connection') + expect(b.options().ended(true).message).toBe('Fixture connection stream ended') + await b.publish(OUT) + expect(b.snapshot()).toMatchObject({ view: OUT, linked: true, stopped: false, busy: false }) + b.options().carrierFailed?.(new Error('lost') as never) + expect(b.snapshot().linked).toBe(false) +}) + +it('opens each new link of an operation this browser started once and reports mapped successes', async () => { + const b = fixture() + await b.publish(OUT) + b.connection.start(b.start) + await settle(b) + await b.publish({ ...OUT, operation: operation('connect', 'authorizing', { url: 'https://example.com/a', cancellable: true }) }) + await b.publish({ ...OUT, operation: operation('connect', 'authorizing', { url: 'https://example.com/a', cancellable: true }) }) + expect(b.open.mock.calls).toEqual([['https://example.com/a', '_blank', 'noopener,noreferrer']]) + b.connection.actions.openAuthorization() + expect(b.open).toHaveBeenCalledTimes(2) + await b.publish({ account: { state: 'in' }, result: { id: OP, kind: 'connect', outcome: 'succeeded' } }) + expect(b.snapshot().notice).toEqual({ seq: 1, kind: 'connected' }) + await b.publish({ account: { state: 'in' }, result: { id: OP, kind: 'connect', outcome: 'succeeded' } }) + expect(b.snapshot().notice?.seq).toBe(1) + b.connection.actions.dismissNotice() + expect(b.snapshot().notice).toBeUndefined() +}) + +it('reports no notice for an unmapped kind or an unsuccessful outcome', async () => { + const b = fixture() + b.connection.start(b.start) + await settle(b) + await b.publish({ ...OUT, result: { id: OP, kind: 'check', outcome: 'succeeded' } }) + const SECOND = 'op-2' as CliOperationId + b.connection.start(async () => ({ ok: true, value: SECOND })) + await settle(b) + await b.publish({ ...OUT, result: { id: SECOND, kind: 'connect', outcome: 'failed', failure: { command: 'login', exitCode: 1 } } }) + expect(b.snapshot().notice).toBeUndefined() +}) + +it('opens a link reported before the start answered, never a foreign operation, and only over HTTPS', async () => { + const b = fixture() + const answer = Promise.withResolvers>() + await b.publish({ ...OUT, operation: operation('connect', 'authorizing', { url: 'https://example.com/other', id: 'other' as CliOperationId }) }) + b.connection.start(() => answer.promise) + await b.publish({ ...OUT, operation: operation('connect', 'authorizing', { url: 'https://example.com/device' }) }) + expect(b.open).not.toHaveBeenCalled() + answer.resolve({ ok: true, value: OP }) + await vi.waitFor(() => { expect(b.open).toHaveBeenCalledWith('https://example.com/device', '_blank', 'noopener,noreferrer') }) + await b.publish({ ...OUT, operation: operation('connect', 'authorizing', { url: 'http://example.com/device' }) }) + b.connection.actions.openAuthorization() + await b.publish({ ...OUT, operation: operation('connect', 'authorizing', { url: 'not a url' }) }) + b.connection.actions.openAuthorization() + expect(b.open).toHaveBeenCalledOnce() +}) + +it('cancels only an operation the Host marks cancellable', async () => { + const b = fixture() + b.connection.actions.cancel() + await b.publish({ ...OUT, operation: operation('leave', 'leaving') }) + b.connection.actions.cancel() + b.connection.actions.openAuthorization() + expect(b.cancel).not.toHaveBeenCalled() + await b.publish({ ...OUT, operation: operation('connect', 'authorizing', { cancellable: true }) }) + b.connection.actions.cancel() + await settle(b) + expect(b.cancel).toHaveBeenCalledWith(OP) + expect(b.open).not.toHaveBeenCalled() +}) + +it('reports a failed action once and ignores overlapping clicks', async () => { + const b = fixture() + await b.publish(OUT) + const second = vi.fn(async () => ({ ok: true as const, value: OP })) + b.connection.start(async () => ({ ok: false, error: new RemoteError('gateway/internal', 'offline', {}) }) as never) + b.connection.start(second) + await vi.waitFor(() => { expect(b.snapshot().notice?.kind).toBe('action-failed') }) + expect(second).not.toHaveBeenCalled() +}) + +it('reports nothing after disposal and marks the page stopped when the stream fails', async () => { + const b = fixture() + await b.publish(OUT) + const answer = Promise.withResolvers>() + b.connection.start(() => answer.promise) + b.failOnClose(new Error('closed')) + await b.connection.dispose() + answer.resolve({ ok: false, error: new RemoteError('gateway/internal', 'offline', {}) } as never) + await settle(b) + expect(b.stream.dispose).toHaveBeenCalled() + expect(b.snapshot()).toMatchObject({ linked: true, notice: undefined }) + + const c = fixture() + await c.publish(OUT) + c.fail(new Error('invalid frame')) + await vi.waitFor(() => { expect(c.snapshot()).toMatchObject({ linked: false, stopped: true }) }) +}) + +it('reopens a stopped Host stream on retry and ignores retry while the stream runs', async () => { + const b = fixture() + b.connection.actions.retry() + await b.publish(OUT) + expect(b.streams).toHaveLength(1) + b.fail(new Error('gone')) + await vi.waitFor(() => { expect(b.snapshot().stopped).toBe(true) }) + b.connection.actions.retry() + await vi.waitFor(() => { expect(b.streams).toHaveLength(2) }) + expect(b.snapshot()).toMatchObject({ view: undefined, stopped: false }) + await b.publish(OUT) + expect(b.snapshot()).toMatchObject({ view: OUT, linked: true }) + + await b.connection.dispose() + b.connection.actions.retry() + expect(b.streams).toHaveLength(2) +}) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index b37136b414..a1dfeba114 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -3985,6 +3985,9 @@ importers: '@deepseek-ai/dsh-client-store': specifier: workspace:* version: link:../store + '@deepseek-ai/dsh-client-test-runtime': + specifier: workspace:* + version: link:../../test-support/client-runtime '@deepseek-ai/dsh-client-ui-plugin-manager': specifier: workspace:* version: link:../ui-plugin-manager @@ -3997,6 +4000,9 @@ importers: '@deepseek-ai/dsh-typert-protocol': specifier: workspace:* version: link:../../typert/protocol + '@testing-library/react': + specifier: ^16.3.3 + version: 16.3.3(@testing-library/dom@10.4.2)(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) '@types/react': specifier: ~18.3.1 version: 18.3.31