diff --git a/packages/client/ui-feishu/README.i18n.yaml b/packages/client/ui-feishu/README.i18n.yaml index f54f6e3d1f..f34f68f853 100644 --- a/packages/client/ui-feishu/README.i18n.yaml +++ b/packages/client/ui-feishu/README.i18n.yaml @@ -18,11 +18,11 @@ en: fa34bf7d74d487d6 zh: ed0389c337dd8ccb /deepseek-ai-dsh-client-ui-feishu/understand-the-implementation: - en: d973647652293ad2 - zh: 7929da8c49a23e28 + en: d875b1c00b46e2e7 + zh: a2b0335529d44126 /deepseek-ai-dsh-client-ui-feishu/further-exploration: - en: 06bea154fccda185 - zh: a862d7d255e8d9d3 + en: 3cf75e280f2a7c4d + zh: 9075ab4e72c926f7 /deepseek-ai-dsh-client-ui-feishu/model-experience: en: 012af7ceabf177e8 zh: f1ed31e734d6ba78 diff --git a/packages/client/ui-feishu/README.md b/packages/client/ui-feishu/README.md index 2c15090970..68a7bbd9fd 100644 --- a/packages/client/ui-feishu/README.md +++ b/packages/client/ui-feishu/README.md @@ -48,9 +48,9 @@ Leaving the page does not cancel a connection, which the Host owns. Each step op
Implementation internals — click to expand -The Host half, [`src/index.ts`](src/index.ts), is an empty `apply`, present only so the package holds the Loader row the client module system serves the browser half for. The browser half, [`src/client/index.ts`](src/client/index.ts), mounts the `feishu` Remote itself with `ctx.remote.$mount`, because the shipped Remote assembly does not include on-demand packages, and withdraws its registrations before unmounting it. +The Host half, [`src/index.ts`](src/index.ts), is an empty `apply`, present only so the package holds the Loader row the client module system serves the browser half for. The browser half, [`src/client/index.ts`](src/client/index.ts), mounts the `feishu` Remote itself with `ctx.remote.$mount`, because the shipped Remote assembly does not include on-demand packages, and withdraws its account registration before unmounting it. -[`src/client/connection.ts`](src/client/connection.ts) creates one `CliAccountConnection` from the [CLI plugin page pieces](../ui-cli-account/README.md) per browser plugin over the `feishu` Remote, and derives the page state from the Host's view alone. That connection opens a link only for the operation this browser started, only once, and only over HTTPS. [`src/client/FeishuConnection.tsx`](src/client/FeishuConnection.tsx) renders the shared section, tag, activation prompt, confirmations, and toast with the Feishu actions; the Web shell supplies the shared library as a platform module, so this package's bundle does not include it. It registers `plugins.bundle.config` keyed by `@deepseek-ai/dsh-feishu` for the section, `plugins.bundle.activation` for the guidance, `plugins.detail.badge` for the tag, and a `shell.overlay` toast. The page's copy, including the keys the shared pieces read, lives in this package's `feishu` dictionary. +The browser half registers the Feishu account with the [CLI account surfaces](../ui-cli-account/README.md) through `ctx.cliAccounts`, which follow the `feishu` Remote and render the section, tag, activation prompt, confirmations, and toast for `@deepseek-ai/dsh-feishu`. A link opens only for the operation this browser started, only once, and only over HTTPS. [`src/client/connection.ts`](src/client/connection.ts) derives the connection state from the Host's view alone, and [`src/client/account.ts`](src/client/account.ts) maps it to the section's buttons, linked app, confirmations, and failure guidance. The page's copy, including the keys the shared surfaces read, lives in this package's `feishu` dictionary.
@@ -61,8 +61,8 @@ The Host half, [`src/index.ts`](src/index.ts), is an empty `apply`, present only - [Feishu plugin](../../connector/feishu/README.md) — the bundle that inserts this row and the Host row. - [Feishu CLI and skills](../../connector/feishu-cli/README.md) — the Host row and the account operations this page drives. -- [CLI plugin page pieces](../ui-cli-account/README.md) — the shared connection mirror and components this page renders. -- [ui-plugin-manager](../ui-plugin-manager/README.md) — the Plugins page and the bundle slots the page registers into. +- [CLI account surfaces](../ui-cli-account/README.md) — the registry that follows the Remote and renders this page's account. +- [ui-plugin-manager](../ui-plugin-manager/README.md) — the Plugins page and the bundle slots the account surfaces fill. ----- diff --git a/packages/client/ui-feishu/README.zh.md b/packages/client/ui-feishu/README.zh.md index 3238397d9c..774bc9e1e1 100644 --- a/packages/client/ui-feishu/README.zh.md +++ b/packages/client/ui-feishu/README.zh.md @@ -48,9 +48,9 @@ kind: "package-reference"
实现内部机制——点击展开 -Host 半部 [`src/index.ts`](src/index.ts) 是空的 `apply`,只为让本包持有一行 Loader 条目,客户端模块系统据此提供浏览器半部。浏览器半部 [`src/client/index.ts`](src/client/index.ts) 用 `ctx.remote.$mount` 自行挂载 `feishu` Remote,因为随产品发布的 Remote 集合不包含按需安装的包;卸载 Remote 之前会先撤下自己的注册。 +Host 半部 [`src/index.ts`](src/index.ts) 是空的 `apply`,只为让本包持有一行 Loader 条目,客户端模块系统据此提供浏览器半部。浏览器半部 [`src/client/index.ts`](src/client/index.ts) 用 `ctx.remote.$mount` 自行挂载 `feishu` Remote,因为随产品发布的 Remote 集合不包含按需安装的包;卸载 Remote 之前会先撤下账号注册。 -[`src/client/connection.ts`](src/client/connection.ts) 为每个浏览器插件基于 `feishu` Remote 创建一个来自 [CLI 插件页组件](../ui-cli-account/README.zh.md)的 `CliAccountConnection`,只根据 Host 的视图推导页面状态。该连接只为本浏览器发起的操作打开链接,每个链接只打开一次,且只打开 HTTPS 链接。[`src/client/FeishuConnection.tsx`](src/client/FeishuConnection.tsx) 用飞书的操作渲染共用的区块、标签、开启引导、确认框和提示;Web 外壳以平台模块提供这个共用库,因此本包的 bundle 不包含它。它以 `@deepseek-ai/dsh-feishu` 为 key 注册 `plugins.bundle.config` 作为区块,注册 `plugins.bundle.activation` 作为引导、`plugins.detail.badge` 作为标签,以及一个 `shell.overlay` 提示。页面文案,包括共用组件读取的键,位于本包的 `feishu` 词典。 +浏览器半部通过 `ctx.cliAccounts` 把飞书账号注册到 [CLI 账号界面](../ui-cli-account/README.zh.md),由它跟随 `feishu` Remote,并为 `@deepseek-ai/dsh-feishu` 渲染区块、标签、开启引导、确认框和提示。链接只为本浏览器发起的操作打开,每个链接只打开一次,且只打开 HTTPS 链接。[`src/client/connection.ts`](src/client/connection.ts) 只根据 Host 的视图推导连接状态,[`src/client/account.ts`](src/client/account.ts) 再把它映射为区块的按钮、已关联应用、确认框和失败建议。页面文案,包括共用界面读取的键,位于本包的 `feishu` 词典。
@@ -61,8 +61,8 @@ Host 半部 [`src/index.ts`](src/index.ts) 是空的 `apply`,只为让本包 - [飞书插件](../../connector/feishu/README.zh.md)——插入本行与 Host 行的 bundle。 - [飞书 CLI 与技能](../../connector/feishu-cli/README.zh.md)——Host 行,以及本页面发起的账号操作。 -- [CLI 插件页组件](../ui-cli-account/README.zh.md)——本页面渲染的共用连接镜像与组件。 -- [ui-plugin-manager](../ui-plugin-manager/README.zh.md)——插件页,以及本页面注册进的 bundle slot。 +- [CLI 账号界面](../ui-cli-account/README.zh.md)——跟随 Remote 并渲染本页面账号的注册表。 +- [ui-plugin-manager](../ui-plugin-manager/README.zh.md)——插件页,以及账号界面填入的 bundle slot。 ----- diff --git a/packages/client/ui-feishu/package.json b/packages/client/ui-feishu/package.json index d921ea5326..c5818fd86c 100644 --- a/packages/client/ui-feishu/package.json +++ b/packages/client/ui-feishu/package.json @@ -38,8 +38,7 @@ "inject": [ "@deepseek-ai/dsh-api-remotes", "@deepseek-ai/dsh-client-locale", - "@deepseek-ai/dsh-client-ui-layout", - "@deepseek-ai/dsh-client-ui-plugin-manager" + "@deepseek-ai/dsh-client-ui-cli-account" ], "platform": "web" } @@ -53,22 +52,14 @@ }, "devDependencies": { "@deepseek-ai/cordis": "workspace:~", - "@deepseek-ai/dsh-api-gateway": "workspace:*", "@deepseek-ai/dsh-api-remotes": "workspace:*", "@deepseek-ai/dsh-cli-account": "workspace:*", "@deepseek-ai/dsh-client-locale": "workspace:*", - "@deepseek-ai/dsh-client-store": "workspace:*", "@deepseek-ai/dsh-client-test-runtime": "workspace:*", "@deepseek-ai/dsh-client-ui-cli-account": "workspace:*", - "@deepseek-ai/dsh-client-ui-layout": "workspace:*", - "@deepseek-ai/dsh-client-ui-plugin-manager": "workspace:*", - "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", "@deepseek-ai/dsh-client-ui-slots": "workspace:*", "@deepseek-ai/dsh-feishu-cli": "workspace:*", "@deepseek-ai/dsh-typert-protocol": "workspace:*", - "@deepseek-ai/dsh-util-values": "workspace:*", - "@testing-library/react": "^16.3.3", - "react": "^18.2.0", - "react-dom": "^18.2.0" + "@deepseek-ai/dsh-util-values": "workspace:*" } } diff --git a/packages/client/ui-feishu/src/client/FeishuConnection.tsx b/packages/client/ui-feishu/src/client/FeishuConnection.tsx deleted file mode 100644 index 295e8fa55a..0000000000 --- a/packages/client/ui-feishu/src/client/FeishuConnection.tsx +++ /dev/null @@ -1,108 +0,0 @@ -/** Feishu connection surfaces on the Plugins page: the bundle section, title tag, activation guidance, and notices. */ -import { useState, type ReactNode } from 'react' -import { - CliAccountActivation, CliAccountBadge, CliAccountConfirm, CliAccountSection, CliAccountToast, type CliAccountAction, -} from '@deepseek-ai/dsh-client-ui-cli-account' -import type { InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' -import type {} from '@deepseek-ai/dsh-client-ui-plugin-manager/client' -import { FEISHU_PACKAGE, presentConnection, type ConnectionFace } from './connection.ts' -import type { NS } from './locales.ts' - -type FaceProps = InjectFace & PropsLocale - -/** - * The connection section on the Feishu bundle's page. - * @param props - the shared connection face and the Feishu dictionary. - * @returns the status line, its actions, and the sign-out confirmation. - */ -export function FeishuConnectionSection(props: FaceProps): ReactNode { - const { useFeishuConnection, check, linkApp, signIn, cancel, signOut, openAuthorization, retry, t } = props - const snapshot = useFeishuConnection(value => value) - const [confirming, setConfirming] = useState<'sign-out' | 'replace-app' | undefined>(undefined) - const shown = presentConnection(snapshot) - const actions: CliAccountAction[] = [] - let status: string | undefined - let detail: string | undefined - switch (shown.phase) { - case 'disconnected': - actions.push(shown.next === 'link-app' - ? { label: t('action.linkApp'), onClick: linkApp, variant: 'primary' } - : { label: t('action.signIn'), onClick: signIn, variant: 'primary' }) - detail = t(shown.next === 'link-app' ? 'detail.no-app' : 'detail.signed-out') - break - case 'unavailable': actions.push({ label: t('action.retry'), onClick: check }); detail = t('detail.unavailable'); break - case 'stopped': actions.push({ label: t('action.retry'), onClick: retry }); detail = t('detail.stopped'); break - case 'connected': - actions.push({ label: t('action.signOut'), onClick: () => { setConfirming('sign-out') } }) - detail = shown.userName === undefined ? t('detail.connected') : t('detail.connectedAs', { name: shown.userName }) - break - case 'connecting': - status = t(`step.${shown.step}`) - if (shown.url !== undefined) { - actions.push({ label: t('action.open'), onClick: openAuthorization, variant: 'primary' }) - if (shown.step === 'configuring' || shown.step === 'authorizing') detail = t(`detail.${shown.step}`) - } - if (shown.cancellable) actions.push({ label: t('action.cancel'), onClick: cancel, variant: 'ghost' }) - break - case 'checking': break - } - const close = (): void => { setConfirming(undefined) } - return ( - { setConfirming('replace-app') }, variant: 'ghost' } }] - : []} - failure={'failed' in shown && shown.failed !== undefined ? { - text: t(shown.failed.kind === 'link-app' ? 'failed.linkApp' : 'failed'), - command: shown.failed.failure, - details: [shown.failed.failure?.type, shown.failed.failure?.subtype], - } : undefined}> - - - - ) -} - -/** - * The connection tag beside the Feishu bundle's title. - * @param props - the open detail page's subject, the connection face, and the dictionary. - * @returns the tag for the Feishu bundle, or null on any other page. - */ -export function FeishuConnectionBadge({ subject, useFeishuConnection, t }: FaceProps & PropsRuntime<'plugins.detail.badge'>): ReactNode { - const phase = useFeishuConnection(value => presentConnection(value).phase) - return -} - -/** - * Guidance after the user switches the Feishu bundle on while the account is not connected. - * @param props - activation callbacks, the connection face, and the dictionary. - * @returns a dismissible prompt that starts the connection from the bundle's page. - */ -export function FeishuConnectionActivation(props: FaceProps & PropsRuntime<'plugins.bundle.activation'>): ReactNode { - const { useFeishuConnection, linkApp, signIn, onDismiss, onOpenDetails, t } = props - const phase = useFeishuConnection(value => presentConnection(value).phase) - const next = useFeishuConnection((value) => { - const shown = presentConnection(value) - return shown.phase === 'disconnected' ? shown.next : undefined - }) - return ( - { - onOpenDetails() - if (next === 'sign-in') signIn() - else linkApp() - }} /> - ) -} - -/** - * Connection outcomes reported outside the Plugins panel's lifetime. - * @param props - the shared notice, its dismissal, and the dictionary. - * @returns the toast for the latest notice, or null. - */ -export function FeishuConnectionToast({ useFeishuConnection, dismissNotice, t }: FaceProps): ReactNode { - const notice = useFeishuConnection(value => value.notice) - return -} diff --git a/packages/client/ui-feishu/src/client/account.ts b/packages/client/ui-feishu/src/client/account.ts new file mode 100644 index 0000000000..e050285266 --- /dev/null +++ b/packages/client/ui-feishu/src/client/account.ts @@ -0,0 +1,73 @@ +/** The Feishu account section: the buttons, rows, and failure the Plugins page shows for each connection state. */ +import type { CliAccountAction, CliAccountDisplay, CliAccountPage } from '@deepseek-ai/dsh-client-ui-cli-account/client' +import type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots' +import { presentConnection, type ConnectionSnapshot } from './connection.ts' +import type { NS } from './locales.ts' + +/** The page actions and the Feishu Remote operations the section's buttons call. */ +export interface FeishuActions extends CliAccountPage { + /** Check the account again. */ + readonly check: () => void + /** Link an app, replacing a configured one after the page confirms it. */ + readonly linkApp: () => void + /** Sign the linked app's user in. */ + readonly signIn: () => void + readonly signOut: () => void +} + +/** + * The connection section for one page snapshot. + * @param snapshot - the Host's view and the page state. + * @param t - the Feishu dictionary. + * @param actions - what the section's buttons call. + * @returns the phase, step, buttons, detail, linked app, and failure. + */ +export function presentAccount(snapshot: ConnectionSnapshot, t: TranslateNS, actions: FeishuActions): CliAccountDisplay { + const shown = presentConnection(snapshot) + const buttons: CliAccountAction[] = [] + let status: string | undefined + let detail: string | undefined + switch (shown.phase) { + case 'disconnected': + buttons.push(shown.next === 'link-app' + ? { label: t('action.linkApp'), onClick: actions.linkApp, variant: 'primary' } + : { label: t('action.signIn'), onClick: actions.signIn, variant: 'primary' }) + detail = t(shown.next === 'link-app' ? 'detail.no-app' : 'detail.signed-out') + break + case 'unavailable': buttons.push({ label: t('action.retry'), onClick: actions.check }); detail = t('detail.unavailable'); break + case 'stopped': buttons.push({ label: t('action.retry'), onClick: actions.retry }); detail = t('detail.stopped'); break + case 'connected': + buttons.push({ + label: t('action.signOut'), onClick: actions.signOut, + confirm: { title: t('signOut.title'), body: t('signOut.body'), label: t('action.signOut') }, + }) + detail = shown.userName === undefined ? t('detail.connected') : t('detail.connectedAs', { name: shown.userName }) + break + case 'connecting': + status = t(`step.${shown.step}`) + if (shown.url !== undefined) { + buttons.push({ label: t('action.open'), onClick: actions.openAuthorization, variant: 'primary' }) + if (shown.step === 'configuring' || shown.step === 'authorizing') detail = t(`detail.${shown.step}`) + } + if (shown.cancellable) buttons.push({ label: t('action.cancel'), onClick: actions.cancel, variant: 'ghost' }) + break + case 'checking': break + } + return { + phase: shown.phase, status, actions: buttons, detail, + notes: 'appId' in shown + ? [{ + text: t('app.linked', { id: shown.appId }), + action: { + label: t('action.replaceApp'), onClick: actions.linkApp, variant: 'ghost', + confirm: { title: t('replaceApp.title'), body: t('replaceApp.body'), label: t('action.replaceApp') }, + }, + }] + : [], + failure: 'failed' in shown && shown.failed !== undefined ? { + text: t(shown.failed.kind === 'link-app' ? 'failed.linkApp' : 'failed'), + command: shown.failed.failure, + details: [shown.failed.failure?.type, shown.failed.failure?.subtype], + } : undefined, + } +} diff --git a/packages/client/ui-feishu/src/client/connection.ts b/packages/client/ui-feishu/src/client/connection.ts index d4d1693e50..4cf65791f2 100644 --- a/packages/client/ui-feishu/src/client/connection.ts +++ b/packages/client/ui-feishu/src/client/connection.ts @@ -1,19 +1,13 @@ -/** Browser mirror of the Host's Feishu account and the Plugins page's connection actions. */ -import type { Context } from '@deepseek-ai/cordis' -import type {} from '@deepseek-ai/dsh-api-remotes/client' -import { CliAccountConnection, type CliAccountSnapshot } from '@deepseek-ai/dsh-client-ui-cli-account' -import type { HostObservable } from '@deepseek-ai/dsh-client-ui-slots' +/** The Feishu connection the Plugins page shows, derived from the Host's account view. */ +import type { CliAccountSnapshot } from '@deepseek-ai/dsh-client-ui-cli-account/client' import type { FeishuAppId, FeishuState } from '@deepseek-ai/dsh-feishu-cli/types' import { assertNever } from '@deepseek-ai/dsh-util-values' /** The npm package whose bundle page carries the connection section. */ export const FEISHU_PACKAGE = '@deepseek-ai/dsh-feishu' -/** Outcomes the page reports after an operation this browser started succeeds. */ -export type FeishuNotice = 'app-linked' | 'connected' | 'signed-out' - /** The page's whole view: the Host's account view plus this browser's stream, pending action, and notice. */ -export type ConnectionSnapshot = CliAccountSnapshot +export type ConnectionSnapshot = CliAccountSnapshot /** The step a connection or sign-out in progress shows. */ export type ConnectionStep = 'configuring' | 'authorizing' | 'connecting' | 'signing-out' @@ -32,23 +26,6 @@ export type ConnectionPresentation = readonly cancellable: boolean } -/** Page-facing actions and the snapshot hook the slot entries inject. */ -export interface ConnectionFace { - hooks: { feishuConnection: HostObservable } - /** Check the account again. */ - check(): void - /** Link an app, replacing a configured one after the page confirms it. */ - linkApp(): void - /** Sign the linked app's user in. */ - signIn(): void - cancel(): void - signOut(): void - openAuthorization(): void - /** Reopen the Host stream after it stopped. */ - retry(): void - dismissNotice(): void -} - function step(phase: Exclude['phase'], 'checking'>): ConnectionStep { switch (phase) { case 'configuring': @@ -91,26 +68,3 @@ export function presentConnection(snapshot: Pick; face: ConnectionFace } { - const connection = new CliAccountConnection(ctx, { - name: 'Feishu connection', - follow: signal => ctx.remote.feishu.follow(signal), - cancel: id => ctx.remote.feishu.cancel(id), - notices: { 'link-app': 'app-linked', 'sign-in': 'connected', 'sign-out': 'signed-out' }, - }) - const face: ConnectionFace = { - hooks: { feishuConnection: connection.state }, - check: () => { connection.start(() => ctx.remote.feishu.check()) }, - linkApp: () => { connection.start(() => ctx.remote.feishu.linkApp()) }, - signIn: () => { connection.start(() => ctx.remote.feishu.signIn()) }, - signOut: () => { connection.start(() => ctx.remote.feishu.signOut()) }, - ...connection.actions, - } - return { connection, face } -} diff --git a/packages/client/ui-feishu/src/client/index.ts b/packages/client/ui-feishu/src/client/index.ts index cb44793f21..71c8427b47 100644 --- a/packages/client/ui-feishu/src/client/index.ts +++ b/packages/client/ui-feishu/src/client/index.ts @@ -1,50 +1,48 @@ /** - * Feishu plugin, browser half: the connection section on the Feishu bundle's - * page, the tag beside its title, guidance after the bundle is switched on, and - * connection notices. The Host's `feishu` Remote owns the account operations; - * this half mounts that Remote itself because the on-demand package stays out - * of the shipped Remote assembly. + * Feishu plugin, browser half: registers the Feishu account with the Plugins + * page's CLI account surfaces. The Host's `feishu` Remote owns the account + * operations; this half mounts that Remote itself because the on-demand + * package stays out of the shipped Remote assembly. */ import type { Context } from '@deepseek-ai/cordis' import type {} from '@deepseek-ai/dsh-api-remotes/client' import type {} from '@deepseek-ai/dsh-client-locale/client' -import type {} from '@deepseek-ai/dsh-client-ui-layout/client' -import type {} from '@deepseek-ai/dsh-client-ui-plugin-manager/client' -import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' +import type {} from '@deepseek-ai/dsh-client-ui-cli-account/client' import feishuRemote from '@deepseek-ai/dsh-feishu-cli/remote' -import { FEISHU_PACKAGE, createConnection } from './connection.ts' +import type { FeishuState } from '@deepseek-ai/dsh-feishu-cli/types' +import { presentAccount } from './account.ts' +import { FEISHU_PACKAGE } from './connection.ts' import { de, en, es, fr, ja, NS, pt, ru, zh } from './locales.ts' -import { FeishuConnectionActivation, FeishuConnectionBadge, FeishuConnectionSection, FeishuConnectionToast } from './FeishuConnection.tsx' -/** Services the Remote mount and the slot registrations need. */ -export const inject = ['remote', 'slots', 'locale'] +/** Services the Remote mount and the account registration need. */ +export const inject = ['remote', 'locale', 'cliAccounts'] function registerUi(ctx: Context): void { ctx.effect(() => ctx.locale.register(NS, { zh, en, ja, es, fr, de, ru, pt }), 'feishu: dictionaries') - const { connection, face } = createConnection(ctx) - ctx.effect(() => async () => { await connection.dispose() }, 'feishu: connection') - ctx.slots.inject('plugins.bundle.config', () => ctx.slots.register({ - name: 'plugins.bundle.config', key: FEISHU_PACKAGE, locale: NS, inject: () => face, - }, FeishuConnectionSection)) - ctx.slots.inject('plugins.bundle.activation', () => ctx.slots.register({ - name: 'plugins.bundle.activation', key: FEISHU_PACKAGE, locale: NS, inject: () => face, - }, FeishuConnectionActivation)) - ctx.slots.inject('plugins.detail.badge', () => ctx.slots.register({ - name: 'plugins.detail.badge', id: 'feishu.connection', locale: NS, inject: () => face, - }, FeishuConnectionBadge)) - ctx.slots.inject('shell.overlay', () => ctx.slots.register({ - name: 'shell.overlay', id: 'feishu.connection-toast', locale: NS, inject: () => face, - }, FeishuConnectionToast)) + const t = ctx.locale.bind(NS) + ctx.effect(() => ctx.cliAccounts.register({ + packageName: FEISHU_PACKAGE, locale: NS, + follow: signal => ctx.remote.feishu.follow(signal), + cancel: id => ctx.remote.feishu.cancel(id), + notices: { 'link-app': () => t('notice.app-linked'), 'sign-in': () => t('notice.connected'), 'sign-out': () => t('notice.signed-out') }, + present: (snapshot, page) => presentAccount(snapshot, t, { + ...page, + check: () => { page.start(() => ctx.remote.feishu.check()) }, + linkApp: () => { page.start(() => ctx.remote.feishu.linkApp()) }, + signIn: () => { page.start(() => ctx.remote.feishu.signIn()) }, + signOut: () => { page.start(() => ctx.remote.feishu.signOut()) }, + }), + }), 'feishu: account') } /** - * Mount the Feishu Remote, then register the connection surfaces for as long as the Feishu row is on. + * Mount the Feishu Remote, then register the account for as long as the Feishu row is on. * @param ctx - the browser plugin context. - * @returns a disposer that withdraws the surfaces, then the Remote. + * @returns a disposer that withdraws the account, then the Remote. */ export async function apply(ctx: Context): Promise<() => Promise> { const disposeRemote = await ctx.remote.$mount(feishuRemote) - const ui = ctx.inject(['remote.feishu', 'slots', 'locale'], registerUi) + const ui = ctx.inject(['remote.feishu', 'locale', 'cliAccounts'], registerUi) try { await ui } catch (error) { diff --git a/packages/client/ui-feishu/tests/account.client.spec.ts b/packages/client/ui-feishu/tests/account.client.spec.ts new file mode 100644 index 0000000000..b4f2d851fd --- /dev/null +++ b/packages/client/ui-feishu/tests/account.client.spec.ts @@ -0,0 +1,131 @@ +/** The Feishu section offers each state's next step, the linked app, confirmations, and failure guidance. */ +import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' +import type { CliOperationId } from '@deepseek-ai/dsh-cli-account/types' +import type { CliAccountAction, CliAccountDisplay } from '@deepseek-ai/dsh-client-ui-cli-account/client' +import type { FeishuAppId, FeishuState } from '@deepseek-ai/dsh-feishu-cli/types' +import { expect, it, vi } from 'vitest' +import { presentAccount, type FeishuActions } from '../src/client/account.ts' +import type { ConnectionSnapshot } from '../src/client/connection.ts' +import { en, zh } from '../src/client/locales.ts' + +const OP = 'op' as CliOperationId +const APP = 'cli_a' as FeishuAppId + +function fixture(copy: typeof zh = zh) { + const actions: FeishuActions = { + start: vi.fn(), cancel: vi.fn(), openAuthorization: vi.fn(), retry: vi.fn(), + check: vi.fn(), linkApp: vi.fn(), signIn: vi.fn(), signOut: vi.fn(), + } + const show = (view: FeishuState | undefined, page: Partial = {}): CliAccountDisplay => + presentAccount({ view, linked: true, stopped: false, busy: false, notice: undefined, ...page }, makeTranslate(copy), actions) + return { actions, show } +} + +const labels = (display: CliAccountDisplay): string[] => (display.actions ?? []).map(action => action.label) +const action = (display: CliAccountDisplay, label: string): CliAccountAction => { + const found = [...display.actions ?? [], ...(display.notes ?? []).flatMap(note => note.action ?? [])].find(item => item.label === label) + if (found === undefined) throw new Error(`no ${label} action`) + return found +} +const text = (key: keyof typeof zh, values: Record = {}) => + Object.entries(values).reduce((value, [name, replacement]) => value.replace(`{${name}}`, replacement), zh[key]) + +it('offers the next step for each state', () => { + const b = fixture() + let shown = b.show({ account: { state: 'unconfigured' } }) + expect(shown).toMatchObject({ phase: 'disconnected', detail: zh['detail.no-app'], notes: [] }) + action(shown, zh['action.linkApp']).onClick() + expect(b.actions.linkApp).toHaveBeenCalledOnce() + + shown = b.show({ account: { state: 'unconfigured' }, operation: { id: OP, kind: 'link-app', phase: 'configuring', cancellable: true } }) + expect(shown).toMatchObject({ phase: 'connecting', status: zh['step.configuring'] }) + expect(labels(shown)).toEqual([zh['action.cancel']]) + + shown = b.show({ account: { state: 'signed-out', appId: APP } }) + expect(shown.detail).toBe(zh['detail.signed-out']) + action(shown, zh['action.signIn']).onClick() + expect(b.actions.signIn).toHaveBeenCalledOnce() + + shown = b.show({ account: { state: 'signed-out', appId: APP }, operation: { id: OP, kind: 'sign-in', phase: 'authorizing', cancellable: true, authorizationUrl: 'https://x.feishu.cn' } }) + expect(shown.detail).toBe(zh['detail.authorizing']) + action(shown, zh['action.open']).onClick() + action(shown, zh['action.cancel']).onClick() + expect(b.actions.openAuthorization).toHaveBeenCalledOnce() + expect(b.actions.cancel).toHaveBeenCalledOnce() + + shown = b.show({ account: { state: 'signed-out', appId: APP }, operation: { id: OP, kind: 'sign-out', phase: 'signing-out', cancellable: false, authorizationUrl: 'https://x.feishu.cn' } }) + expect(shown).toMatchObject({ status: zh['step.signing-out'], detail: undefined }) + expect(labels(shown)).toEqual([zh['action.open']]) + + shown = b.show({ account: { state: 'unverified', appId: APP } }) + expect(shown.detail).toBe(zh['detail.unavailable']) + action(shown, zh['action.retry']).onClick() + expect(b.actions.check).toHaveBeenCalledOnce() + + shown = b.show(undefined) + expect(shown).toMatchObject({ phase: 'checking', actions: [], notes: [] }) +}) + +it.each([['zh', zh], ['en', en]] as const)('reports app-link recovery with its safe diagnostics in %s', (_locale, copy) => { + const b = fixture(copy) + let shown = b.show({ + account: { state: 'unconfigured' }, + result: { id: OP, kind: 'link-app', outcome: 'failed', failure: { command: 'config-init', exitCode: 1, type: 'internal', subtype: 'sdk_error' } }, + }) + expect(labels(shown)).toEqual([copy['action.linkApp']]) + expect(shown.failure).toEqual({ + text: copy['failed.linkApp'], + command: { command: 'config-init', exitCode: 1, type: 'internal', subtype: 'sdk_error' }, + details: ['internal', 'sdk_error'], + }) + + shown = b.show({ account: { state: 'signed-out', appId: APP }, result: { id: OP, kind: 'link-app', outcome: 'failed', failure: { command: 'auth-status', exitCode: null } } }) + expect(labels(shown)).toEqual([copy['action.signIn']]) + expect(shown.failure).toEqual({ text: copy['failed.linkApp'], command: { command: 'auth-status', exitCode: null }, details: [undefined, undefined] }) + + shown = b.show({ account: { state: 'unconfigured' }, result: { id: OP, kind: 'link-app', outcome: 'cancelled' } }) + expect(shown.failure).toBeUndefined() +}) + +it.each(['sign-in', 'sign-out', 'check'] as const)('keeps the generic guidance for a failed %s', (kind) => { + const shown = fixture().show({ account: { state: 'signed-out', appId: APP }, result: { id: OP, kind, outcome: 'failed' } }) + expect(shown.failure?.text).toBe(zh.failed) +}) + +it('explains a stopped Host component and reopens the stream', () => { + const b = fixture() + const shown = b.show(undefined, { linked: false, stopped: true }) + expect(shown).toMatchObject({ phase: 'stopped', detail: zh['detail.stopped'] }) + action(shown, zh['action.retry']).onClick() + expect(b.actions.retry).toHaveBeenCalledOnce() +}) + +it('shows who is signed in and asks before signing out', () => { + const b = fixture() + expect(b.show({ account: { state: 'connected', appId: APP, userName: '张三' } }).detail).toBe(text('detail.connectedAs', { name: '张三' })) + const shown = b.show({ account: { state: 'connected', appId: APP } }) + expect(shown.detail).toBe(zh['detail.connected']) + const signOut = action(shown, zh['action.signOut']) + expect(signOut.confirm).toEqual({ title: zh['signOut.title'], body: zh['signOut.body'], label: zh['action.signOut'] }) + signOut.onClick() + expect(b.actions.signOut).toHaveBeenCalledOnce() +}) + +it('shows the linked app and asks before changing it', () => { + const b = fixture() + const shown = b.show({ account: { state: 'signed-out', appId: APP } }) + expect(shown.notes?.map(note => note.text)).toEqual([text('app.linked', { id: 'cli_a' })]) + const replace = action(shown, zh['action.replaceApp']) + expect(replace).toMatchObject({ variant: 'ghost', confirm: { title: zh['replaceApp.title'], body: zh['replaceApp.body'], label: zh['action.replaceApp'] } }) + replace.onClick() + expect(b.actions.linkApp).toHaveBeenCalledOnce() +}) + +it.each<[string, FeishuState, keyof FeishuActions]>([ + ['links an app first', { account: { state: 'unconfigured' } }, 'linkApp'], + ['signs in to a linked app', { account: { state: 'signed-out', appId: APP } }, 'signIn'], +])('answers the activation prompt with its next step: %s', (_name, state, step) => { + const b = fixture() + const primary = b.show(state).actions?.filter(item => item.variant === 'primary' && item.confirm === undefined) + expect(primary?.map(item => item.onClick)).toEqual([b.actions[step]]) +}) diff --git a/packages/client/ui-feishu/tests/components.client.spec.tsx b/packages/client/ui-feishu/tests/components.client.spec.tsx deleted file mode 100644 index e7b45cf5af..0000000000 --- a/packages/client/ui-feishu/tests/components.client.spec.tsx +++ /dev/null @@ -1,209 +0,0 @@ -// @vitest-environment jsdom -/** The connection section, title tag, activation guidance, and notices render the Host view the page mirrors. */ -import type { ComponentProps } from 'react' -import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' -import { bindSnapshotSelector, makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' -import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' -import type { PluginPackageRef, PluginsSubject } from '@deepseek-ai/dsh-client-ui-plugin-manager/client' -import { afterEach, expect, it, vi } from 'vitest' -import type { ConnectionSnapshot } from '../src/client/connection.ts' -import { en, zh } from '../src/client/locales.ts' -import { - FeishuConnectionActivation, FeishuConnectionBadge, FeishuConnectionSection, FeishuConnectionToast, -} from '../src/client/FeishuConnection.tsx' -import type { CliOperationId } from '@deepseek-ai/dsh-cli-account/types' -import type { FeishuAppId, FeishuState } from '@deepseek-ai/dsh-feishu-cli/types' - -afterEach(cleanup) - -const OP = 'op' as CliOperationId -const APP = 'cli_a' as FeishuAppId - -function fixture(view?: FeishuState, copy: typeof zh = zh) { - const state = createSnapshotStore({ view, linked: true, stopped: false, busy: false, notice: undefined }) - const face = { - useFeishuConnection: bindSnapshotSelector(state), - check: vi.fn(), linkApp: vi.fn(), signIn: vi.fn(), cancel: vi.fn(), signOut: vi.fn(), - openAuthorization: vi.fn(), retry: vi.fn(), dismissNotice: vi.fn(), - t: makeTranslate(copy), - } - return { face, set: (change: Partial) => { act(() => { state.set({ ...state.getSnapshot(), ...change }) }) } } -} - -const button = (name: string) => screen.getByRole('button', { name }) -const text = (key: keyof typeof zh, values: Record = {}) => - Object.entries(values).reduce((value, [name, replacement]) => value.replace(`{${name}}`, replacement), zh[key]) - -it('offers the next step for each state', () => { - const b = fixture({ account: { state: 'unconfigured' } }) - render() - expect(screen.getByText(zh['detail.no-app'])).toBeTruthy() - expect(screen.getByText(zh.hint)).toBeTruthy() - fireEvent.click(button(zh['action.linkApp'])) - expect(b.face.linkApp).toHaveBeenCalledOnce() - - b.set({ view: { account: { state: 'unconfigured' }, operation: { id: OP, kind: 'link-app', phase: 'configuring', cancellable: true } } }) - expect(screen.getByText(zh['step.configuring'])).toBeTruthy() - expect(screen.queryByRole('button', { name: zh['action.open'] })).toBeNull() - b.set({ view: { account: { state: 'signed-out', appId: APP } } }) - expect(screen.getByText(zh['detail.signed-out'])).toBeTruthy() - fireEvent.click(button(zh['action.signIn'])) - expect(b.face.signIn).toHaveBeenCalledOnce() - - b.set({ view: { account: { state: 'signed-out', appId: APP }, operation: { id: OP, kind: 'sign-in', phase: 'authorizing', cancellable: true, authorizationUrl: 'https://x.feishu.cn' } } }) - expect(screen.getByText(zh['detail.authorizing'])).toBeTruthy() - fireEvent.click(button(zh['action.open'])) - fireEvent.click(button(zh['action.cancel'])) - expect(b.face.openAuthorization).toHaveBeenCalledOnce() - expect(b.face.cancel).toHaveBeenCalledOnce() - - b.set({ view: { account: { state: 'signed-out', appId: APP }, operation: { id: OP, kind: 'sign-out', phase: 'signing-out', cancellable: false, authorizationUrl: 'https://x.feishu.cn' } } }) - expect(screen.getByText(zh['step.signing-out'])).toBeTruthy() - expect(screen.queryByRole('button', { name: zh['action.cancel'] })).toBeNull() - expect(document.querySelector('[data-cli-account="connecting"] p')?.textContent).toBe(zh.hint) - - b.set({ view: { account: { state: 'signed-out', appId: APP }, result: { id: OP, kind: 'sign-in', outcome: 'failed' } } }) - expect(screen.getByRole('alert').textContent).toBe(zh.failed) - - b.set({ view: { account: { state: 'unverified', appId: APP } } }) - expect(screen.getByText(zh['detail.unavailable'])).toBeTruthy() - fireEvent.click(button(zh['action.retry'])) - expect(b.face.check).toHaveBeenCalledOnce() - - b.set({ view: undefined }) - expect(screen.getByText(zh['status.checking'])).toBeTruthy() - expect(screen.queryAllByRole('button')).toHaveLength(0) -}) - -it.each([['zh', zh], ['en', en]] as const)('reports app-link recovery and safe diagnostics in %s', async (locale, copy) => { - const b = fixture({ - account: { state: 'unconfigured' }, - result: { - id: OP, kind: 'link-app', outcome: 'failed', - failure: { command: 'config-init', exitCode: 1, type: 'internal', subtype: 'sdk_error' }, - }, - }, copy) - render() - expect(button(copy['action.linkApp'])).toBeTruthy() - await expect(`${screen.getByRole('alert').textContent}\n`).toMatchFileSnapshot(`./expected/link-app-failed-${locale}.txt`) - - b.set({ view: { account: { state: 'signed-out', appId: APP }, result: { - id: OP, kind: 'link-app', outcome: 'failed', failure: { command: 'auth-status', exitCode: null }, - } } }) - expect(button(copy['action.signIn'])).toBeTruthy() - expect(screen.getByRole('alert').textContent).toBe(`${copy['failed.linkApp']} ${copy['failure.details'].replace('{details}', 'auth-status')}`) - - b.set({ view: { account: { state: 'unconfigured' }, result: { id: OP, kind: 'link-app', outcome: 'failed' } } }) - expect(screen.getByRole('alert').textContent).toBe(copy['failed.linkApp']) - b.set({ view: { account: { state: 'unconfigured' }, result: { id: OP, kind: 'link-app', outcome: 'cancelled' } } }) - expect(screen.queryByRole('alert')).toBeNull() -}) - -it.each(['sign-in', 'sign-out', 'check'] as const)('keeps the generic notice for a failed %s', (kind) => { - const b = fixture({ account: { state: 'signed-out', appId: APP }, result: { id: OP, kind, outcome: 'failed' } }) - render() - expect(screen.getByRole('alert').textContent).toBe(zh.failed) -}) - -it('explains a stopped Host component and retries even while the stream is offline', () => { - const b = fixture(undefined) - render() - b.set({ linked: false, stopped: true }) - expect(screen.getByText(zh['status.stopped'])).toBeTruthy() - expect(screen.getByText(zh['detail.stopped'])).toBeTruthy() - fireEvent.click(button(zh['action.retry'])) - expect(b.face.retry).toHaveBeenCalledOnce() - b.set({ busy: true }) - expect((button(zh['action.retry']) as HTMLButtonElement).disabled).toBe(true) -}) - -it('shows who is signed in and signs out only after confirmation', () => { - const b = fixture({ account: { state: 'connected', appId: APP, userName: '张三' } }) - render() - expect(screen.getByText(text('detail.connectedAs', { name: '张三' }))).toBeTruthy() - b.set({ view: { account: { state: 'connected', appId: APP } } }) - expect(screen.getByText(zh['detail.connected'])).toBeTruthy() - fireEvent.click(button(zh['action.signOut'])) - expect(screen.getByText(zh['signOut.body'])).toBeTruthy() - fireEvent.click(button(zh['action.cancel'])) - fireEvent.click(button(zh['action.signOut'])) - fireEvent.click(button(zh.close)) - expect(b.face.signOut).not.toHaveBeenCalled() - fireEvent.click(button(zh['action.signOut'])) - fireEvent.click(screen.getAllByRole('button', { name: zh['action.signOut'] }).at(-1)!) - expect(b.face.signOut).toHaveBeenCalledOnce() -}) - -it('shows the linked app and changes it only after confirmation', () => { - const b = fixture({ account: { state: 'unconfigured' } }) - render() - expect(screen.queryByRole('button', { name: zh['action.replaceApp'] })).toBeNull() - b.set({ view: { account: { state: 'signed-out', appId: APP } } }) - expect(screen.getByText(text('app.linked', { id: 'cli_a' }))).toBeTruthy() - fireEvent.click(button(zh['action.replaceApp'])) - expect(screen.getByText(zh['replaceApp.body'])).toBeTruthy() - fireEvent.click(button(zh['action.cancel'])) - fireEvent.click(button(zh['action.replaceApp'])) - fireEvent.click(button(zh.close)) - expect(b.face.linkApp).not.toHaveBeenCalled() - fireEvent.click(button(zh['action.replaceApp'])) - fireEvent.click(screen.getAllByRole('button', { name: zh['action.replaceApp'] }).at(-1)!) - expect(b.face.linkApp).toHaveBeenCalledOnce() -}) - -it('disables actions while one is pending or the Host stream is offline', () => { - const b = fixture({ account: { state: 'unconfigured' } }) - render() - b.set({ busy: true }) - expect(button(zh['action.linkApp']).hasAttribute('disabled')).toBe(true) - b.set({ busy: false, linked: false }) - expect(button(zh['action.linkApp']).hasAttribute('disabled')).toBe(true) -}) - -it('tags only the enabled Feishu bundle', () => { - const b = fixture({ account: { state: 'connected', appId: APP } }) - const pkg = (name: string, enabled = true): PluginPackageRef => ({ name, installed: true, availability: 'profile', official: false, enabled, rows: [] }) - const badge = (subject: PluginsSubject) => - } /> - const { rerender } = render(badge({ kind: 'bundle', pkg: pkg('@deepseek-ai/dsh-feishu') })) - expect(screen.getByText(zh['badge.connected'])).toBeTruthy() - b.set({ view: { account: { state: 'unverified', appId: APP } } }) - expect(screen.getByText(zh['badge.unavailable'])).toBeTruthy() - b.set({ view: undefined }) - expect(document.body.textContent).toBe('') - b.set({ view: { account: { state: 'signed-out', appId: APP } } }) - rerender(badge({ kind: 'bundle', pkg: pkg('@deepseek-ai/dsh-feishu', false) })) - expect(document.body.textContent).toBe('') - rerender(badge({ kind: 'bundle', pkg: pkg('@acme/other') })) - expect(document.body.textContent).toBe('') - rerender(badge({ kind: 'item', id: 'shell' })) - expect(document.body.textContent).toBe('') -}) - -it.each<[string, FeishuState, 'linkApp' | 'signIn']>([ - ['links an app first', { account: { state: 'unconfigured' } }, 'linkApp'], - ['signs in to a linked app', { account: { state: 'signed-out', appId: APP } }, 'signIn'], -])('guides a newly enabled bundle to its next step: %s, and steps aside once connected', (_name, state, step) => { - const b = fixture() - const onDismiss = vi.fn(), onOpenDetails = vi.fn() - const props = { ...b.face, packageName: '@deepseek-ai/dsh-feishu', onDismiss, onOpenDetails } as ComponentProps - render() - expect(screen.queryByText(zh['activation.body'])).toBeNull() - b.set({ view: state }) - fireEvent.click(button(zh['action.connect'])) - expect(onOpenDetails).toHaveBeenCalledOnce() - expect(b.face[step]).toHaveBeenCalledOnce() - expect(onDismiss).not.toHaveBeenCalled() - b.set({ view: { account: { state: 'connected', appId: APP } } }) - expect(onDismiss).toHaveBeenCalledOnce() -}) - -it('reports the latest notice', () => { - const b = fixture() - render() - expect(document.body.textContent).toBe('') - b.set({ notice: { seq: 1, kind: 'signed-out' } }) - expect(screen.getByText(zh['notice.signed-out'])).toBeTruthy() - b.set({ notice: { seq: 2, kind: 'action-failed' } }) - expect(screen.getByText(zh['notice.action-failed'])).toBeTruthy() -}) diff --git a/packages/client/ui-feishu/tests/connection.client.spec.ts b/packages/client/ui-feishu/tests/connection.client.spec.ts index 2910d967cf..0593c880ba 100644 --- a/packages/client/ui-feishu/tests/connection.client.spec.ts +++ b/packages/client/ui-feishu/tests/connection.client.spec.ts @@ -1,12 +1,8 @@ -// @vitest-environment jsdom -/** The page derives the Feishu connection from the Host's view and drives account operations through its Remote. */ -import { Context } from '@deepseek-ai/cordis' -import type { RemoteStreamOptions } from '@deepseek-ai/dsh-api-gateway/client' +/** The page derives the Feishu connection from the Host's view. */ import type { CliOperationId } from '@deepseek-ai/dsh-cli-account/types' import type { FeishuAppId, FeishuState } from '@deepseek-ai/dsh-feishu-cli/types' -import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' -import { expect, it, onTestFinished, vi } from 'vitest' -import { createConnection, presentConnection, type ConnectionPresentation, type ConnectionStep } from '../src/client/connection.ts' +import { expect, it } from 'vitest' +import { presentConnection, type ConnectionPresentation, type ConnectionStep } from '../src/client/connection.ts' type Operation = NonNullable @@ -43,106 +39,3 @@ it.each<[string, FeishuState | undefined, ConnectionPresentation]>([ ])('presents %s', (name, view, expected) => { expect(presentConnection({ view, stopped: name === 'a stopped stream' })).toEqual(expected) }) - -function fixture() { - const queue: FeishuState[] = [] - let wake: (() => void) | undefined, closed = false, accepted = 0 - let options!: RemoteStreamOptions - const ok = (value: T): RemoteResult => ({ ok: true, value }) - const remote = { - follow: vi.fn(), - check: vi.fn(async () => ok(OP)), - linkApp: vi.fn(async () => ok(OP)), - signIn: vi.fn(async () => ok(OP)), - signOut: vi.fn(async () => ok(OP)), - cancel: vi.fn(async (_id: CliOperationId) => ok(undefined)), - } - const ctx = new Context() - ctx.provide('remote', { - feishu: remote, - $stream: (value: typeof options) => { - options = value - return { - async *[Symbol.asyncIterator]() { - for (;;) { - if (closed) return - const next = queue.shift() - if (next === undefined) { await new Promise((resolve) => { wake = resolve }); continue } - yield { value: next, accept: () => { accepted++ } } - } - }, - dispose: async () => { closed = true; wake?.() }, - } - }, - }) - const windowOpen = vi.spyOn(window, 'open').mockReturnValue(null) - const { connection, face } = createConnection(ctx) - onTestFinished(async () => { await connection.dispose(); windowOpen.mockRestore(); await ctx.fiber.dispose() }) - return { - face, remote, open: windowOpen, options: () => options, - snapshot: () => connection.state.getSnapshot(), - async publish(view: FeishuState) { - const target = accepted + 1 - queue.push(view) - wake?.() - await vi.waitFor(() => { expect(accepted).toBe(target) }) - }, - } -} - -const settle = async (b: ReturnType) => { await vi.waitFor(() => { expect(b.snapshot().busy).toBe(false) }) } - -it('follows the feishu Remote and exposes the mirror to the page', async () => { - const b = fixture() - const signal = new AbortController().signal - b.options().open(signal) - expect(b.remote.follow).toHaveBeenCalledWith(signal) - await b.publish(SIGNED_OUT) - expect(b.face.hooks.feishuConnection.getSnapshot()).toMatchObject({ view: SIGNED_OUT, linked: true, busy: false }) -}) - -it('links an app and signs in through the Remote, opening each link and reporting each finished step', async () => { - const b = fixture() - const NO_APP: FeishuState = { account: { state: 'unconfigured' } } - await b.publish(NO_APP) - b.face.linkApp() - await settle(b) - expect(b.remote.linkApp).toHaveBeenCalledOnce() - await b.publish({ ...NO_APP, operation: operation('link-app', 'configuring', true, 'https://open.feishu.cn/app') }) - expect(b.open.mock.calls.map(call => call[0])).toEqual(['https://open.feishu.cn/app']) - await b.publish({ ...SIGNED_OUT, result: { id: OP, kind: 'link-app', outcome: 'succeeded' } }) - expect(b.snapshot().notice).toEqual({ seq: 1, kind: 'app-linked' }) - - const SIGN_IN = 'op-2' as CliOperationId - b.remote.signIn.mockResolvedValueOnce({ ok: true, value: SIGN_IN }) - b.face.signIn() - await settle(b) - await b.publish({ ...SIGNED_OUT, operation: operation('sign-in', 'authorizing', true, 'https://accounts.feishu.cn/device', SIGN_IN) }) - expect(b.open.mock.calls.map(call => call[0])).toEqual(['https://open.feishu.cn/app', 'https://accounts.feishu.cn/device']) - await b.publish({ account: { state: 'connected', appId: APP }, result: { id: SIGN_IN, kind: 'sign-in', outcome: 'succeeded' } }) - expect(b.snapshot().notice).toEqual({ seq: 2, kind: 'connected' }) -}) - -it('checks again without a notice', async () => { - const b = fixture() - await b.publish({ account: { state: 'unverified', appId: APP } }) - b.face.check() - await settle(b) - expect(b.remote.check).toHaveBeenCalledOnce() - await b.publish({ ...SIGNED_OUT, result: { id: OP, kind: 'check', outcome: 'succeeded' } }) - expect(b.snapshot().notice).toBeUndefined() -}) - -it('signs out with a notice and cancels a cancellable sign-in through the Remote', async () => { - const b = fixture() - await b.publish({ account: { state: 'connected', appId: APP } }) - b.face.signOut() - await settle(b) - expect(b.remote.signOut).toHaveBeenCalledOnce() - await b.publish({ account: { state: 'signed-out', appId: APP }, result: { id: OP, kind: 'sign-out', outcome: 'succeeded' } }) - expect(b.snapshot().notice?.kind).toBe('signed-out') - await b.publish({ ...SIGNED_OUT, operation: operation('sign-in', 'authorizing', true) }) - b.face.cancel() - await settle(b) - expect(b.remote.cancel).toHaveBeenCalledWith(OP) -}) diff --git a/packages/client/ui-feishu/tests/expected/link-app-failed-en.txt b/packages/client/ui-feishu/tests/expected/link-app-failed-en.txt deleted file mode 100644 index 5b10fbebd8..0000000000 --- a/packages/client/ui-feishu/tests/expected/link-app-failed-en.txt +++ /dev/null @@ -1 +0,0 @@ -Feishu app linking did not finish. If the Feishu page reported success, check DSH access to local configuration and system credentials, then choose the existing app when linking again. Diagnostic: config-init · Exit code 1 · internal · sdk_error diff --git a/packages/client/ui-feishu/tests/expected/link-app-failed-zh.txt b/packages/client/ui-feishu/tests/expected/link-app-failed-zh.txt deleted file mode 100644 index 73e69941a2..0000000000 --- a/packages/client/ui-feishu/tests/expected/link-app-failed-zh.txt +++ /dev/null @@ -1 +0,0 @@ -飞书应用关联未完成。若飞书页面已显示成功,请检查 DSH 对本机配置与系统凭据的访问权限,再次关联时请选择已有应用 排障信息:config-init · 退出码 1 · internal · sdk_error diff --git a/packages/client/ui-feishu/tests/mount.client.spec.ts b/packages/client/ui-feishu/tests/mount.client.spec.ts index b98161bbd7..201d1df91d 100644 --- a/packages/client/ui-feishu/tests/mount.client.spec.ts +++ b/packages/client/ui-feishu/tests/mount.client.spec.ts @@ -1,65 +1,82 @@ -/** The browser half mounts the Feishu Remote, registers its surfaces, and withdraws both on disposal or failure. */ +/** The browser half mounts the Feishu Remote, registers its account, and withdraws both on disposal or failure. */ import { Context, Service } from '@deepseek-ai/cordis' +import type { CliOperationId } from '@deepseek-ai/dsh-cli-account/types' import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' -import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client' +import type { CliAccountPage, CliAccountRegistration } from '@deepseek-ai/dsh-client-ui-cli-account/client' +import type { FeishuState } from '@deepseek-ai/dsh-feishu-cli/types' import type { TypertRemoteContribution } from '@deepseek-ai/dsh-typert-protocol' import { expect, it, vi } from 'vitest' import { apply as hostApply } from '../src/index.ts' -import { FeishuConnectionActivation, FeishuConnectionBadge, FeishuConnectionSection, FeishuConnectionToast } from '../src/client/FeishuConnection.tsx' +import { en } from '../src/client/locales.ts' const REMOTE: TypertRemoteContribution = { package: '@deepseek-ai/dsh-feishu-cli', descriptors: [] } -const SLOTS = [ - ['plugins.bundle.config', FeishuConnectionSection], - ['plugins.bundle.activation', FeishuConnectionActivation], - ['plugins.detail.badge', FeishuConnectionBadge], - ['shell.overlay', FeishuConnectionToast], -] as const +const OP = 'op' as CliOperationId async function fixture() { const ctx = new Context() const unmount = vi.fn(async () => {}) - const dispose = vi.fn(async () => {}) + const remote = { + follow: vi.fn(), cancel: vi.fn(), check: vi.fn(), linkApp: vi.fn(), signIn: vi.fn(), signOut: vi.fn(), + } class Remote extends Service { constructor() { super(ctx, 'remote') } async $mount(contribution: TypertRemoteContribution) { expect(contribution).toBe(REMOTE) - ctx.provide('remote.feishu', { follow: vi.fn() }) + ctx.provide('remote.feishu', remote) return unmount } - $stream() { - return { async *[Symbol.asyncIterator]() { /* the Host reports nothing in this composition */ }, dispose } - } } new Remote() - ctx.provide('locale', new LocaleRuntime(ctx)) - await ctx.plugin(SlotRegistry) - ctx.slots.register({ name: 'root', children: { - 'plugins.bundle.activation': { kind: 'keyed', scope: 'root' }, - 'plugins.bundle.config': { kind: 'keyed', scope: 'root' }, - 'plugins.detail.badge': { kind: 'list', scope: 'root' }, - 'shell.overlay': { kind: 'list', scope: 'root' }, - } } as never, () => null) + const locale = new LocaleRuntime(ctx) + ctx.provide('locale', locale) + const unregister = vi.fn() + const register = vi.fn((_account: CliAccountRegistration) => unregister) + ctx.provide('cliAccounts', { register }) vi.doMock('@deepseek-ai/dsh-feishu-cli/remote', () => ({ default: REMOTE })) const browser = await import('../src/client/index.ts') - return { ctx, unmount, dispose, browser } + return { ctx, locale, unmount, remote, register, unregister, browser } } -it('registers the connection surfaces with one shared face, then withdraws them and the Remote', async () => { +it('registers the Feishu account over its Remote, then withdraws it and the Remote', async () => { hostApply() const b = await fixture() try { const fiber = b.ctx.plugin({ inject: [...b.browser.inject], apply: b.browser.apply }) await fiber - const faces = SLOTS.map(([slot, component]) => { - const [entry] = b.ctx.slots.entries(slot) - expect(entry).toMatchObject({ locale: 'feishu', component }) - return entry!.inject!() - }) - expect(new Set(faces.map(face => face.hooks)).size).toBe(1) - expect(b.ctx.slots.entries('plugins.bundle.config')[0]!.options.key).toBe('@deepseek-ai/dsh-feishu') + b.locale.setLocale('en') + expect(b.register).toHaveBeenCalledOnce() + const account = b.register.mock.calls[0]![0] + expect(account).toMatchObject({ packageName: '@deepseek-ai/dsh-feishu', locale: 'feishu' }) + const signal = new AbortController().signal + void account.follow(signal) + void account.cancel(OP) + expect(b.remote.follow).toHaveBeenCalledWith(signal) + expect(b.remote.cancel).toHaveBeenCalledWith(OP) + expect(account.notices['link-app']?.()).toBe(en['notice.app-linked']) + expect(account.notices['sign-in']?.()).toBe(en['notice.connected']) + expect(account.notices['sign-out']?.()).toBe(en['notice.signed-out']) + expect(account.notices.check).toBeUndefined() + + const page: CliAccountPage = { start: vi.fn((call) => { void call() }), cancel: vi.fn(), openAuthorization: vi.fn(), retry: vi.fn() } + const snapshot = { linked: true, stopped: false, busy: false, notice: undefined } + const press = (view: FeishuState, label: string) => { + const display = account.present({ ...snapshot, view }, page) + const notes = (display.notes ?? []).flatMap(note => note.action ?? []) + const found = [...display.actions ?? [], ...notes].find(item => item.label === label) + expect(found).toBeDefined() + found!.onClick() + } + press({ account: { state: 'unconfigured' } }, en['action.linkApp']) + press({ account: { state: 'signed-out', appId: 'cli_a' as never } }, en['action.signIn']) + press({ account: { state: 'unverified', appId: 'cli_a' as never } }, en['action.retry']) + press({ account: { state: 'connected', appId: 'cli_a' as never } }, en['action.signOut']) + expect(b.remote.linkApp).toHaveBeenCalledOnce() + expect(b.remote.signIn).toHaveBeenCalledOnce() + expect(b.remote.check).toHaveBeenCalledOnce() + expect(b.remote.signOut).toHaveBeenCalledOnce() + await fiber.dispose() - for (const [slot] of SLOTS) expect(b.ctx.slots.entries(slot)).toHaveLength(0) - expect(b.dispose).toHaveBeenCalledOnce() + expect(b.unregister).toHaveBeenCalledOnce() expect(b.unmount).toHaveBeenCalledOnce() } finally { await b.ctx.fiber.dispose() @@ -67,11 +84,11 @@ it('registers the connection surfaces with one shared face, then withdraws them } }) -it('withdraws the Remote when the surfaces fail to register', async () => { +it('withdraws the Remote when the account fails to register', async () => { const b = await fixture() - vi.spyOn(b.ctx.slots, 'inject').mockImplementationOnce(() => { throw new Error('slot failed') }) + b.register.mockImplementationOnce(() => { throw new Error('register failed') }) try { - await expect(b.browser.apply(b.ctx)).rejects.toThrow('slot failed') + await expect(b.browser.apply(b.ctx)).rejects.toThrow('register failed') expect(b.unmount).toHaveBeenCalledOnce() } finally { await b.ctx.fiber.dispose() diff --git a/packages/client/ui-feishu/tsconfig.json b/packages/client/ui-feishu/tsconfig.json index f61f48e00a..964c908bc1 100644 --- a/packages/client/ui-feishu/tsconfig.json +++ b/packages/client/ui-feishu/tsconfig.json @@ -11,27 +11,12 @@ { "path": "../../../vendor/cordis" }, - { - "path": "../../api/gateway/tsconfig.client.json" - }, { "path": "../../api/remotes/tsconfig.client.json" }, { "path": "../locale/tsconfig.client.json" }, - { - "path": "../store" - }, - { - "path": "../ui-layout" - }, - { - "path": "../ui-plugin-manager/tsconfig.client.json" - }, - { - "path": "../ui-renderer" - }, { "path": "../ui-slots" }, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index dcab5078cd..5b98fff2da 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -4536,9 +4536,6 @@ importers: '@deepseek-ai/cordis': specifier: workspace:~ version: link:../../../vendor/cordis - '@deepseek-ai/dsh-api-gateway': - specifier: workspace:* - version: link:../../api/gateway '@deepseek-ai/dsh-api-remotes': specifier: workspace:* version: link:../../api/remotes @@ -4548,24 +4545,12 @@ importers: '@deepseek-ai/dsh-client-locale': specifier: workspace:* version: link:../locale - '@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-cli-account': specifier: workspace:* version: link:../ui-cli-account - '@deepseek-ai/dsh-client-ui-layout': - specifier: workspace:* - version: link:../ui-layout - '@deepseek-ai/dsh-client-ui-plugin-manager': - specifier: workspace:* - version: link:../ui-plugin-manager - '@deepseek-ai/dsh-client-ui-renderer': - specifier: workspace:* - version: link:../ui-renderer '@deepseek-ai/dsh-client-ui-slots': specifier: workspace:* version: link:../ui-slots @@ -4578,15 +4563,6 @@ importers: '@deepseek-ai/dsh-util-values': specifier: workspace:* version: link:../../util/values - '@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) - react: - specifier: ^18.2.0 - version: 18.3.1 - react-dom: - specifier: ^18.2.0 - version: 18.3.1(react@18.3.1) packages/client/ui-file-actions: devDependencies: